Why Am I Unable To Remove This Label (Tkinter) Why Am I Unable To Remove This Label (Tkinter) tkinter tkinter

Why Am I Unable To Remove This Label (Tkinter)


There are a couple of problems with your code.

  1. If you try to print the value of the labels, you will realize that it is actually None. That's because you have used the pack() method just after you have defined the widget and pack() returns None. So, you need to separate them.

  2. Refrain from using sleep() in tkinter. It will freeze your mainloop. The way to do it is to use after().

Here is the working code.

from tkinter import *import randomroot = Tk()root.geometry("800x500")root.title("amazing")def one():    label1 = Label(root, text="one", font=("Comic Sans MS", 30),  fg="purple")    label1.pack()    label1.after(2000, label1.destroy)def two():    label2 = Label(root, text="two", font=("Comic Sans MS", 30),  fg="purple")    label2.pack()    label2.after(2000, label2.destroy)def doit():    rchoice = [two, one]    selected = random.choice(rchoice)    return selected()Button(root, text="Button", width=15, height=3, font=("Comic Sans MS", 20), fg="blue", bg="lightgreen", command=doit).pack(pady=50)root.mainloop()