Tkinter callback arguments

eb303 eric.brunel.pragmadev at gmail.com
Mon Nov 2 10:07:45 CET 2009


On Nov 1, 8:53 pm, Lord Eldritch <lord_eldri... at yahoo.co.uk> wrote:
> Hi
>
> Maybe this is maybe something it has been answered somewhere but I haven't
> been able to make it work. I wanna pass one variable to a callback function
> and I've read the proper way is:
>
> Button(......, command=lambda: function(x))
>
> So with
>
> def function(a): print a
>
> I get the value of x. Ok. My problem now is that I generate the widgets in a
> loop and I use the variable to 'label' the widget:
>
> for x in range(0,3):  Button(......, command=lambda: function(x))
>
> so pressing each button should give me 0,1,2.
>
> But with the lambda, I always get the last index, because it gets actualized
> at each loop cycle. Is there any way to get that?

for x in range(0,3): Button(..., command=functools.partial(function,
x))

With the functools standard module that appeared in version 2.5, I
hardly ever use lambdas in Tkinter callbacks now.

> Thanks in advance!

HTH



More information about the Python-list mailing list