[Tkinter-discuss] Problems with lambda functions in callbacks

Bob Greschke bob at passcal.nmt.edu
Thu Feb 15 18:37:56 CET 2007


On Feb 15, 2007, at 08:47, Dídac Busquets wrote:

> Hello,
>
> I'm trying to create a set of buttons to which I assign a callback  
> that
> is the same for all of them, except for the parameter (to do this I  
> use
> a lambda function). I want to get the buttons numbered from 0 to 4, so
> that when I click on any of them, it prints out its number (that is,
> button 0 prints 0, button 1 prints 1, etc). The code I wrote is the
> following:
>
> from Tkinter import *
>
> root = Tk();
>
> def cb(x):
>     print x;
>
> for i in range(5):
>     b = Button(root,text=i,command=lambda:cb(i));
>     b.pack();
>
> root.mainloop();
>
>
> This doesn't work, and for any button I click, I only get "4" printed
> (which is the last value of variable 'i').
>
> Any idea about what is going on?
>
> Thanks a lot,
>
>     Dídac

I've never used a lambda.


from Tkinter import *


######################
# BEGIN: class Command
# Pass arguments to functions from button presses and menu  
selections! Nice!
# In your declaration:  ...command = Command(func, args,...)
# Also use in bind() statements
#     x.bind("<blah>", Command(func, args...))
class Command:
     def __init__(self, func, *args, **kw):
         self.func = func
         self.args = args
         self.kw = kw
     def __call__(self, *args, **kw):
         args = self.args+args
         kw.update(self.kw)
         apply(self.func, args, kw)
# END: class Command


root = Tk()


def cb(x):
     print x
     return


for i in range(5):
     b = Button(root, text=i, command = Command(cb, i))
     b.pack()

root.mainloop()


What were all of the extra semi-colons?

Bob



More information about the Tkinter-discuss mailing list