python에서 gui를 사용하기 위해서 Tkinter라는 것을 사용한다고 한다. 그 외에도 Turtle과 같은 모듈을 받아서 쓸 수 있지만 각종 버튼 등의 기능이나 동작이 있는 프로그램을 만들기 위해서 사용하는 것으로 보인다
실제 사용하는 방법은 아래와 같다
# manual Link : https://docs.python.org/3/library/tkinter.html
#import tkinter
# 위처럼 사용하면 tkinter를 매번 다시 입력하는 경우, 아래처럼 사용하는 경우 tkinter를 안 쓸 수 있음
from tkinter import *
window = Tk()
# 윈도우 창의 타이틀 변경
window.title("Test")
# 윈도우 가로, 세로 길이 조절
window.minsize(width=500, height=400)
# Label 만들고 중앙 상단에 배치
label = Label(text="Test label", font=("Arial", 20, "italic"))
# Label 을 사용 가능한 화면을 가득 채우는 형식으로 배치. 화면 정중앙에 배치되는 것으로 보인다
#label.pack(expand=True)
label.pack()
# Label 배치를 하단에 하는 경우
#label.pack(side="bottom")
# label의 속성 중 text를 초기화한 형태에서 아래 2가지 형태로 값을 바꿀 수 있다.
label["text"] = "New Text"
label.config(text="New Text")
# Button
def button_clicked():
print("Button Click")
input_text = input_entry.get()
label.config(text=input_text)
# text에 버튼에 표시할 텍스트, command에 버튼 콜백 함수 연결
button = Button(text="Click Text", command=button_clicked)
# Label과 마찬가지로 세팅하고 동작
button.pack()
#Entry (input 필드를 만들고 width를 10)
input_entry = Entry(width=10)
input_entry.pack()
# input 필드에서 입력한 스트링 가져오기
print(input_entry.get())
# 윈도우 창이 닫히지 않게 해줌. 해당 호출이 없으면 실행 후 바로 꺼진다
window.mainloop()
그 외에 Tkinter에는
- Text 박스
- Spinbox
- Scale
- Checkbutton
- Radiobutton
- listbox
와 같은 기능들이 존재한다
아래의 예시 코드는 현재 공부하고 있는 udemy 강좌에 있는 코드의 예시로 각 기능들을 사용하는 방법을 보여주고 있고, 나중에 참고삼아 다시 볼 기회가 있을 듯 싶어서 적어둔다
#Text
text = Text(height=5, width=30)
#Puts cursor in textbox.
text.focus()
#Adds some text to begin with.
text.insert(END, "Example of multi-line text entry.")
#Get's current value in textbox at line 1, character 0
print(text.get("1.0", END))
text.pack()
#Spinbox
def spinbox_used():
#gets the current value in spinbox.
print(spinbox.get())
spinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used)
spinbox.pack()
#Scale
#Called with current scale value.
def scale_used(value):
print(value)
scale = Scale(from_=0, to=100, command=scale_used)
scale.pack()
#Checkbutton
def checkbutton_used():
#Prints 1 if On button checked, otherwise 0.
print(checked_state.get())
#variable to hold on to checked state, 0 is off, 1 is on.
checked_state = IntVar()
checkbutton = Checkbutton(text="Is On?", variable=checked_state, command=checkbutton_used)
checked_state.get()
checkbutton.pack()
#Radiobutton
def radio_used():
print(radio_state.get())
#Variable to hold on to which radio button value is checked.
radio_state = IntVar()
radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used)
radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used)
radiobutton1.pack()
radiobutton2.pack()
#Listbox
def listbox_used(event):
# Gets current selection from listbox
print(listbox.get(listbox.curselection()))
listbox = Listbox(height=4)
fruits = ["Apple", "Pear", "Orange", "Banana"]
for item in fruits:
listbox.insert(fruits.index(item), item)
listbox.bind("<<ListboxSelect>>", listbox_used)
listbox.pack()
+ 추가로 레이아웃 설정시 pack / place / grid 가 있다
place는 x, y 값으로 해당 위젯의 위치를 조정 가능하다 (0,0)이 좌상단
(단점은 너무 구체적으로 위치를 잡아줘야 함)
grid는 Row/Column을 써서 행렬로 구역을 나눠서 보면 된다 (0,0)이 역시 좌상단
위 예시의 코드에서 아래와 같아 0,1,2로 바꾼 결과의 스크린샷을 같이 첨부
(추가로 grid와 pack은 같이 쓸 수 없다)
label.grid(column=0, row=0)
button.grid(column=1, row=1)
input_entry.grid(column=2, row=2)
레이아웃의 사용 예시를 보면 뭔가 제한 적인 부분들이 있어 보인다.
특히 grid의 경우 한 위젯이 두 칸을 차지하는 경우 어떻게 하는지에 대해서 인자 설정이 필요한데, 그 때 사용되는 것이 columnspan의 기능을 쓸 수 있다 (가로로 n칸 차지하게 함)
from tkinter import *
window = Tk()
t1 = Label(text="Text1")
t1.grid(row=0, column=0)
t2 = Label(text="Text2")
t2.grid(row=1, column=1)
t3 = Label(text="Text3")
# 아래처럼 columnspan이 2이면 3번째 줄에서 2칸을 차지한다
t3.grid(row=2, column=0, columnspan=2)
window.mainloop()
추가로 tkinter에 대한 파이썬 매뉴얼 링크는 아래에 첨부
https://docs.python.org/3/library/tkinter.html
tkinter — Python interface to Tcl/Tk
Source code: Lib/tkinter/__init__.py The tkinter package (“Tk interface”) is the standard Python interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, inclu...
docs.python.org
추가로 글이 길어져서 Canvas Widget 사용법과 MessageBox 사용에 대해서는 따로 링크를 연결해두었습니다
'Devs > Python' 카테고리의 다른 글
[Python] Tkinter - Canvas Widget (0) | 2025.04.04 |
---|---|
[Python] *args, **kwargs 를 알아보자 (0) | 2025.04.03 |
[Python] List Comprehension, Dictionary Comprehension 알아보기 (0) | 2025.04.02 |
[Python] File Read/Write와 with 사용법 (0) | 2025.04.01 |
[Python] List, Tuple Slicing 사용법 (0) | 2025.03.31 |