In the following code, the two ways of constructing buttons act differently:
from Tkinter import *
def buildButton1():
root = Tk()
Button( root, command = lambda : foo(1) ).pack()
Button( root, command = lambda : foo(2) ).pack()
def buildButton2():
root = Tk()
buttons = ( Button( root, command = lambda : foo(i) ) for i in range(2) )
map( lambda button : button.pack(), buttons )
def foo( number ):
print number
Both methods make Tkinter window with two ostensibly identical button layouts, but in the second example - which seems much more concise were we to add 50 buttons instead of 2 - the value that gets passed into foo is the last iterated i.
So in this case, pushing any button made with buildButton2 prints 1, where buildButton1's buttons print 0 and 1 respectively. Why is there a difference? Is there a way to make buildButton2 work as expected?
Edit It's been pointed out that this is a duplicate question, and that a more correct way of constructing this is to write:
buttons = ( Button( root, command = lambda i=i : foo(i) ) for i in range(2) )
which gives the desired result. Thanks guys!