4

Question: How does one create in tkinter.ttk.Treeview a node where the toggling arrow of the node is replaced by a defined image? That is, how do I get from my second picture to the first picture as shown below.

Problem: The New Mexico Tech Guide showed that tkinter.ttk.Treeview can create a folder directory as shown below:

To Achieve

Using the tkinter.ttk.Treeview .insert() method with an "image" keyword, I am only able to achieve the below. An image does appear on the left of the node text, but the image does not replace the arrow toggling the opening and closing of the node to reveal its descendants. I had assumed the image defined by the "image" keyword would replace the toggling arrows. But this did not happen.

Achieved so far

Test Code:

import os
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

class App(ttk.Frame):

    def __init__(self, master, path):

        ttk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self)
        ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.tree.heading('#0', text='Directory', anchor='w')

        abspath = os.path.abspath(path)
        i = './icon/Home-icon_16.gif'
        self.root_pic = tk.PhotoImage(file=i)
        root_node = self.tree.insert('', 'end', text='  Work Folder', open=True, image=self.root_pic)
        l1_node = self.tree.insert(root_node, 'end', text='level 1', open=True)
        l2_node = self.tree.insert(l1_node, 'end', text='level 2', open=True)
        l3_node = self.tree.insert(l2_node, 'end', text='level 3', open=True)
        l2a_node = self.tree.insert(l1_node, 'end', text='level 2a', open=True)
        l3a_node = self.tree.insert(l2a_node, 'end', text='level 3a', open=True)

        self.tree.grid(row=0, column=0)
        ysb.grid(row=0, column=1, sticky='ns')
        xsb.grid(row=1, column=0, sticky='ew')
        self.grid()

root = tk.Tk()
path_to_my_project = os.getcwd()
app = App(root, path=path_to_my_project)
app.mainloop()

Home-icon_16.gif:Home-icon_16.gif

Sun Bear
  • 7,594
  • 11
  • 56
  • 102

0 Answers0