根据
文档 (以及
BryanOakley的评论),图像对象可以在支持
image
选项的小部件(例如标签、按钮、菜单)中使用。在这些情况下,
Tk不会保留对图像的引用。当最后一个Python引用被删除时,图像数据也会被删除,并且Tk将在使用图像的地方显示一个空框。虽然
BryanOakley的建议绝对是最简单的解决方案,但它会阻止未使用的图像被垃圾回收,可能是不想要的。请注意:我的建议是假设
self.listBox
是一个
Text
小部件,因为
Listbox
小部件没有
image_create
方法。如果您正在使用不同类型的小部件,则仍可以制作类似的类来处理使用的图像并保留引用。你可以制作一个
Text
的子类来保留插入的图像的引用,覆盖相关方法(
image_create
和
delete
是最重要的)。
from tkinter import Text
class Text_autoReferenceImage(Text):
def __init__(self,*varg,**kw):
self.images = {}
Text.__init__(self,*varg,**kw)
def image_create(self,index,**options):
img = options.get("image",None)
name = Text.image_create(self,index,**options)
if img is not None:
self.images[name] = img
return name
def delete(self,*varg,**kw):
Text.delete(self,*varg,**kw)
self.clean_up_images()
def clean_up_images(self):
"""deletes reference to all images that are no longer present in Text widget (called by .delete())"""
images_still_in_use = self.image_names()
for name in set(self.images.keys()):
if name not in images_still_in_use:
del self.images[name]
def destroy(self):
self.images.clear()
return Text.destroy(self)
如果
self.listBox
是这个类的实例而不是
Text
,它将为您处理图像引用。
global images; ... images = []; ... images.append(img) ...
- Bryan Oakley