Tkinter checkbuttons and variables

Diez B. Roggisch deets at nospam.web.de
Wed Feb 21 10:24:11 EST 2007


Gigs_ schrieb:
> from Tkinter import *
> 
> states = []
> 
> def onpress(i):
>     states[i] = not states[i]
> 
> 
> root = Tk()
> for i in range(10):
>     chk = Checkbutton(root, text= str(i), command=lambda i=i: onpress(i))
>     chk.pack(side=LEFT)
>     states.append(0)
> root.mainloop()
> print states
> 
> after exiting i get everything like it suppose to but when i put command 
> like this:
> command=lambda: onpress(i)
> i got only last checkbutton check.
> 
> Why i have to pass this default argument?

Because python creates a closure around the lambda that allows 
expressions inside the lambda to access surrounding variables. However, 
these variables are looked up at _runtime_, when the command is actually 
executed. Naturally, the value of i then is 9, because that's what it 
has been assigned in the last loop iteration.

Diez



More information about the Python-list mailing list