如何清除除输入项目外的所有画布项目?

时间:2019-04-23 08:43:04

标签: python python-3.x tkinter tkinter-canvas

我想在tkinter中删除画布的所有元素(入口元素除外)。有什么办法吗?

1 个答案:

答案 0 :(得分:0)

一种方法是将每个小部件的引用存储在可独立操作的集合中。在这里,我们分别存储LabelButtonEntry。按下remove all but entry按钮后,除Entries

之外的所有小部件均被销毁。
import tkinter as tk


def remove_all_but_entries():
    for button in buttons:
        button.destroy()
    for label in labels:
        label.destroy()


root = tk.Tk()

labels = []
labels.append(tk.Label(root, text='make disappear example'))
for label in labels:
    label.pack()

buttons = []
buttons.append(tk.Button(root, text='start', command=lambda: print('button start')))
buttons.append(tk.Button(root, text='stop', command=lambda: print('button stop')))
buttons.append(tk.Button(root, text='remove all but entry', command=remove_all_but_entries))
for button in buttons:
    button.pack()

entries = []
entries.append(tk.Entry(root))
for entry in entries:
    entry.pack()

root.mainloop()