Why Am I Unable To Remove This Label (Tkinter)
There are a couple of problems with your code.
If you try to print the value of the labels, you will realize that it is actually
None
. That's because you have used thepack()
method just after you have defined the widget andpack()
returns None. So, you need to separate them.Refrain from using
sleep()
in tkinter. It will freeze your mainloop. The way to do it is to useafter()
.
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()