python – How to delete dynamically created elements?

Question:

I have problem removing / hiding dynamically created widgets in tkinter. This function generates the results of a search in tkinter, the problem is that they accumulate on top of each other. The idea is that each time the function is executed, it eliminates the labels created by the previous execution, if there was one. I have tried using the pack_forget () method except it was throwing the NameError exception and only removes the last label (search sometimes creates more than one). I don't know if all labels can be removed. I've tried putting a for loop on the pack_forget, but it still removes only one. I don't know if by element name (all labels have that name, label) it can be eliminated at once. Thanks a lot

def funcion():
    try:
        label.pack_forget()
    except:
        pass
    for i,url in enumerate(resultados_lista):
        v=tk.StringVar()
        tabName=tabControl.select()
        textWidget = tabControl.nametowidget(tabName)
        global label
        label=tk.Label(textWidget,textvariable=v, cursor="hand2")
        v.set(url)
        f = font.Font(label, label.cget("font"))
        f.configure(underline=True)
        label.pack(side=tk.BOTTOM)
        label.after(60000, label.pack_forget)
        label.bind("<Button-1>",lambda e,url=url:abrir_resultado(url))```

Answer:

Before the loop a labelframe is created:

group = tk.LabelFrame(tab1, text="Resultados", padx=10, pady=10)
group.pack(side=tk.BOTTOM)

… and instead of using label.pack_forget() use label.master.destroy() .

Scroll to Top