Tkinter 위젯

2024. 2. 20. 06:05GUI/tkinter

요약 : 이 튜토리얼에서는 Tkinter Button 위젯과 이를 사용하여 다양한 종류의 버튼을 만드는 방법에 대해 배웁니다.

Tkinter Button 위젯 소개

버튼 위젯은 애플리케이션에서 클릭할 수 있는 항목을 나타냅니다. 일반적으로 텍스트나 이미지를 사용하여 클릭 시 수행되는 작업을 표시합니다.

버튼은 단일 글꼴로 텍스트를 표시할 수 있습니다. 그러나 텍스트가 여러 줄에 걸쳐 있을 수 있습니다. 또한 문자 중 하나에 밑줄을 표시하여 키보드 단축키를 표시할 수 있습니다.

버튼을 클릭할 때 클래스 의 함수나 메서드를 자동으로 호출하려면 해당 command 옵션을 함수나 메서드에 할당합니다. 이것을 Tkinter에서는 명령 바인딩 이라고 합니다.

버튼을 만들려면 ttk.Button다음과 같이 ttk.Button 생성자를 사용합니다.

button = ttk.Button(master, **option)

버튼에는 다양한 옵션이 있습니다. 그러나 대표적인 것은 다음과 같습니다.

button = ttk.Button(master, text, command)

이 구문에서는:

  • master : 버튼을 배치하는 상위 위젯입니다.
  • text : 버튼의 라벨입니다.
  • command : 버튼을 클릭하면 자동으로 호출되는 콜백 함수를 지정합니다.

명령 콜백

command 옵션은 버튼의 동작을 클래스의 함수 또는 메서드와 연결합니다. 버튼을 클릭하거나 누르면 콜백 함수가 자동으로 호출됩니다.

command 옵션에 콜백을 할당하려면 람다 표현식을 사용할 수 있습니다.

In [5]:
# 실행되는 코드가 아님

def callback():
    # do something


ttk.Button(
   root, 
   text="Demo Button", 
   command=callback
)
  Cell In[5], line 5
    ttk.Button(
    ^
IndentationError: expected an indented block after function definition on line 1

함수에 표현식이 하나 포함되어 있으면 람다 표현식을 사용합니다.

In [6]:
# 실행되는 코드가 아님

ttk.Button(
   root, 
   text="Demo Button", 
   command=lambda_expression
)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[6], line 2
      1 ttk.Button(
----> 2    root, 
      3    text="Demo Button", 
      4    command=lambda_expression
      5 )

NameError: name 'root' is not defined

버튼 상태

버튼의 기본 상태는 normal 입니다. 이 normal 상태에서 버튼은 해당 명령 옵션에 할당된 콜백 함수를 호출하여 마우스 이벤트 및 키보드 누름에 응답합니다.

버튼에도 disabled 상태가 있을 수 있습니다. 이 disabled 상태에서는 버튼이 회색으로 표시되고 마우스 이벤트 및 키보드 누르기에 응답하지 않습니다.

버튼 상태를 제어하려면 다음 state() 메서드를 사용합니다.

In [7]:
# 실행되는 코드가 아님

# set the disabled flag
button.state(['disabled'])

# remove the disabled flag
button.state(['!disabled'])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 2
      1 # set the disabled flag
----> 2 button.state(['disabled'])
      4 # remove the disabled flag
      5 button.state(['!disabled'])

NameError: name 'button' is not defined

Tkinter 버튼 예

버튼 위젯을 사용하는 몇 가지 예를 살펴보겠습니다.

1) 간단한 Tkinter 버튼 예

다음 프로그램은 Exit버튼을 표시하는 방법을 보여줍니다. 클릭 시 프로그램이 종료됩니다.

In [8]:
import tkinter as tk
from tkinter import ttk

# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Button Demo')

# exit button
exit_button = ttk.Button(
    root,
    text='Exit',
    command=lambda: root.quit()
)

exit_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)

root.mainloop()

작동 방식.

다음은 Exit버튼을 생성합니다.

In [10]:
exit_button = ttk.Button(
    root,
    text='Exit',
    command=lambda: root.quit()
)

버튼 명령은 루트 창을 닫는 람다 식 에 할당됩니다.

2) Tkinter 이미지 버튼 예

다음 프로그램은 이미지 버튼을 표시하는 방법을 보여줍니다. 이 예제를 연습하려면 먼저 다음 이미지를 다운로드해야 합니다.

 

 

 

마우스 오른쪽 버튼을 클릭하고 다음 프로그램에서 액세스할 수 있는 폴더(예: assets폴더)에 저장하세요.

In [7]:
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Image Button Demo')

# download button
def download_clicked():
    showinfo(
        title='Information',
        message='Download button clicked!'
    )


download_icon = tk.PhotoImage(file='./assets/download.png')
download_button = ttk.Button(
    root,
    image=download_icon,
    command=download_clicked
)

download_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)


root.mainloop()

작동 방식.

  • 먼저 './assets/download.png' 이미지 파일을 참조하는 클래스 tk.PhotoImage의 새 인스턴스를 만듭니다.
  • 둘째, 이미지에 이미지 옵션이 할당된 ttk.Button 를 만듭니다.
  • 셋째, command 옵션에 기능을 할당합니다. 버튼을 클릭하면 download_clicked 메시지 상자를 표시하는 함수가 호출됩니다.

3) 이미지 버튼 표시

버튼에 텍스트와 이미지를 모두 표시하려면 compound 옵션을 사용해야 합니다. 그렇지 않으면 버튼에 이미지가 아닌 텍스트만 표시됩니다.

다음은 버튼에 텍스트와 이미지를 모두 표시하는 방법을 보여줍니다.

In [9]:
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo


# root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Image Button Demo')


# download button handler
def download_clicked():
    showinfo(
        title='Information',
        message='Download button clicked!'
    )


download_icon = tk.PhotoImage(file='./assets/download.png')

download_button = ttk.Button(
    root,
    image=download_icon,
    text='Download',
    compound=tk.LEFT,
    command=download_clicked
)

download_button.pack(
    ipadx=5,
    ipady=5,
    expand=True
)


root.mainloop()

요약

  • 클래스를 사용하여 ttk.Button()버튼을 만듭니다.
  • 버튼 클릭 이벤트에 응답하는 command 옵션에 람다 식 이나 함수를 할당합니다.
  • 버튼에 이미지를 표시하려면 image 속성에 tk.PhotoImage()를 할당하세요.
  • 버튼에 텍스트와 이미지를 모두 표시하려면 compound 옵션을 사용하세요.
 

'GUI > tkinter' 카테고리의 다른 글

Tkinter Pack  (0) 2024.02.21
Tkinter Entry  (1) 2024.02.20
Tkinter 라벨  (1) 2024.02.18
Tkinter 명령 바인딩  (0) 2024.02.17
Tk 테마 위젯에 대한 옵션을 설정하는 3가지 방법  (0) 2024.02.16