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 -- http://mail.python.org/mailman/listinfo/python-list