如何更改 Tkinter 按钮状态

您所在的位置:网站首页 state函数python 如何更改 Tkinter 按钮状态

如何更改 Tkinter 按钮状态

2023-03-10 13:14| 来源: 网络整理| 查看: 265

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。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3