valvore92
valvore92

Reputation: 317

Image in treeview Tkinter library in Python

I'm creating treeview in Python tkinter library. I would like to have an icon of image next to every node which represent file. I have created function, but I don't know why image appears only in last node.

    def populate_tree(self, parent, fullpath, children):
    for child in children:
        cpath = os.path.join(fullpath, child).replace('\\', '/')

        if os.path.isdir(cpath):
            cid = self.tree.insert(parent, END, text=child,
                                   values=[cpath, 'directory'])
            self.tree.insert(cid, END, text='dummy')
        else:
            if (child != "Thumbs.db"):
                self.pic = ImageTk.PhotoImage(file=cpath)
                self.tree.insert(parent, END, text=child, image=self.pic,
                     values=[cpath, 'file','{} bajtów'.format(os.stat(cpath).st_size)])

enter image description here

And disappear if next node is extended...

enter image description here

Upvotes: 1

Views: 2686

Answers (1)

figbeam
figbeam

Reputation: 7176

I think this has to do with not saving references to the images. for every file you create a new image: self.pic = ImageTk.PhotoImage(file=cpath) and I guess Python creates a new object, and the objects representing the previous images gets garbage collected.

I made an example in which I create the images outside the function scope and then use them while creating the treeview items:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack()

# Create a list of thumbnail images associated with filenmes
thumbnails = ['thumb1.png','thumb2.png','thumb3.png']
images = []
for thumb in thumbnails:
    images.append(tk.PhotoImage(file=thumb))

def populate_tree():
    folder = tree.insert('', 'end', text='Folder')
    for i in range(3):
        filename = 'Image_' + str(i)
        tree.insert(folder, 'end', text=filename, image=images[i])

populate_tree()

In my example I use a list of thumbnails to make it simple. If you have many files you might want to use a dict to associate thumbnails and files.

Upvotes: 4

Related Questions