Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable / Enable Button in TKinter

Tags:

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.

I tried things like if, else but didn't get it to work. Here's an example:

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()
like image 572
rattionline Avatar asked Dec 02 '18 13:12

rattionline


People also ask

How do I GREY a button in Python?

You set the state option to “disabled” to grey out the button and make it insensitive. The button has the value “active” when the mouse is on it and the default value is “normal”.

How do I change the state of a button in Python?

Build A Paint Program With TKinter and Python In order to change the state of the button, we can use the state property. The state property is used to enable and disable a button in an application. In order to change the state of the application, we have two operations: state=DISABLED and state=NORMAL.

What is Tkinter button command?

Tkinter Button command option sets the function or method to be called when the button is clicked. To set a function for execution on button click, define a Python function, and assign this function name to the command option of Button.


2 Answers

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()
like image 129
Miraj50 Avatar answered Sep 22 '22 15:09

Miraj50


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
like image 21
Will Dereham Avatar answered Sep 23 '22 15:09

Will Dereham