I am making an interface that requires a counter or countdown. For now everything works fine, however, when I close the window I get this error: invalid command name ".!label"
. How can i fix this? I really don't know if it's the label or something. Here is my code:
from tkinter import *
from PIL import ImageTk, Image
from tkinter import font
import time
root = Tk()
root.title("Entrenamiento")
root.resizable(FALSE, FALSE)
root.geometry('1000x700+300+50')
root.configure(background='#6dd5ed')
# Countdown
lbl_seconds = Label(root, font=("Yu Gothic UI Semibold", 30), background='#6dd5ed')
lbl_seconds.pack(pady=10)
def update():
for i in range(3, -1, -1):
lbl_seconds['text'] = i
if i == 3:
lbl_seconds['foreground'] = '#50c700'
elif i == 2:
lbl_seconds['foreground'] = '#e8f300'
else:
lbl_seconds['foreground'] = '#ff0000'
root.update()
time.sleep(1)
for i in range(30, -1, -1):
lbl_seconds['foreground'] = 'white'
lbl_seconds['text'] = i
root.update()
time.sleep(0.5)
update()
root.mainloop()
Explanation
There are several errors in your code:
My advice is to never use time.sleep in conjunction with Tkinter. That makes the program inactive for the indicated time. That means the GUI won't draw or process events (such as clicks) until time passes.
Tkinter comes with a universal method (which every widget has) called after, whose first argument is the milliseconds to "wait" and the second is the function to call when the time passes. Any additional arguments will be passed to the function. This puts a function on hold without breaking the internal event loop.
Solution
The idea of this solution is to make a function call, the function will do what it has to do and call itself within 1000 milliseconds and so on until the counter (which we will have been passing as an argument) reaches 0.
I removed the imports not relevant to the test.
I did a test with 10 seconds countdown and it works fine!