首页 > 解决方案 > 在 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()

标签: pythontkinter

解决方案


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()

推荐阅读