【问题标题】:Disable / Enable Button in TKinter在 TKinter 中禁用/启用按钮
【发布时间】:2018-12-02 13:05:59
【问题描述】:

我正在尝试制作一个像开关一样的按钮,所以如果我单击禁用按钮 它将禁用“按钮”(有效)。如果我再次按下它,它将再次启用它。

我尝试了 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()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      问题出在您的switch 函数中。

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

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

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

      【讨论】:

        猜你喜欢
        • 2022-08-14
        • 1970-01-01
        • 2020-04-19
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-16
        • 1970-01-01
        相关资源
        最近更新 更多