我想做一个像开关一样的按钮,所以如果我点击禁用按钮 它将禁用“按钮”(有效)。如果我再次按下它,它将再次启用它。
我尝试了 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/