我正在通过overrideredirect在Tkinter中构建一个带有自定义窗口的应用程序.我将自行设计的X按钮绑定到下面的功能.使用我的按钮关闭应用程序工作正常,它确实淡出,但几秒钟后窗口重新出现,卡在一个循环(这就是它的样子)和崩溃.它应该退出,这是我在添加淡出循环之前所做的.有人能告诉我为什么程序重新出现然后在关闭应用程序时崩溃或为淡出效果提供更好的替代方案(我知道有更复杂的工具包但我需要在这种情况下使用Tkinter)?
谢谢
def CloseApp(event):
if InProgress==False: #InProgress boolean defined elsewhere in program
if tkMessageBox.askokcancel("Quit","Do you really wish to quit?"):
n=1
while n != 0:
n -= 0.1
QuizWindow.attributes("-alpha", n)
time.sleep(0.02)
Window.destroy() #I've also tried using the quit() method, not that it would make a difference
else:
if tkMessageBox.askokcancel("Quit"," If you quit now you will lose your progress and have to start again. Are you sure you want to quit?"):
n=1
while n != 0:
n -= 0.1
QuizWindow.attributes("-alpha", n)
time.sleep(0.02)
Window.destroy()
Run Code Online (Sandbox Code Playgroud)
你有两个问题.首先,您不应该对浮点数进行精确比较.浮点数学是不精确的,n实际上可能永远不会0.0000000....
其次,你永远不应该调用time.sleepGUI程序.如果你想每隔0.02秒运行一次,请使用after.
这是一个例子:
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
b = tk.Button(self, text="Click to fade away", command=self.quit)
b.pack()
self.parent = parent
def quit(self):
self.fade_away()
def fade_away(self):
alpha = self.parent.attributes("-alpha")
if alpha > 0:
alpha -= .1
self.parent.attributes("-alpha", alpha)
self.after(100, self.fade_away)
else:
self.parent.destroy()
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)