Home > Software engineering >  How to delete a label packing in a function
How to delete a label packing in a function

Time:09-27

long story short i got stuck in how i will fill the dlttxt() function which is to clear all the packed labels but its backed in another function so label.destroy() dosen't work.

from tkinter import *
from tkinter import ttk

# setting the window up
root = Tk()
scrw, scrh = root.winfo_screenwidth(), root.winfo_screenheight()
root.title('note app')
root.geometry('500x500-{} {}'.format(int(scrw/2-250), int(scrh/2-270)))
root.resizable(False, False)
# ---------------------
# setting images
eyeon = PhotoImage(file = 'tk_imgs/eyeon.png',)
eyeoff = PhotoImage(file = 'tk_imgs/eyeoff.png',)
# ------------

ycord = 0
def svtxt():
    global ycord
    label = Label(root, text=entxt.get())
    if entxt.get():
        label.place(x=250, y=ycord)
        ycord  = 22

onoff = False
def chngtxt():
    global onoff
    if onoff:
        entry.config(show='*')
        showtxt.config(image=eyeoff)
        onoff = False
    else:
        entry.config(show='')
        showtxt.config(image=eyeon)
        onoff = True

def dlttxt():
    '''this function has to
    delete all the packed labels
    '''



# setting entry widget
entxt = StringVar()
entry = Entry(root, borderwidth=4, textvariable=entxt, show='*')
entry.place(x=0, y=0) 
entry.focus()
# ------------

# setting show text button
showtxt = Button(root, command=chngtxt, pady=5, image=eyeoff)
showtxt.place(x=200, y=-2)
# ------------

#  setting save text button
sbutton = Button(root, text='save text', command=svtxt)
sbutton.place(x=50, y=35)
# ------------

# setting delete text button
dbutton = Button(root, text='Delete all', command=dlttxt)
dbutton.place(x=49, y=66)
# ------------



root.mainloop()

CodePudding user response:

just save them in another list, then destroy them.

labels_list = []
def svtxt():
    global ycord
    label = Label(root, text=entxt.get())
    if entxt.get():
        label.place(x=250, y=ycord)
        labels_list.append(label)
        ycord  = 22

def dlttxt():
    '''this function has to
    delete all the packed labels
    '''
    global labels_list
    while len(labels_list) != 0:
        cur_label = labels_list.pop()
        cur_label.place_forget()
        cur_label.destroy()

i am guessing you also have to reset ycord to 0 (make sure you global it first), but that's up to you.

  • Related