tkinter button command

Christopher T King squirrel at WPI.EDU
Wed Aug 4 14:57:00 CEST 2004


On Wed, 4 Aug 2004, Ajay wrote:

> if i set two buttons to call the same function when they are pressed, is
> there any way, within the function of knowing which button invoked it.

Not built-in to Tkinter, but you can easily get such behaviour using 
lambda like so:

>>> from Tkinter import *
>>> def click(which):
...     print which, 'was clicked!'
>>> button1 = Button(text='Button 1',command=lambda: click('number 1'))
>>> button2 = Button(text='Button 2',command=lambda: click('number 2'))
>>> button1.pack()
>>> button2.pack()

lambda: will wrap the call to click() up in a function.  You can call
click() with any arguments this way; instead of strings, you could use
integers or a reference to the object itself (though you'd have to set
command after creating the button to do this).




More information about the Python-list mailing list