파이썬 Tkinter 가볍게 시작하기
2줄의 코드로 시작합니다.
from tkinter import *
Tk().mainloop()
임포트 문에 *을 사용하는 것은 일반적으론 추천되지 않습니다.
하지만, GUI 프로그래밍에는 임포트할 것들이 너무 많습니다.
파이썬 공식 tkinter 문서에도 *가 사용됩니다.
GUI 객체와 루프를 돌려주는 메서드만 있으면 창을 볼 수 있습니다.
코드를 나눠볼까요?
from tkinter import *
root = Tk()
root.mainloop()
Tk 클래스에서 root라는 인스턴스를 만들고,
root 인스턴스의 루핑 메서드를 실행합니다.
root 인스턴스 설정
from tkinter import *
root = Tk()
root.title('컴닥')
root.geometry('640x480')
root.mainloop()
root 창(인스턴스)에 몇 가지 속성(타이틀, 크기)을 설정해 줍니다.
점점 그럴듯해집니다.
image
이제 이미지를 하나 올려보겠습니다.
* JPEG 파일은 직접 지원하지 않으니 PNG나 GIF를 이용합니다.
* Pillow 모듈을 이용하면 JPEG파일을 불러올 수 있습니다.
from tkinter import *
root = Tk()
root.title('컴닥')
root.geometry('640x480')
image = PhotoImage(file='test.png') # jpeg 파일은 지원하지 않습니다.
label = Label(root, image=image)
label.pack()
root.mainloop()
Label의 첫번째 인자는 부모(?) 객체(창, 프레임 등)입니다.
옵션 확인
라벨에는 어떤 옵션들이 있는 지 궁금해집니다.
이럴 때는 config() 메서드를 사용하면 됩니다.
from tkinter import *
print(Label().config())
{'activebackground': ('activebackground', 'activeBackground', 'Foreground', <string object: 'SystemButtonFace'>, 'SystemButtonFace'), 'activeforeground': ('activeforeground', 'activeForeground', 'Background', <string object: 'SystemButtonText'>, 'SystemButtonText'), 'anchor': ('anchor', 'anchor', 'Anchor', <string object: 'center'>, 'center'), 'background': ('background', 'background', 'Background', <string object: 'SystemButtonFace'>, 'SystemButtonFace'), 'bd': ('bd', '-borderwidth'), 'bg': ('bg', '-background'), 'bitmap': ('bitmap', 'bitmap', 'Bitmap', '', ''), 'borderwidth': ('borderwidth', 'borderWidth', 'BorderWidth', <string object: '2'>, <string object: '2'>), 'compound': ('compound', 'compound', 'Compound', <string object: 'none'>, 'none'), 'cursor': ('cursor', 'cursor', 'Cursor', '', ''), 'disabledforeground': ('disabledforeground', 'disabledForeground', 'DisabledForeground', <string object: 'SystemDisabledText'>, 'SystemDisabledText'), 'fg': ('fg', '-foreground'), 'font': ('font', 'font', 'Font', <string object: 'TkDefaultFont'>, 'TkDefaultFont'), 'foreground': ('foreground', 'foreground', 'Foreground', <string object: 'SystemButtonText'>, 'SystemButtonText'), 'height': ('height', 'height', 'Height', 0, 0), 'highlightbackground': ('highlightbackground', 'highlightBackground', 'HighlightBackground', <string object: 'SystemButtonFace'>, 'SystemButtonFace'), 'highlightcolor': ('highlightcolor', 'highlightColor', 'HighlightColor', <string object: 'SystemWindowFrame'>, 'SystemWindowFrame'), 'highlightthickness': ('highlightthickness', 'highlightThickness', 'HighlightThickness', <string object: '0'>, <string object: '0'>), 'image': ('image', 'image', 'Image', '', ''), 'justify': ('justify', 'justify', 'Justify', <string object: 'center'>, 'center'), 'padx': ('padx', 'padX', 'Pad', <string object: '1'>, <string object: '1'>), 'pady': ('pady', 'padY', 'Pad', <string object: '1'>, <string object: '1'>), 'relief': ('relief', 'relief', 'Relief', <string object: 'flat'>, 'flat'), 'state': ('state', 'state', 'State', <string object: 'normal'>, 'normal'), 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '0', '0'), 'text': ('text', 'text', 'Text', '', ''), 'textvariable': ('textvariable', 'textVariable', 'Variable', '', ''), 'underline': ('underline', 'underline', 'Underline', -1, -1), 'width': ('width', 'width', 'Width', 0, 0), 'wraplength': ('wraplength', 'wrapLength', 'WrapLength', <string object: '0'>, <string object: '0'>)}
조금 정신이 없지만 확인이 가능합니다.
위 값은 딕셔너리니까, 키만 확인 하는 것도 괜찮을 것 같습니다.
from tkinter import *
print(Label().config().keys())
dict_keys(['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'compound', 'cursor', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'padx', 'pady', 'relief', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength'])
깔끔하네요.
relief(부조)라는 옵션을 써보고 싶습니다.
부조, 浮彫 (명사미술•공예)
어떤 형상을 평평한 면에 도드라지게 새기는 기법.
relief 옵션을 확인해도 별 내용은 없습니다.
from tkinter import *
print(Label().config()['relief'])
(기본값이 'flat' 인 것은 알 수 있습니다.)
('relief', 'relief', 'Relief', <string object: 'flat'>, 'flat')
자세한 것은 구글 검색이나
아래 'tkinter 정리가 잘 되어 있는 블로그'를 참고하시면 됩니다.
relief='sunken'을 걸어줍니다.
from tkinter import *
root = Tk()
root.title('컴닥')
root.geometry('640x480')
image = PhotoImage(file='test.png') # jpeg 파일은 지원하지 않습니다.
label = Label(root, image=image, relief='sunken')
label.pack()
root.mainloop()
라벨(그림)주위의 그림자(?)를 볼 수 있습니다.
쏙 들어간 느낌을 주네요.
relief 옵션들을 확인해 보았습니다.
from tkinter import *
root = Tk()
b1 = Button(root, text='FLAT', relief=FLAT)
b1.pack()
b2 = Button(root, text='RAISED', relief=RAISED)
b2.pack()
b3 = Button(root, text='SUNKEN', relief=SUNKEN)
b3.pack()
b4 = Button(root, text='GROOVE', relief=GROOVE)
b4.pack()
b5 = Button(root, text='RIDGE', relief=RIDGE)
b5.pack()
b6 = Button(root, text='SOLID', relief=SOLID)
b6.pack()
root.mainloop()
대문자로 사용할 수도 있습니다.
'constants.py'에 정의되어 있기 때문입니다.
# Python\Python310-32\Lib\tkinter\constants.py
# Symbolic constants for Tk
# Booleans
NO=FALSE=OFF=0
YES=TRUE=ON=1
# -anchor and -sticky
N='n'
S='s'
W='w'
E='e'
NW='nw'
SW='sw'
NE='ne'
SE='se'
NS='ns'
EW='ew'
NSEW='nsew'
CENTER='center'
# -fill
NONE='none'
X='x'
Y='y'
BOTH='both'
# -side
LEFT='left'
TOP='top'
RIGHT='right'
BOTTOM='bottom'
# -relief
RAISED='raised'
SUNKEN='sunken'
FLAT='flat'
RIDGE='ridge'
GROOVE='groove'
SOLID = 'solid'
# -orient
HORIZONTAL='horizontal'
VERTICAL='vertical'
# -tabs
NUMERIC='numeric'
# -wrap
CHAR='char'
WORD='word'
# -align
BASELINE='baseline'
# -bordermode
INSIDE='inside'
OUTSIDE='outside'
# Special tags, marks and insert positions
SEL='sel'
SEL_FIRST='sel.first'
SEL_LAST='sel.last'
END='end'
INSERT='insert'
CURRENT='current'
ANCHOR='anchor'
ALL='all' # e.g. Canvas.delete(ALL)
# Text widget and button states
NORMAL='normal'
DISABLED='disabled'
ACTIVE='active'
# Canvas state
HIDDEN='hidden'
# Menu item types
CASCADE='cascade'
CHECKBUTTON='checkbutton'
COMMAND='command'
RADIOBUTTON='radiobutton'
SEPARATOR='separator'
# Selection modes for list boxes
SINGLE='single'
BROWSE='browse'
MULTIPLE='multiple'
EXTENDED='extended'
# Activestyle for list boxes
# NONE='none' is also valid
DOTBOX='dotbox'
UNDERLINE='underline'
# Various canvas styles
PIESLICE='pieslice'
CHORD='chord'
ARC='arc'
FIRST='first'
LAST='last'
BUTT='butt'
PROJECTING='projecting'
ROUND='round'
BEVEL='bevel'
MITER='miter'
# Arguments to xview/yview
MOVETO='moveto'
SCROLL='scroll'
UNITS='units'
PAGES='pages'
수고하셨습니다.
* 참고: 예제로 배우는 파이썬 프로그래밍
예제로 배우는 파이썬 프로그래밍 - Tkinter 소개
1. Tkinter 소개 Tkinter는 Tcl/Tk에 대한 파이썬 Wrapper로서 Tcl/Tk를 파이썬에 사용할 수 있도록 한 Lightweight GUI 모듈이다. Tcl은 Tool Command Language의 약자로서 일종의 프로그래밍 언어이며, Tk는 크로스 플
pythonstudy.xyz
* 참고: tkinter 정리가 잘 되어 있는 블로그
tkinter 공부하기 좋은 블로그
tkinter 공부하기 좋은 블로그를 찾았습니다. 추천~! Python-tkinter PYTHON TKINTER 강좌 : 제 31강 – SEPARATOR - [0 COMMENTS]2018-06-18 PYTHON TKINTER 강좌 : 제 30강 – TREEVIEW - [2 COMMENTS]2018-06..
comdoc.tistory.com
* 좋은 내용
Python,tkinter 입문
Python, tkinter 간단히 사용하기 001 python3.2.2 >> 간단한 창띄우기 << 1 2 3 4 5 # -*- c...
blog.naver.com
영어의 압박이 있지만..
TkDocs Home
Tk is the only cross-platform (Windows, Mac, Unix) graphical user interface toolkit designed exclusively for high-level dynamic languages, like Python, Tcl, Ruby, Perl, and many others. Whatever language you use, this site brings you the current, high-qual
tkdocs.com