Get the text of a button widget

淺唱寂寞╮ 提交于 2020-01-12 14:11:28

问题


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:


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.



来源:https://stackoverflow.com/questions/26765218/get-the-text-of-a-button-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!