如何更改 Tkinter 按钮状态
Jinku Hu
2024年2月15日
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
