Tkinter.Button(... command) lambda and argument problem

Jay jaysherby at gmail.com
Sat Sep 16 02:00:57 CEST 2006


Perfect.  Thanks.


Paul Rubin wrote:
> "Jay" <jaysherby at gmail.com> writes:
>
> > I'm having a problem using lambda to use a command with an argument for
> > a button in Tkinter.
> >
> >                 buttons = range(5)
> > 		for x in xrange(5):
>
> > self.highlight(x))
> > 			buttons[x].pack(side=LEFT)
> >
> > The buttons are correctly numbered 1 through 5, but no matter which
> > button I click on, it sends the number 4 as an argument to the
> > highlight function.
>
> x is not bound by the lambda and so the lambda body gets it from the
> outside environment at the time the body is executed.  You have to
> capture it at the time you create the lambda.  There's an ugly but
> idiomatic trick in Python usually used for that:
>
>   buttons[x] = Button(frame, text=str(x+1),   \
>         command=lambda x=x: self.highlight(x))
>
> See the "x=x" gives the lambda an arg whose default value is set to
> x at the time the lambda is created, as opposed to when it's called.




More information about the Python-list mailing list