如何在 Tkinter 中创建淡出效果?我的代码崩溃 [英] How to create a fade out effect in Tkinter? My code crashes
问题描述
我正在 Tkinter 中通过 overrideredirect 使用自定义窗口构建应用程序.我已经将我自己设计的 X 按钮绑定到下面的功能.使用我的按钮关闭应用程序工作正常,它确实淡出,但几秒钟后窗口重新出现,陷入循环(这就是它的样子)并崩溃.它应该退出,这就是我添加淡出循环之前所做的.有人能告诉我为什么程序会在关闭应用程序时重新出现然后崩溃或为淡出效果提供更好的替代方案(我知道有更复杂的工具包,但在这种情况下我需要使用 Tkinter)?
I am building an application in Tkinter with a custom window through overrideredirect. I have bound my self-designed X button to the function below. Closing the app using my button works fine, and it does fade out, but after a few seconds the window reappears, gets stuck in a loop (that's what it looks like) and crashes. It should just quit, which is what it did before I added the fadeout loop. Can someone tell me why the program reappears then crashes or offer a better alternative for a fadeout effect when closing the app (I know there are more sophisticated toolkits but I need to use Tkinter in this case)?
谢谢
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()
推荐答案
您有两个问题.首先,您永远不应该对浮点数进行精确比较.浮点数学是不精确的,n
实际上可能永远不会是 0.0000000...
.
You have two problems. First, you should never do exact comparisons to floating point numbers. Floating point math is imprecise, and n
may never actually be 0.0000000...
.
第二,永远不要在 GUI 程序中调用 time.sleep
.如果您想每 0.02 秒运行一次,请使用 after代码>
.
Second, you should never call time.sleep
in a GUI program. If you want to run something every .02 seconds, use 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()
这篇关于如何在 Tkinter 中创建淡出效果?我的代码崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!