Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬 tkinter와 tkinter.ttk 위젯의 차이점 완벽 정리


tkinter.ttk는 tkinter 위젯에 스타일을 적용하기 위해 사용되는 모듈입니다. HTML 요소를 꾸밀 때 CSS를 사용하는 것처럼, tkinter에서도 tkinter.ttk를 활용하면 위젯의 색상과 테마를 손쉽게 다듬을 수 있습니다.

tkinter와 tkinter.ttk의 주요 차이점

  • 위젯 종류: 기본 tkinter 위젯은 버튼(Button), 레이블(Label), 텍스트(Text), 스크롤바(Scrollbar) 등을 추가할 때 사용됩니다. 반면 tkinter.ttk는 Combobox, Treeview, Notebook, Progressbar 등 훨씬 더 다양한 위젯을 추가로 지원합니다.
  • 스타일링 방식: ttk 위젯은 bg, fg 같은 전통적인 옵션을 일부 직접 지원하지 않습니다. 대신 ttk.Style 객체를 통해 테마와 색상을 설정해야 하며, 위젯의 배치(pack, grid, place)는 기존 방식과 동일하게 사용할 수 있습니다.
  • 모던한 외관: ttk는 테마 엔진을 기반으로 동작하므로, 운영체제의 네이티브 애플리케이션에 가까운 현대적인 UI를 구현할 수 있는 다양한 기능과 설정을 제공합니다.
  • 모듈의 성격: 기본 tkinter 위젯은 tkinter 라이브러리에 내장된 고전(native) 위젯인 반면, ttk는 테마가 적용된(themed) 전용 모듈입니다.
  • 임포트 방법: 기존 Tk 위젯을 ttk 위젯으로 대체하려면 from tkinter.ttk import *로 임포트하면 됩니다. 이렇게 하면 Button, Label 등이 자동으로 ttk 버전으로 교체됩니다.

예제 코드

아래 예제에서는 tkinter.ttk 모듈을 사용해 tkinter 위젯에 스타일을 적용해 보겠습니다. 버튼을 클릭하면 텍스트 위젯의 배경색이 빨간색으로 변경됩니다.

#Import the tkinter library
from tkinter import *
from tkinter.ttk import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("620x400")

#Add a class to style the tkinter widgets
style = ttk.Style()
style.configure('TEntry', foreground = 'red')

#Define a function to change the text color
def change_color():
    text.configure(background="red")

#Create a text widget
text=Label(win,text="This is a New Text",foreground="white",
background="blue",font=('Aerial bold',20))
text.pack(pady=20)

#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)
win.mainloop()

실행 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

파이썬 tkinter와 tkinter.ttk 위젯의 차이점 완벽 정리

이제 "Click Here" 버튼을 클릭하면 텍스트 위젯의 배경색이 빨간색으로 바뀌는 것을 확인할 수 있습니다.

파이썬 tkinter와 tkinter.ttk 위젯의 차이점 완벽 정리