Search code examples
python-3.xtkinterlabelattributeerror

Make tkinter Label disappear after time - "NoneType" Object has no attribute "destroy"


please excuse if the following problem is a super stupid mistake on my side. Im very new to coding and despite some similar problems here which have been solved already, I still can't figure out, why Im running into the following Error message within my specific code:

Exception in Tkinter callback Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/init.py", line 1883, in call return self.func(*args) File "/Users/Tomasz/Desktop/Code/04_OtherCodes/patch_app/app.py", line 64, in clear_inputs master.after(2000, vis.destroy()) AttributeError: 'NoneType' object has no attribute 'destroy'

Basically I'm trying to write a function, which clears all inputs in a tkinter form and displays a success message below. In order to being able to reuse the grid for more messages later on, I have to get rid of the message after a certain (short) time - let's say 2 seconds. Here is what I got so far:

from tkinter import *
import pandas as pd

master = Tk()
master.title("Patch Organizer")
master.geometry("620x500")
message = ""

### Defining several variables and input Fields in between
### And listing them all in a list input_fields = [entry1, entry2, entry3, etc]


def clear_inputs():
    global input_fields, message
    for field in input_fields:
        field.delete(0, END)

    message = "All clear - let's start all over!"
    vis= Label(master, fg = "green", text= message).grid(row=4,column=1)
    master.after(2000, vis.destroy())

mainloop()

Why cant I call the method destroy on tkinters Label Object? And maybe there is also a better way? Like calling a function which sets the message again back to an empty string?

Thanks so much for your help!

Cheers jaq


Solution

  • First you need to do the grid method seperate and then you need to put lambda before the command, otherwise it happens immediately.

    from tkinter import *
    import pandas as pd
    
    master = Tk()
    master.title("Patch Organizer")
    master.geometry("620x500")
    message = ""
    
    ### Defining several variables and input Fields in between
    ### And listing them all in a list input_fields = [entry1, entry2, entry3, etc]
    
    def clear_inputs(event):
        message =("All clear - let's start all over!")
        vis= Label(master, fg = "green", text= message)
        vis.grid(row=4,column=1)
        master.after(2000, lambda:vis.destroy())
    
    e1 = Entry(master)
    e1.grid()
    e1.bind("<Return>", clear_inputs)
    
    
    
    mainloop()