[Tkinter-discuss] Problems with lambda functions in callbacks

Dídac Busquets busquets at silver.udg.es
Fri Feb 16 18:04:24 CET 2007


Hi,

Thank you all for you responses. With Stewart's answer I could get it 
working. Those were my first lines in python (that is why I had so many 
semi-colons - I'm so used to C and C++).

And also thanks for the explanation. One really needs to know how the 
programming language works when writing a program.

Cheers,

    Dídac

mkieverpy at tlink.de wrote:
> Hello Dídac,
>
> just to add an explanation, why your code doesn't work:
>
> >from Tkinter import *
>   
>> root = Tk();
>>
>> def cb(x):
>>    print x;
>>     
>    
>   
>> for i in range(5):
>>    b = Button(root,text=i,command=lambda:cb(i));
>>     
>
> The part "lambda:cb(i)" is a function which gets evaluated
> (called) when a button is clicked. It is evaluated
> in the scope where it is defined. In this scope (the global scope)
> the for-loop has finished running long ago.
> Thus 'i' is always evaluated to '4' regardless which
> button is pressed because this is the value of 'i'
> after the end of the loop.
>
> Stewart's code:
>    b = Button(root,text=i,command=lambda i=i:cb(i));
> This code works because it turns the loop variable 'i'
> into a default value for the parameter 'i' of the lambda function.
> And default values are evaluated when the function is defined,
> i.e. while the loop is running.
>
>   
>>    b.pack();
>>
>> root.mainloop();
>>     
>
> Hope this helps to demystify this behaviour,
>
> Matthias Kievernagel
> (mkiever/at/web/dot/de)
> _______________________________________________
> Tkinter-discuss mailing list
> Tkinter-discuss at python.org
> http://mail.python.org/mailman/listinfo/tkinter-discuss
>
>
>   

-- 
------------------------------------------------------------------------
*Dídac Busquets i Font*

Investigador Ramón y Cajal
Universitat de Girona
Dept. d'Electrònica, Informàtica i Automàtica
Institut d'Informàtica i Aplicacions
Edifici P-IV, Despatx 128
Campus Montilivi
17071 Girona

Tel. (+34) 972.41.81.79
Fax. (+34) 972.41.80.98
e-mail: busquets at eia.udg.es
web: http://eia.udg.es/~busquets

------------------------------------------------------------------------
Abans d'imprimir aquest correu electrònic pensa si és necessari fer-ho: 
el medi ambient és cosa de tots.

------------------------------------------------------------------------


More information about the Tkinter-discuss mailing list