Disable / Enable Button in TKinter

后端 未结 2 1277
没有蜡笔的小新
没有蜡笔的小新 2020-12-17 17:30

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.

相关标签:
2条回答
  • 2020-12-17 18:10

    A Tkinter Button has three states : active, normal, disabled.

    You set the state option to disabled to gray out the button and make it unresponsive. It has the value active when the mouse is over it and the default is 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()
    
    0 讨论(0)
  • 2020-12-17 18:13

    The problem is in your switch function.

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

    When you click the button, switch is being called each time. For a toggle behaviour, you need to tell it to switch back to the NORMAL state.

    def switch():
        if b1["state"] == NORMAL:
            b1["state"] = DISABLED
        else:
            b1["state"] = NORMAL
    
    0 讨论(0)
提交回复
热议问题