[英]Unable to display images in Tkinter Treeview properly
I want my method to pull images from a sqlite database and display them as an image for the particular row in a Treeview.我希望我的方法从 sqlite 数据库中提取图像,并将它们显示为 Treeview 中特定行的图像。 Unfortunately, it's only displaying the image in the last row inserted.不幸的是,它只显示插入的最后一行中的图像。 I defined a singular image outside of the loop and it displayed an image on each row as I wanted.我在循环之外定义了一个单一的图像,它根据我的需要在每一行显示一个图像。 This leads me to believe that when I dynamically define the image in the loop, the images are getting garbage collected.这让我相信,当我在循环中动态定义图像时,图像会被垃圾收集。 In order for me to pull images from the database and place them in the Treeview, I can't have a single image definition outside the loop, but I'm not sure how to prevent garbage collection otherwise.为了让我从数据库中提取图像并将它们放在 Treeview 中,我不能在循环之外有单个图像定义,但我不确定如何防止垃圾收集。
Note: db.getdata()
is a function from another file that returns.fetchall() from the database.注意: db.getdata()
是来自另一个文件的 function,该文件从数据库返回.fetchall()。
def update_records(self):
records = self.dbTree.get_children()
for element in records:
self.dbTree.delete(element)
db_rows = db.get_data()
#img = PhotoImage(file = 'earth.gif').subsample(30, 30)
for row in db_rows:
img = tk.PhotoImage(data=row[5]).subsample(20, 20)
self.dbTree.insert('', 0, text = row[0], values = (row[1], row[2], row[3], row[4]), image
= img)
self.dbTree.image = img
Since you used same attribute self.dbTree.image
to save the reference of images, only the last image will be kept and the others are garbage collected.由于您使用相同的属性self.dbTree.image
来保存图像的引用,因此只保留最后一张图像,其他图像被垃圾收集。
Use a dictionary to store the images:使用字典存储图像:
self.dbTree.images = {}
for row in db_rows:
img = tk.PhotoImage(data=row[5]).subsample(20, 20)
self.dbTree.insert('', 0, text=row[0], values=(row[1], row[2], row[3], row[4]), image=img)
self.dbTree.images[row[0]] = img
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.