Skip to content
Advertisement

Why isn’t the program closing after the fade animation?

I am new to python and I came up with this idea on how to make the page fade out by controlling the wm_attributes of my GUI program. I made this code which decreases the amount of ‘a’ by 0.1 each iteration then the program goes to sleep for 0.1 second to create this fade effect. After the page was completely transparent I told it to destroy root. However, the fade animation works perfectly but the window freezes and it doesn’t close after the animation is done. What am I doing wrong here? Here is my code:

from tkinter import *
import time


root = Tk()


def animation():
    a = 1
    while a != 0:
        a -= 0.1
        root.wm_attributes("-alpha", a)
        time.sleep(0.1)
    root.destroy()


btn = Button(root, text='Fade out', command=animation)
btn.pack()
root.mainloop()

Advertisement

Answer

In your while loop, the a variable will never reach the exact 0 value and thus your loop will never end. You either need to check if a is positive or use an integer value for subtracting.

Python uses binary floating-point arithmetic. You can find more info here.

from tkinter import *
import time


root = Tk()


def animation():
    a = 1
    while a > 0:
        a -= 0.1
        root.wm_attributes("-alpha", a)
        time.sleep(0.1)
    root.destroy()


btn = Button(root, text='Fade out', command=animation)
btn.pack()
root.mainloop()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement