如何更改 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