python - 在 TKinter 中禁用/启用按钮

标签 python tkinter

我想做一个像开关一样的按钮,所以如果我点击禁用按钮 它将禁用“按钮”(有效)。如果我再次按下它,它将再次启用它。

我尝试了 if, else 之类的方法,但没有成功。 这是一个例子:

from tkinter import *
fenster = Tk()
fenster.title("Window")

def switch():
    b1["state"] = DISABLED

#--Buttons
b1=Button(fenster, text="Button")
b1.config(height = 5, width = 7)
b1.grid(row=0, column=0)    

b2 = Button(text="disable", command=switch)
b2.grid(row=0,column=1)

fenster.mainloop()

最佳答案

Tkinter Button 具有三种状态:active, normal, disabled

您将 state 选项设置为 disabled 以使按钮变灰并使其无响应。当鼠标悬停在其上时,它的值为 active,默认值为 normal

使用它您可以检查按钮的状态并采取所需的操作。这是工作代码。

from tkinter import *

fenster = Tk()
fenster.title("Window")

def switch():
    if b1["state"] == "normal":
        b1["state"] = "disabled"
        b2["text"] = "enable"
    else:
        b1["state"] = "normal"
        b2["text"] = "disable"

#--Buttons
b1 = Button(fenster, text="Button", height=5, width=7)
b1.grid(row=0, column=0)    

b2 = Button(text="disable", command=switch)
b2.grid(row=0, column=1)

fenster.mainloop()

关于python - 在 TKinter 中禁用/启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53580507/

相关文章:

python - 任意数序列的回归测试

python - 绘制后更改 tkinter Canvas 对象

Python:Tkinter——如何让光标显示忙碌状态

javascript - 使用 Javascript 将页面打印为 PDF(使用 Django)

python - 每当训练模型时,内核都会重新启动

python - 无法连接 'str' 和 'instance' 对象

python - 限制空小部件的大小

python - 如何让程序在后台监听键盘事件?

python - 需要计算数据框中的负值

python - 如何通过批处理文件测试python脚本是否成功运行