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...
.
Second, you should never call time.sleep
in a GUI program. If you want to run something every .02 seconds, use after
.
Here's an example:
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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…