Check state of button in tkinter
Asked Answered
S

3

8

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.

Sabu answered 25/10, 2016 at 20:54 Comment(0)
S
15

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!
Sabu answered 25/10, 2016 at 21:17 Comment(2)
super easy way to do it! Thanks for that, saved me a lot of timeSaveloy
Note: self.button['state'] does not return a string. Instead, it returns <class '_tkinter.Tcl_Obj'>Feeder
L
0

State returns the string only. And also for me if state == DISABLED: works fine.

Only difference is I'm not using this inside class: But inside my main program.

Please refer below screen shot:

state

Lachlan answered 17/8, 2023 at 13:28 Comment(0)
R
-1
from tkinter import *
app_win  = Tk()

name_btn = Button(app_win,text = 'aaaaaaa')
name_btn.pack()


print(name_btn["state"])
#normal

app_win.mainloop()
Reeding answered 17/12, 2022 at 13:44 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Beestings

© 2022 - 2024 — McMap. All rights reserved.