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?