python – Disable / Enable Button in TKinter

python – Disable / Enable Button in TKinter

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

n

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.

n

Using this you can check for the state of the button and take the required action. Here is the working code.

n

from tkinter import *nnfenster = Tk()nfenster.title(Window)nndef switch():n    if b1[state] == normal:n        b1[state] = disabledn        b2[text] = enablen    else:n        b1[state] = normaln        b2[text] = disablenn#--Buttonsnb1 = Button(fenster, text=Button, height=5, width=7)nb1.grid(row=0, column=0)    nnb2 = Button(text=disable, command=switch)nb2.grid(row=0, column=1)nnfenster.mainloop()n

The problem is in your switch function.

n

def switch():n    b1[state] = DISABLEDn

n

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.

n

def switch():n    if b1[state] == NORMAL:n        b1[state] = DISABLEDn    else:n        b1[state] = NORMALn

python – Disable / Enable Button in TKinter

Leave a Reply

Your email address will not be published.