[Tkinter-discuss] Problems with lambda functions in callbacks

Dídac Busquets busquets at silver.udg.es
Thu Feb 15 16:47:05 CET 2007


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

-- 
------------------------------------------------------------------------
*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