I'm trying to make a tic tac toe game with tkinter. When I instantiate buttons in a 3x3 board that each call a function of mark_square() with themselves as a parameter, each button will refer to the last button that was instantiated in the nested for loop.
People have suggested that I bind the lambda function to the button which is what I did in this code:
from tkinter import *
from tkinter import messagebox
turn = "X"
def mark_square(box):
global turn
if box.cget('text') == " ":
box['text'] = turn
else:
messagebox.showerror(title="Invalid", message="Invalid")
root = Tk()
root.title("Tic-Tac-Toe")
for x in range(0, 3):
for y in range(0, 3):
grid_box = Button(text=" ", font=("Arial", 40), padx=20, command=lambda grid_box=grid_box: mark_square(grid_box))
grid_box.grid(row=x, column=y)
root.mainloop()
However, I'm getting an error telling me that grid_box is undefined. Does anyone know what's going on and how to fix it?
grid_boxas a the default value of an argument to thelambdafunction, however during the first iteration of theforloop, the variable doesn't exist yet which will cause an error…and even if it did not, each time it would be referring to the value of the last assignment to the variable (which would be for the previousButton). - martineaugrid_boxhas not been created yet. So usegrid_box.config(command=lambda ...)after it is created. - acw1668