pythonuser-interfacetkintertreeviewicons

Tkinter treeview - how to add a icon at the beginning of text


We're all familiar with the treeview of modern computers. I want to add this look to my tkinter app using treeview to highlight what is a file and what is a folder by an image, followed by its name. But how do i do that?

What I want:

This is what I want:

What I've got:

What I currently have

This is two lines that i tried, but gave me errors.

folderLogo = tkinter.BitmapImage(file="icons/folder24.xbm")

self.treeOMine.insert(parent='', index=END, iid=rowid, text=path, tags=('even',), image=folderLogo)

I've also tried bmp ang png files, before i noticed xbm was what i needed.

I can see it mentioned everywhere, but I just cant seem to figure out how to proceed with it. Or am I misunderstanding anything here?

Quote: "Normally, you'll also specify the name of each item, which is the text displayed in the tree. Other options allow you to add an image beside the name, specify whether the node is open or closed, etc." (https://tkdocs.com/tutorial/tree.html)

Also https://docs.python.org/3/library/tkinter.ttk.html mentions the possibility of adding image. Which makes me really think it is possible.

enter image description here


Solution

  • You should use the image option, and provide an instance of PhotoImage:

    tree = ttk.Treeview(root)
    tree.pack(fill="both", expand=True)
    
    folder_image = tk.PhotoImage(file="folder.png")
    file_image = tk.PhotoImage(file="page.png")
    
    folder_a = tree.insert("", "end", text="Folder A", image=folder_image)
    tree.insert(folder_a, "end", text="File 1", image=file_image)
    tree.insert(folder_a, "end", text="File 2", image=file_image)
    tree.insert(folder_a, "end", text="File 3", image=file_image)
    

    enter image description here