Get the text of a button widget

2019-04-06 14:43发布

I want to get the text from a button to compare it using an if-statement.

Say I have this button:

my_button = Button(self, text = 'hi')
my_button.grid(row = 0, column = 0, sticky = W)

And want to do something like this:

my_text = my_button.text

So that the following if-statement evaluates as True:

if my_text == 'hi':
    # do something

How can I do this in an easy way?

1条回答
来,给爷笑一个
2楼-- · 2019-04-06 15:17

You can simply do:

my_text = my_button['text']

Tkinter allows you to access any option of a widget this way (height, width, text, etc.)


If you need this as a method call, you can use .cget:

my_text = my_button.cget('text')

Note that this method is available on all standard Tkinter widgets.

查看更多
登录 后发表回答