如何更改 Tkinter 按鈕狀態
Jinku Hu
2020年6月25日
Tkinter
Tkinter Button
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()
左側按鈕已禁用(變灰),右側按鈕正常。

可以用類似於字典的方法或類似於配置的方法來修改狀態。
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,或者反向切換。

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)
甚至我們可以更簡單的使用字串 normal 和 disabled 來切換狀態,而不非得用 tk.NORMAL 和 tk.DISABLED。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
