Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check state of button in tkinter

On a tkinter GUI I want to print different messages on a canvas depending on the state of a button I hover over. If the button itself is DISABLED, I want to display another message on the canvas than when the button is NORMAL. I have this (stripped) relevant code:

from tkinter import *

class app:
    def __init__(self):
        self.window = Tk()
        self.button = Button(self.window,text="Button",command=self.someCommand,state=DISABLED)

        self.button.bind("<Enter>", self.showText)
        self.button.bind("<Leave>", self.hideText)

        self.window.mainloop()

    def showText(self):
        if self.button["state"] == DISABLED:
            #print this text on a canvas
        else:
            #print that text on a canvas

    def hideText(self):
        #remove text    

def main()
    instance = app()

main()

This always draws 'that text' on the canvas, instead of 'this text'

I have tried the following too:

 self.button['state']
 == 'disabled'
 == 'DISABLED'

if I print:

print(self.button["state"] == DISABLED)

it gives me:

False

Changing the state using:

self.button["state"] = NORMAL

works as I would expect.

I have read through a few topics here but none seem to answer the question to why the if-statement doesn't work.

like image 565
Joris Hilberink Avatar asked Oct 25 '16 20:10

Joris Hilberink


People also ask

How do you check if a button has been pressed Tkinter?

Let us suppose that we want to know which button is pressed in a given application. In order to get the information about the Button, we can use the callback function in the Button configuration. In the Callback function, we will use the print(test) function to print the button that is clicked.

What are the states of the button recognized by Tkinter?

The Tkinter button has two states: normal and disabled. In the regular condition, we can push the button; but, in the disabled state, we cannot click the button.

How do I get the value of a button in Python?

We can get the value of any button in the Entry widget by defining the function which inserts the value in the Entry widget. To get the value, we have to first define buttons having command for adding the specific value to be displayed on the Entry widget.


1 Answers

After some more research I finally got a solution.

print(self.button['state'])

prints:

disabled

So I could use:

state = str(self.button['state'])
if state == 'disabled':
    #print the correct text!
like image 128
Joris Hilberink Avatar answered Sep 25 '22 07:09

Joris Hilberink