如何删除tkinter函数中创建的标签?dlttxt()函数实现遇阻
解决Tkinter中删除动态创建标签的问题
问题核心是你在svtxt()函数里创建的标签属于局部变量,函数执行结束后无法再引用这些标签,导致直接调用label.destroy()无效。解决方法是用一个全局列表存储所有动态创建的标签,之后在删除函数里遍历列表销毁每个标签。
修改步骤:
- 定义全局列表用于保存所有创建的标签
- 在
svtxt()中,每次创建标签后将其添加到列表 - 在
dlttxt()中,遍历列表销毁每个标签,同时清空列表并重置ycord
修改后的完整代码:
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 # 全局列表存储所有动态创建的标签 labels_list = [] def svtxt(): global ycord label = Label(root, text=entxt.get()) if entxt.get(): label.place(x=250, y=ycord) ycord += 22 # 将标签加入全局列表 labels_list.append(label) 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 ''' global ycord # 遍历销毁每个标签 for label in labels_list: label.destroy() # 清空列表并重置y坐标 labels_list.clear() ycord = 0 # 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()
内容的提问来源于stack exchange,提问作者NoFallToggled
相关产品推荐
相关产品推荐

