Get Button Text

Kevin Doyle doyle at acrossthebigpond.com
Tue Apr 9 21:36:16 EDT 2002


Thanks James that worked great, exactly what I was looking for and a 
really nice straight forward example.

James Logajan wrote:
> Kevin Doyle <doyle at acrossthebigpond.com> wrote:
> 
>>I have code that creates x amount of Buttons on the fly.  Each buttons 
>>will have a unique Text displayed on it.
>>
>>I want to be able to get the text vale of the button when it is pressed.
>>
>>I also want to know is it possible to create just one function and bind 
>>this one function to all the buttons, and call the function with a 
>>reference to the button clicked as an argument.
> 
> 
> The secret is the use of lambda to define the command (there is another 
> way, but this has worked for me). Try this; hopefully it will become clear.
> 
> #-----------------------
> from Tkinter import *
> 
> buttonWidgets = []
> buttonLabels = [ "OK", "Cancel", "Whatever" ]
> 
> def YourFunctionCall(button_text):
>     print "You pressed ", button_text
>     # Just for the heck of it, delete the button pressed.
>     buttonLabels.remove(button_text)
>     UpdateButtons()
> 
> def UpdateButtons():
>     global buttonWidgets
>     global root
>     for button in buttonWidgets:
>         button.destroy()
>     buttonWidgets = []
>     for buttonLabel in buttonLabels:
>         button = Button(root, text = buttonLabel, command =
>                     lambda txt = buttonLabel: YourFunctionCall(txt))
>         button.pack(side = LEFT)
>         buttonWidgets.append(button)
> 
> root = Frame()
> root.pack()
> UpdateButtons()
> root.mainloop()




More information about the Python-list mailing list