0

I am trying to teach myself Python and decided to try to use Tkinter in order to recreate Super Tic Tac Toe. In the game, there are buttons that act to return their "value" which allows me to get their position and do the logic of the game.

To create the buttons, I use the following while loop:

def ButtonCreatorLoop():
identifierCreator = 0
while identifierCreator < 80:
          buttonList.append(Button(height=3, width=8, command=lambda: Click(identifierCreator)))
    buttonList[identifierCreator].grid(row= rowList[identifierCreator], column = columnList[identifierCreator])
    identifierCreator += 1

The issue I have is that when I create the buttons, I assign the identifying value to the identifierCreator variable, not its value at the current time, which is what I would like it to be. As a result, every button returns the value 80, which is the final value of the identifierCreator variable.

Is there a way to assign only the value at that time instead of pointing to the variable? Or would I just have to define those 80 buttons on 80 different lines?

LeoChiappini
  • 36
  • 1
  • 6
  • Lambdas has late binding. Here's a solution: https://stackoverflow.com/a/49617454/6486738. Basically, write `lambda i=identifierCreator: Click(i)` instead – Ted Klein Bergman Jun 01 '21 at 05:59
  • The more principled solution is to use a factory function, i.e. `def func_maker(identifier_creator): return lambda: Click(identifier_creator)` then use that in your loop – juanpa.arrivillaga Jun 01 '21 at 07:36

0 Answers0