본문 바로가기

코딩/파이썬 tkinter

[Tkinter] 12장. Button

Look and Feel!

 

화면에서 tkinter.Button과 ttk.Button은 위의 이미지와 같이 보입니다.

동일하게 코드를 구현했음에도 Label과는 달리 tkinter.Button과 ttk.Button의 모양이 조금 다르네요.

 

위 화면에 대한 코드는 아래와 같습니다.

 

  • Button 객체를 생성하여 화면에 표시하는 방법은 Label과 동일합니다. 다만, Button이라는 특성상 버튼이 눌렸을 때, 정의한 기능을 실행하기 위해 Button 객체 생성 시 command 옵션으로 실행할 메서드(또는 함수)를 정의해야 합니다.
  • 각 위젯의 configure (또는 config) 메서드를 이용해 이미 정의한 또는 정의하지 않은 위젯의 옵션을 변경할 수 있습니다.
  • 각 위젯의 옵션 변경을 위해 예로 self.label1['foreground']='red'로 코드를 작성해도 됩니다.
import tkinter as tk
import tkinter.ttk as ttk


class MainWin(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.win_settings()
        self.tkinter_ttk_basics()

    def win_settings(self):
        self.title('tkinter / ttk')
        self.geometry('480x320+200+200')
        self.minsize(200, 200)

    # -------------------------------------------------------------------------
    def tkinter_ttk_basics(self):
        tk.Button(self, text='tk.Button', command=self.click_tk_button).grid(padx=10, pady=10, sticky=tk.W)
        ttk.Button(self, text='ttk.Button', command=self.click_ttk_button).grid(padx=10, sticky=tk.W)

        self.label1 = tk.Label(self, text='tk.Label')
        self.label1.grid(row=0, column=1, sticky=tk.W)

        self.label2 = ttk.Label(self, text='ttk.Label')
        self.label2.grid(row=1, column=1, sticky=tk.W)

    def click_tk_button(self):
        self.label1.configure(foreground='blue')
        self.label2.config(foreground='red')

    def click_ttk_button(self):
        self.label1.configure(fg='red')
        self.label2.configure(foreground='blue')
    # -------------------------------------------------------------------------
    

if __name__ == '__main__':
    mainWin = MainWin()
    mainWin.mainloop()

 

ttk.Button 버튼을 누르면 아래와 같이 각 Label의 글자색이 변합니다.

 

'코딩 > 파이썬 tkinter' 카테고리의 다른 글

[Tkinter] 14장. 위젯의 focus() 메서드  (0) 2020.11.15
[Tkinter] 13장. Entry  (0) 2020.11.12
[Tkinter] 11장. Label (ttk) 2단계  (0) 2020.11.08
[Tkinter] 10장. Label 2단계  (0) 2020.11.08
[Tkinter] 9장. Grid  (0) 2020.11.08