I'm trying to run a (GUI) program in Python (Tkinter) which should work as follows:
A loop generates five (or n in general, I'm just trying to do it for n=5 for now) button, and clicking on the i'th button prints out i. Here's what I did:
def func(i):
print i
for i in range(5):
buttons[i]= Button(but, text= "%s" %str(inputs[i]), command= lambda: func(i+1))
buttons[i].grid(row= i+2, column= 0)
Problem is, clicking on all of the buttons prints 5, so somehow func(5) is assigned to all of the buttons. Surprisingly, doing the following works out.
buttons[0].config(command= lambda: func(1))
buttons[1].config(command= lambda: func(2))
buttons[2].config(command= lambda: func(3))
buttons[3].config(command= lambda: func(4))
buttons[4].config(command= lambda: func(5))
As I'm trying to do it in general for any number of inputs, there's no other way to do this without looping. Could anyone please help me how to fix that? Thanks!
commandparameter on thegrid()method...