Mihkel
Mihkel

Reputation: 709

Why Am I Unable To Remove This Label (Tkinter)

I am just messing around and testing things in python. For one part of my proof of concept code for a bigger project I need to create and then remove labels. Unfortunately after I create the label and then try to remove it I get this error when I try to .destory() the labels:

AttributeError: 'NoneType' object has no attribute 'destroy'

I have heard that you can get this error if your label has nothing in it and so it is "None" but mine has text. Here is the code:

from tkinter import*
import random
import time

root = Tk()
root.geometry("800x500")
root.title("amazing")

def one():
    label1 = Label(root, text="one", font=("Comic Sans MS", 30),  fg="purple").pack()
    time.sleep(2)
    label1.destroy()

def two():
    label2 = Label(root, text="two", font=("Comic Sans MS", 30),  fg="purple").pack()
    time.sleep(2)
    label2.destroy()

def doit():
    rchoice = [two, one]
    selected = random.choice(rchoice)
    return selected()

Button = Button(root, text="Button", width=15, height=3, font=("Comic Sans MS", 20), fg="blue", bg="lightgreen", command=doit).pack(pady=50)

root.mainloop()

Upvotes: 1

Views: 883

Answers (1)

Miraj50
Miraj50

Reputation: 4407

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 random

root = 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()

Upvotes: 5

Related Questions