Im making an tic tac toe but when the button got click the button wont change this the example
from tkinter import *
a = Tk()
def c():
t = "X"
t = ""
b=Button(a, text= t, command=c)
b.pack()
a.mainloop()
This just an example plss give any way to change the text of button by calling
CodePudding user response:
The line t = "X" creates a new variable inside the function c(), which is then garbage collected when the function exits. Also the button text is not set.
You can change the button text with the .config() method:
from tkinter import *
a = Tk()
def c():
b.config(text="X")
t = ""
b = Button(a, text=t, command=c)
b.pack()
a.mainloop()
CodePudding user response:
The problem is your t is not in the same scope. For example:
def change():
a=10000
a=100
print(a)
change()
print(a)
OUTPUT:
100
100
Functions are like vegas, what happens there, stays there. Read up on scope in more detail here: https://www.w3schools.com/python/python_scope.asp
It's been a while since I've used tkinter, but I do remember creating classes and using them was super helpful for keeping things string.
Here is an example of how to set up a class with a method to change it
from Tkinter import *
class Board:
TurnMarker="X"
root=Tk()
class button:
def __init__(self,GameBoard,x,y):
self.text=""
self.x=x
self.y=y
self.GameBoard=GameBoard
self.button=Button(GameBoard.root,self.text,command=self.set)
self.button.grid(row=y,column=x)
def set(self):
self.button["text"]=self.GameBoard.TurnMarker
if self.GameBoard.TurnMarker=="X":
self.GameBoard.TurnMarker="O"
else:
self.GameBoard.TurnMarker="X"
board=Board()
for y in range(3):
for x in range(3):
b=button(board,x,y)
This is an example of using classes both for the buttons and board. Classes make working with Tkinter much easier.
