TKinter中的禁用/启用按钮

rat*_*ine 6 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()
Run Code Online (Sandbox Code Playgroud)

Mir*_*j50 34

TkinterButton具有三种状态: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()
Run Code Online (Sandbox Code Playgroud)


The*_*ser 9

问题出在你的switch函数上。

def switch():
    b1["state"] = DISABLED
Run Code Online (Sandbox Code Playgroud)

当您单击按钮时,switch每次都会被调用。对于切换行为,您需要告诉它切换回状态NORMAL

def switch():
    if b1["state"] == NORMAL:
        b1["state"] = DISABLED
    else:
        b1["state"] = NORMAL
Run Code Online (Sandbox Code Playgroud)