I am trying to create buttons in tkinter within a for
loop. And with each loop pass the i
count value out as an argument in the command value. So when the function is called from the command
value I can tell which button was pressed and act accordingly.
The problem is, say the length is 3, it will create 3 buttons with titles Game 1 through Game 3 but when any of the buttons are pressed the printed value is always 2
, the last iteration. So it appears the buttons are being made as separate entities, but the i
value in the command arguments seem to be all the same. Here is the code:
def createGameURLs(self):
self.button = []
for i in range(3):
self.button.append(Button(self, text='Game '+str(i+1),
command=lambda: self.open_this(i)))
self.button[i].grid(column=4, row=i+1, sticky=W)
def open_this(self, myNum):
print(myNum)
Is there a way to get the current i
value, each iteration, to stick with that particular button?
This problem can be considered a special case of Creating functions in a loop. There's also What do lambda function closures capture?, for a more technical overview.
See also How to pass arguments to a Button command in Tkinter? for the general problem of passing arguments to Button callbacks.