我正在使用 Tkinter 编写一个井字游戏。当一个用户获胜时,会出现一个带有重新启动按钮的顶级窗口,该窗口必须重新启动程序,但是当我单击它时收到意外错误。我知道我的获胜者检查功能很愚蠢,但我可以用我目前的知识水平写一个更好的。错误信息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Eldiiar Raiymkulov\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Eldiiar Raiymkulov\Desktop\xo2.py", line 62, in <lambda>
command=lambda x=x, y=y: clicked(y, x)))
File "C:\Users\Eldiiar Raiymkulov\Desktop\xo2.py", line 15, in clicked
isWinner(char)
File "C:\Users\Eldiiar Raiymkulov\Desktop\xo2.py", line 46, in isWinner
topMessage(char)
File "C:\Users\Eldiiar Raiymkulov\Desktop\xo2.py", line 30, in topMessage
topButton = Button(top, text="Restart", command=restart(root))
NameError: name 'root' is not defined
这是代码:
from tkinter import *
turn = True
btns = None
def clicked(y, x):
global turn, btns
char = ""
if turn:
char = "X"
else:
char = "O"
btns[y][x].config(text=char,
state=DISABLED)
isWinner(char)
turn = not turn
def restart(root):
global turn
turn = True
root.destroy()
main()
def topMessage(char):
global root
top = Toplevel()
top.title("Congratulations!")
topText = Label(top, text=f"{char} is a winner!")
topButton = Button(top, text="Restart", command=restart(root))
topText.grid(row=0)
topButton.grid(row=1)
def isWinner(char):
global root
另外,如果您对 isWinner 函数有任何更明智的建议,可以与我分享吗?
相关分类