我想要一个干净高效的解决方案来删除/销毁嵌入式Canvas对象。当我说“嵌入的画布对象”时,是指已经包装到另一个画布中的画布。
我当前的解决方案是逐个手动删除每个画布(“ all”)。destroy()。该解决方案非常庞大,难以排序,维护,并且让我担心我没有适当地垃圾收集所有内容。
使用下面的代码进行的实验显示,删除对象本身(del(var))只会导致print(var)产生错误。否则在var.delete(“ all”)和var.destroy()之后,print(var)生成。!canvas
from tkinter import *
# some arbitrary arrangement of canvas objects
root = Tk()
root.geometry("1600x900")
# highest level
topLevel = Canvas(root, bg="blue")
topLevel.pack(fill=BOTH, expand=1)
# second level
redTop = Canvas(topLevel, bg="red")
redTop.pack(side=TOP, fill=X)
greenBottom = Canvas(topLevel, bg="green")
greenBottom.pack(side=BOTTOM, fill=X)
# third level
blackBox = Canvas(redTop, bg="black")
blackBox.pack(side=LEFT)
whiteBox = Canvas(greenBottom, bg="white")
whiteBox.pack(side=RIGHT)
mainloop()
# possible cleanup methods
def my_current_solution():
# starting with the leaf nodes and traversing back in order
blackBox.delete("all")
blackBox.destroy()
del blackBox
redTop.delete("all")
redTop.destroy()
del redTop
whiteBox.delete("all")
whiteBox.destroy()
del whiteBox
greenBottom.delete("all")
greenBottom.destroy()
del greenBottom
topLevel.delete("all")
topLevel.destroy()
del topLevel
def same_but_automated(list):
# assume list is made up of canvases inserted in proper order
for canvas in list:
canvas.delete("all")
canvas.destroy()
del canvas
def what_I_hope_is_okay():
# eliminating only the root *hopefully* does not cause a serious memory leak?
topLevel.delete("all")
topLevel.destroy()
del topLevel
没有错误消息,只想知道我是否不必要地阻塞了代码或内存。寻找更清洁,更简单,更有效的解决方案。