Im making a game using tkinter and I need it to be when the tkinter button in pressed then the name of the button changes to an "x" then an "o" then a blank string again.
im making the grid of buttons using for loops:
class Grid(Tk.Frame):
def __init__(self, win):
Tk.Frame.__init__(self, win)
for row in range(3):
for col in range(3):
butt1 = Tk.Button(self, bg='blue', width=round(WIDTH/33), height=round(HEIGHT/66), command=)
butt1.grid(row=row, column=col)
grid = Grid(win)
grid.pack(side="top", fill="both", expand=True)
Though im not sure what command to put in the button because if i make a function that makes butt1["text"] = "x"
then it will only work for the last button because each button has the same varable name.
Im trying to make it so the variable name is changed independently of the button name.
You could store each of the buttons in some sort of a collection, and then set the callback command to reference that buttons specific location in the collection in order to retrieve and set the text of the button upon future calls to the callback.
In this example I collect all of the buttons into a dict
, with the keys being the tuple
of their (row, column)
index and the value is the button widget itself. The callback uses those same values in order to read and set the buttons text when pressed.
class Grid(tk.Frame):
def __init__(self, win):
tk.Frame.__init__(self, win)
self.buttons = {}
self.labels = ["", "x", "o"]
for row in range(3):
for col in range(3):
butt1 = tk.Button(self, bg="blue", width=round(WIDTH/33), height=round(HEIGHT/66), command = lambda r=row,c=col: self.set_label(r,c))
butt1.grid(row=row, column=col)
self.buttons[(row, col)] = butt1
def set_label(self, r, c):
button = self.buttons[(r,c)]
label = button.cget("text")
idx = self.labels.index(label)
idx = idx + 1 if idx < len(self.labels) - 1 else 0
button.config(text=self.labels[idx])