Checking the state of Tkinter buttons in Python

In this Python tutorial, we will learn how to check and change the states of the button in Tkinter. For this, we first need to install Tkinter into our python environment. We will see a GUI window in which we will change the state of the Tkinter button by pressing it.

First, we need to understand about what is the state in Python Tkinter. Tkinter is a python library by using we can create our own GUI window. The Tkinter button has mainly two states normal state and disabled. In the normal state, we can able to press the button but in the disabled state, we are not able to click the button. So basically in this tutorial, we will learn about the Tkinter button states.

Let us move towards the coding section of the given problem.

import tkinter as tk

Import Tkinter package first.

app = tk.Tk()
app.geometry("300x100")

Now we will make an app object and set the size of that window asĀ  300 x 100.

button1 = tk.Button(app, text="Python Button 1",
                    state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1",
                    command = switchButtonState)

We will add two buttons button1 and button2. We will give an argument as an app as we want to be displayed on app window and give a name by setting text attributes as “Python Button 1”. we will give the value of the state of button 1 as Disabled by assigning value tk.DISABLED.

Likewise, in Button 2 we will pass the command as some function name so that if we press that button it will run that following function. Here we are giving them switchButtonState as function. We will define that function later on.

button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)

Also, we will position those two buttons by using the pack.

def switchButtonState():
    if (button1['state'] == tk.NORMAL):
        button1['state'] = tk.DISABLED
    else:
        button1['state'] = tk.NORMAL

Now, this is the actual function that will change the state of that button. By clicking on the button if the state of button1 is normal then it will change the state it with disabled else it will keep the state normal.

app.mainloop()

At last, we have to give app.mainloop() so that the app runs.

Now you can change the state of that Button1 on clicking on the Button2.
Below I have given the complete code.

import tkinter as tk
app = tk.Tk()
app.geometry("300x100")
button1 = tk.Button(app, text="Python Button 1",
                    state=tk.DISABLED)
button2 = tk.Button(app, text="EN/DISABLE Button 1",
                    command = switchButtonState)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.RIGHT)
def switchButtonState():
    if (button1['state'] == tk.NORMAL):
        button1['state'] = tk.DISABLED
    else:
        button1['state'] = tk.NORMAL
app.mainloop()

That’s it. We are successfully able to check and change the state of the Tkinter button.

You can also do the same and see it working by yourself.

Leave a Reply