如何在Tkinter中创建淡出效果?我的代码崩溃了

6 投票
1 回答
9462 浏览
提问于 2025-04-17 22:53

我正在用Tkinter创建一个应用程序,并通过overrideredirect制作了一个自定义窗口。我把自己设计的关闭按钮绑定到了下面的函数。用我的按钮关闭应用程序是没问题的,窗口会渐渐消失,但过了几秒钟后,窗口又会重新出现,似乎陷入了一个循环,最后崩溃了。它应该直接退出,这在我添加渐变消失的功能之前是可以的。有人能告诉我为什么程序会重新出现然后崩溃,或者给我一个更好的建议,让我在关闭应用程序时实现渐变消失效果吗?(我知道还有更复杂的工具包,但在这种情况下我需要使用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() 

1 个回答

10

你有两个问题。首先,千万不要对浮点数进行精确比较。浮点数的计算不够精确,n 可能永远不会真正等于 0.0000000...

其次,在图形用户界面(GUI)程序中,绝对不要使用 time.sleep。如果你想每隔 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()

撰写回答