[英]Disable / Enable Button in TKinter
I'm trying to make a button like a switch, so if I click the disable button it will disable the "Button" (that works). 我正在尝试创建一个像开关一样的按钮,所以如果我单击禁用按钮,它将禁用“按钮”(这是有效的)。 And if I press it again, it will enable it again.
如果我再次按它,它将再次启用它。
I tried things like if, else but didn't get it to work. 我尝试过if之类的东西,但是没有让它起作用。 Here's an example:
这是一个例子:
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()
A Tkinter Button
has three states : active, normal, disabled
. Tkinter
Button
有三种状态: active, normal, disabled
。
You set the state
option to disabled
to gray out the button and make it unresponsive. 您将
state
选项设置为disabled
以使按钮变灰并使其无响应。 It has the value active
when the mouse is over it and the default is normal
. 当鼠标悬停在默认值为
normal
active
时,它的值active
normal
。
Using this you can check for the state of the button and take the required action. 使用此功能,您可以检查按钮的状态并执行所需的操作。 Here is the working code.
这是工作代码。
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()
The problem is in your switch
function. 问题出在你的
switch
功能上。
def switch():
b1["state"] = DISABLED
When you click the button, switch
is being called each time. 单击该按钮时,每次都会调用
switch
。 For a toggle behaviour, you need to tell it to switch back to the NORMAL
state. 对于切换行为,您需要告诉它切换回
NORMAL
状态。
def switch():
if b1["state"] == NORMAL:
b1["state"] = DISABLED
else:
b1["state"] = NORMAL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.