Getting the sender widget's name in function (Tkinter)

Eric Brunel eric_brunel at despammed.com
Wed Apr 27 05:16:33 EDT 2005


On 26 Apr 2005 13:37:29 -0700, infidel <saint.infidel at gmail.com> wrote:

> from Tkinter import Tk, Button
>
> def say_hello(event):
>     print 'hello!'
>     print event.widget['text']
>
> root = Tk()
> button1 = Button(root, text='Button 1')
> button1.bind('<Button-1>', say_hello)
> button1.pack()
> button2 = Button(root, text='Button 2')
> button2.bind('<Button-1>', say_hello)
> button2.pack()
> root.mainloop()

Unfortunately, making a binding to <Button-1> on Button widgets does not have the same behavior as setting their 'command' option. The binding will fire when the button is *pressed*; the command will be called when the button is *released*. So, binding to <ButtonRelease-1> instead of <Button-1> make things a little better, but still does not have the same effect, since ButtonPress and ButtonRelease events are balanced: the widget getting the ButtonRelease event is always the same as the one getting the ButtonPress event. So if the mouse button is pressed inside the Button, then the mouse pointer goes out of it, and then the mouse button is released, the Button will still get the ButtonRelease event and fire the binding. This is not the normal behavior for a button and this is not the behavior you get via the 'command' option (just try it...).

So having a different function for each button or using tiissa's solution is definitely better.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"



More information about the Python-list mailing list