如何更改 Tkinter 按鈕狀態

Jinku Hu 2020年6月25日 2019年12月2日
如何更改 Tkinter 按鈕狀態

Tkinter 按鈕有兩種狀態,

  • NORMAL - 使用者可以單擊該按鈕
  • DISABLED - 該按鈕不可單擊
try:
    import Tkinter as tk
except:
    import tkinter as tk
    

app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Button 1",
                    state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1")
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()

左側按鈕已禁用(變灰),右側按鈕正常。

Tkinter 按鈕狀態-禁用和正常

可以用類似於字典的方法或類似於配置的方法來修改狀態。

try:
    import Tkinter as tk
except:
    import tkinter as tk
    
def switchButtonState():
    if (button1['state'] == tk.NORMAL):
        button1['state'] = tk.DISABLED
    else:
        button1['state'] = tk.NORMAL
        
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Python Button 1",
                    state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1",
                    command = switchButtonState)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
app.mainloop()

通過單擊 button2,它呼叫 switchButtonState 函式將 button1 狀態從 DISABLED 切換到 NORMAL,或者反向切換。

Tkinter 按鈕狀態切換-禁用和正常之間

state 是 Tkinter 按鈕控制元件的一個選項。所有的 Button 控制元件的選項都是 Button 字典的鍵值。

def switchButtonState():
    if (button1['state'] == tk.NORMAL):
        button1['state'] = tk.DISABLED
    else:
        button1['state'] = tk.NORMAL

通過更新 Button 字典的 state 的值,按鈕的 state 狀態得到了更新。

state 還可以通過使用更改 Button 物件的 config 方法來更改。因此,switchButtonState() 函式也可以按以下方式實現,

def switchButtonState():
    if (button1['state'] == tk.NORMAL):
        button1.config(state=tk.DISABLED)
    else:
        button1.config(state=tk.NORMAL)

甚至我們可以更簡單的使用字串 normaldisabled 來切換狀態,而不非得用 tk.NORMALtk.DISABLED

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Tkinter Button