作爲the documentation狀態:無論一個image
選項是由一些小部件支持(和comment by @BryanOakley)
然後圖像對象可以被使用(例如標籤,按鈕,菜單)。在這些情況下,Tk將不會保留對圖像的引用。刪除圖像對象的最後一個Python引用時,圖像數據也會被刪除,並且無論使用圖像的哪個位置,Tk都會顯示一個空框。
雖然suggestion by @BryanOakley肯定是最簡單的解決方案,它可以防止未使用的圖像從所收集的被垃圾這可能是不希望的。
注:我建議的解決方案是假設self.listBox
是Text
小部件,因爲Listbox
小部件不具有image_create
方法。如果您使用的是不同類型的小部件,那麼您仍然可以創建一個類似的類來處理引用所使用的圖像。
你可以做的Text
一個子類,它保持到通過覆蓋相關的方法插入圖像的參考(image_create
和delete
是最重要的):
from tkinter import Text #, PhotoImage, Tk
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 #this may remove previous reference with same name but different image
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()): #need to put .keys() into a set in python3 or it complains about dictionary changing size during iteration
if name not in images_still_in_use:
del self.images[name]
def destroy(self):
self.images.clear() #remove all references to own images
return Text.destroy(self)
那麼如果self.listBox
是這個類的一個實例而不是Text
它將爲您處理圖像參考。
如果你沒有保存對每個的引用,他們可能被垃圾收集。 –
我該怎麼辦?如何引用他們每個人? – user6036956
即時通訊創建聊天消息在哪裏你可以發送圖像 – user6036956