我正在显示两个窗口。第一个用Entry小部件保存我的游戏。而第二个是我的游戏。
当我使用.destroy()
功能关闭小部件时,它可以正常工作。但是当我想离开游戏时我做fenetre.destroy()
但没有任何反应。当我手动关闭窗口时收到消息错误:
_tkinter.TclError: can't invoke "destroy" command: application has been destroyed
这是我的代码:
def game_quit():
global name
if askyesno("Quit game ?","Are you sure? :("):
if askyesno("Save ?","Do you want to save your game? "):
ask_name()
save_scoreG(grid,lenght)
fenetre.destroy()
def ask_name():
global entry, master
master = Toplevel()
master.title("Your Name")
button=Button(master, text='Input your name and click here', command = get_name, bg= "yellow" )
usertext= StringVar()
entry = Entry(master, textvariable=usertext)
entry.pack()
button.pack()
master.mainloop()
def get_name():
global name, entry, master
name = str(entry.get())
master.destroy()
def save_scoreG(grid,lenght):
global name
with open('score','a') as s:
s.write(str(lenght)+':' + name +':'+ str(score(grid,lenght))+'\n')
我无法简化此操作以获取shell中的错误:
>>> from tkinter import Toplevel, Tk
>>> fenetre = Tk()
>>> w = Toplevel()
>>> w.destroy()
>>> fenetre.destroy()
>>> fenetre.destroy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "Z:\py34-64\lib\tkinter\__init__.py", line 1842, in destroy
self.tk.call('destroy', self._w)
_tkinter.TclError: can't invoke "destroy" command: application has been destroyed
答案 0 :(得分:1)
我真的不喜欢使用global
变量,特别是在GUI程序中,一切都应该在继承自基本小部件的类中。
我想提出一个能够完成我认为你想要实现的功能,在我看来 - 这是一个更清晰的方式。
所以这是一个打开弹出窗口的函数,询问名称并返回它。
def ask_name():
toplevel = tk.Toplevel()
label = tk.Label(toplevel, text="What's your name?")
entry = tk.Entry(toplevel)
button = tk.Button(toplevel, text="OK", command=toplevel.quit)
toplevel.pack(label)
toplevel.pack(entry)
toplevel.pack(button)
toplevel.mainloop()
return entry.get()
此功能允许您不使用global
个变量。此外,它不需要参数。我喜欢这种风格,因为这个函数几乎可以集成到utils.py
模块中,因为它完全独立于任何上下文。
虽然这可能无法直接解决您的问题,但这种避免global
变量的理念将有助于保持代码清除奇怪的依赖关系,并且更容易理解和调试。