Skip to content
Advertisement

How to delete a label from tkinter after a countdown

I am trying to create a ten-second countdown that removes itself after it reaches zero. How and where do I put code to remove the label?

I have experimented with label.destroy() and label.forget(), but they do not work, creating an error message, most likely because they do not exist.

from tkinter import *

root = Tk()

def countdown(count):
    label['text'] = count
    if count > 0:
        root.after(1000, countdown, count-1)
    elif count == 0:
        label['text'] = 'Time Expired'

label = Label(root, anchor=CENTER, font=('Calibri', 48))
label.place(x=132, y=102)
countdown(10)
label.pack_forget()

I was hoping for the program to delete the label after it finished its task. However, it counts down, but does not remove itself.

Advertisement

Answer

If you want to see “Time expired” for 1 sec and then hide the label try this code:

from tkinter import *

root = Tk()
def countdown(count, label):
    label['text'] = count
    if count > 0:
        root.after(1000, countdown, count-1, label)
    elif count == 0:
        label['text'] = 'Time nExpired'
        root.after(1000, countdown, count-1, label)
    elif count < 0:
        label.destroy()

label = Label(root, anchor=CENTER, font=('Calibri', 48))
label.place(x=132, y=102)
countdown(10, label)
root.mainloop()

The main issue is that you do not wait for countdown function to finish execution cycle before hiding the label; One solution is that hiding instruction to be moved inside countdown function and executed in the last cycle.

Advertisement