How to use the Treeview widget to display hierarchical data in Tkinter Python

share link

by vsasikalabe dot icon Updated: Jul 7, 2023

technology logo
technology logo

Guide Kit Guide Kit  

The Tkinter library works with a Tkinter application. The tkinter import * command imports the library. The import * defines all the functions and built-in modules in the tkinter library. We can use these inbuilt methods in a particular application without importing them. We can construct an application using the Tkinter library widgets, functions, and methods. We must import tkinter as tk.import tkinter.ttk as ttk from tkinter.  

 

The Tkinter module plays a pivotal role. It is much needed to import the Tkinter module for initiating further applications. The main difference is that widget options for widget styling are no longer present. Like the text and canvas widgets, the treeview widget uses tags to modify the item's appearance in the tree.  

 

Python OS system function runs a command in the Python script, like running in the Shell. A graphical user interface (GUI) is an interface of a desktop. It communicates with computers. It performs various activities on desktop computers, laptops, and other mobile devices. The Treeview widget's purpose is to present a hierarchical structure of the folder. The user can move the mouse to show or hide any part of the structure.  

 

The parent items are added in the Treeview widget. The os.path.expander () function is used to expand a pathname. It represents the current user's home directory. This may be performed on any platform where users have a home directory. The window.mainloop() triggers Python to run the Tkinter event loop. This method is used for events, such as button clicks or keypresses. It blocks some codes after the running process until we close the window.  

 

The Treeview widget supports horizontal and vertical scrolling. It is per the options described in Scrollable Widget Options and the methods. Treeview instance Creates a new item and returns the item identifier of the created item. This method returns an empty string when the item specified is a top-level item. Otherwise, it returns the iid of that item's parent. Tkinter Treeview is a tabular data representation. It has all the properties of the table. Every item has a textual label, an optional image, and a list of data values. When we select a row and press the edit or delete button, it will perform the operations defined in the program.  

 

To use themed widgets, we need to use the class of the Tkinter module. Tkinter Treeview consists of the GUI toolkit tk. It provides an object-oriented approach for using it as part of the development. Adding or removing nodes helps when you want to and is very useful for many GUI applications. We can also create a Treeview scrollbar.  

 

Here is an example of how to use the Treeview widget to display hierarchical data in Tkinter Python:

Fig : Preview of the output that you will get on running this code from your IDE.

Code


i=3
...
new_folder(path,arrss,'item'+str(i))



def new_folder(path,arrs,values):
    print('item1 ->', treeview.exists('item1'), treeview.item('item1'))
    print(values, '->', treeview.exists(values))
    global i
    for arr in arrs:
        print(f"action: treeview.insert(values,'end',text=arr)")
        print(f"insert arguments: parent='{values}', index='end', text='{arr}'")



item1 -> True {'text': 'Documents', 'image': '', 'values': '', 'open': 0, 'tags': ''}
item3 -> False
action: treeview.insert(values,'end',text=arr)
insert arguments: parent='item3', index='end', text='file.ext'
Traceback (most recent call last):
...
    res = self.tk.call(self._w, "insert", parent, index, *opts)
_tkinter.TclError: Item item3 not found



from tkinter import *
import os
from tkinter import ttk


app = Tk()
app.title("GUI Application of Python")

ttk.Label(app, text="Treeview(hierarchical)").pack()

treeview = ttk.Treeview(app, show='tree')
treeview.pack(fill='both', expand=True)


def new_folder(parent_path, directory_entries,
               parent_iid, f_image, d_image):
    """Creates a graphical representation of the structure
    of subdirectories and files in the specified parent_path.

    Recursive tree building for large directories can take some time.

    :param parent_path: directory path, string
    :param directory_entries: List[str]
           a list containing the names of the entries in the parent_path
           obtained using os.listdir()
    :param parent_iid: unique identifier for a treeview item, string
    :param f_image: file icon, tkinter.PhotoImage
    :param d_image: directory icon, tkinter.PhotoImage
    :return: None
    """
    for name in directory_entries:
        item_path = parent_path+os.sep+name
        # optional: file does not exist or broken symbolic link
        #if not os.path.exists(item_path):
            #print("Skipped:", item_path)
            #continue
        if os.path.isdir(item_path):
            # set subdirectory node
            subdir_iid = treeview.insert(parent=parent_iid,
                                         index='end',
                                         text=name,
                                         image=d_image)
            try:
                # pass the iid of the subdirectory as parent iid
                # all files/folders found in this subdirectory
                # will be attached to this subdirectory node
                subdir_entries = os.listdir(item_path)
                new_folder(parent_path=item_path,
                           directory_entries=subdir_entries,
                           parent_iid=subdir_iid,
                           f_image=f_image,
                           d_image=d_image)
            except PermissionError:
                pass
        else:
            treeview.insert(parent=parent_iid,
                            index='end',
                            text=name,
                            image=f_image)
        print(item_path)


