【发布时间】:2020-08-20 11:59:20
【问题描述】:
我想知道是否有任何方法可以通过不同的函数访问变量?下面是我的代码,在 isWinner() 内部,我想访问按钮的文本。怎么可能?
class ttt():
master = 0
player1 = 0
player2 = 0
bclick = True
buttonCounter = 1
win = 0
lose = 0
def boardDisplay(self):
button1 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button1), height=4, width=10)
button1.place(x=275, y=150)
button2 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button2), height=4, width=10)
button2.place(x=355, y=150)
button3 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button3), height=4, width=10)
button3.place(x=435, y=150)
button4 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button4), height=4, width=10)
button4.place(x=275, y=230)
button5 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button5), height=4, width=10)
button5.place(x=355, y=230)
button6 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button6), height=4, width=10)
button6.place(x=435, y=230)
button7 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button7), height=4, width=10)
button7.place(x=275, y=310)
button8 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button8), height=4, width=10)
button8.place(x=355, y=310)
button9 = tk.Button(self.master, text=" ", command=lambda: self.buttonClick(button9), height=4, width=10)
button9.place(x=435, y=310)
def buttonClick(self, button):
if button["text"] == " " and self.bclick == True:
button["text"] = "X"
self.bclick = False
self.isWinner()
self.buttonCounter += 1
elif button["text"] == " " and self.bclick == False:
button["text"] = "O"
self.bclick = True
self.isWinner()
self.buttonCounter += 1
else:
tk.messagebox.showinfo("Tic Tac Toe", "Button is clicked already!")
def isWinner(self):
【问题讨论】:
-
声明一个
self变量 -
@r0ei 我试过它返回一个错误。所以在我的 isWinner() 函数中,我尝试编写 self.button1["text"] == "X" 或 self.boardDisplay().button1["text"] 它不会以某种方式工作