I'm trying to create 6 buttons in a for loop using tkinter, each button's command points at the same function, but passes a variable (the loop counter.. in this case i) now for some reason.. when i run it, and click on each button, the function is supposed to print the variable passed to it from the button, so i'd expect:
click button 1 -> prints 1 to screen
click button 2 -> prints 2 to screen
However i end up with:
click button 1 - > prints 6 to screen
click button 2 - > prints 6 to screen again..
click button 3 - > 6 yet again.
the code i'm using follows:
def buttonClick(button_number): print button_number if __name__ == '__main__': root = Tk() for i in range(1,6): Button(root, text="%i"%(i), command=lambda:buttonClick(i)).grid(row=i, column=2) root.mainloop()
It seems to be displaying the last value of 'i'?
thanks in advance