# png 16x16 -> base64 strings for tkinter.PhotoImage
file_img = """
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAABGdB
TUEAALGPC/xhBQAAAAl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fYVLbEIwk2gbQBpstxz0QOmq6mdXxxmUr1A8Wg4i8o
rLoWh2C3hvhxr5KcqhMLVMrRJ4eCX97irL/qFh6fdxkvQoAaj4yz
iTv17KsyYu8D8t7hg+q7fXahjr50GaWQawT7OkbDN3/u6JIflQxb
qXN8zzsQniv7tGGv9Czx/tz64gXIqcTCagoaqWxpcO/dKBzL4oTI
uu+QBYaaBX2DeBgyDoJmKQzIMyEVE5Wz8HXMO7W29tnnD8TiiS5A
HbIGPi1kJn3zZzdWLh2CoIKGZHRUlXJPzs29XVoy40SuC6p0lgyo
+PS4e/aM8835GHALDWvY2LVybAxcVs881XtAUEyjC8SEGPx7bfu2
4/mgzfwiEgSz4dcJixRxjq5YVtEM1r6oHiDGuP9RwHS1TOaP/tCj
/d+VL1STn8NNZQAAAABJRU5ErkJggg==
"""
file_image = PhotoImage(data=file_img)
dir_image = PhotoImage(data=dir_img)

# adds a parent item to the tree
# and returns the item's iid value (generated automatically)
parent_iid = treeview.insert(parent='',
                             index='0',
                             text='Documents',
                             open=True,
                             image=dir_image)

start_path = os.path.expanduser(r"~\Documents")
start_dir_entries = os.listdir(start_path)

# inserting items to the treeview
new_folder(parent_path=start_path,
           directory_entries=start_dir_entries,
           parent_iid=parent_iid,
           f_image=file_image,
           d_image=dir_image)

app.mainloop()

Instructions

Follow the steps carefully to get the output easily.

  1. Download and Install the PyCharm Community Edition on your computer.
  2. Create a new Python file on your IDE.
  3. Copy the snippet using the 'copy' button and paste it into your Python file.
  4. Remove code till line no.24
  5. Run the current file to generate the output.


I hope you found this useful.


I found this code snippet by searching for ' Recursively arrange all folders and files in a hierarchical treeview in tkinter ' in Kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. PyCharm Community Edition 2022.3.1
  2. The solution is created in Python 3.11.1 Version


Using this solution, we can able to use the Treeview widget to display hierarchical data in Tkinter Python with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to use the Treeview widget to display hierarchical data in Tkinter Python.

FAQ:  

1. What module do I need to import to use treeview python?  

  • from tkinter import ttk  
  • import tkinter as tk  

We can use the above modules to import Treeview Python.  

 

2. How do text and canvas widgets interact with treeview python?  

Canvas widget  

The Canvas widget lets us display various graphics on the application. It can draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs.  

Text Widget  

A text Widget is used when users want to insert multiline text fields. This widget can be used for various applications where multiline text is required. It can be messaging, sending or displaying information, and many other tasks. We can also insert media files such as images and links in the Textwidget.  

 

3. What GUI toolkit is used for treeview python?  

Tkinter Treeview provides an object-oriented approach. It helps the programmers to use it as part of the development.  

 

4. How do I create a Treeview widget in Python?  

If we create a Treeview widget, we can use Treeview(parent, columns) constructor to build the table. We can edit and delete the Treeview widget items. We can do so by selecting the item using a tree.selection() function. When you select an item is selected, we can perform specific operations to delete or edit the item.  

 

5. What type of data structure is used for creating a tree structure in Python?  

We create a tree data structure in Python using the concept of OS node. We designate one node as a root node and then add more as child nodes.  

 

6. What is the purpose of having a parent node within the tree structure?  

Parent Node:  

The node, a predecessor of any node, is called a Parent Node. The node with a branch from it to any other node is called the Parent node.  

Child Node:  

The node descendant of any node is called a Child Node. Any parent node can have any number of child nodes. 

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page