Python offers a variety of Graphical User Interface (GUI) frameworks that are highly useful for developers when creating interactive applications.
These frameworks provide the tools necessary for building applications that can run on multiple operating systems, including Windows, Linux, and macOS. Among the most popular GUI frameworks available in Python are Tkinter, wxPython, and PyQt.
Each of these frameworks allows developers to create sophisticated and user-friendly interfaces with a wide range of widgets—components that facilitate user interaction with the application.
Treeview Widgets in Python GUIs
One of the most versatile and powerful widgets available in these GUI frameworks, particularly in Tkinter, is the Treeview widget. This widget is invaluable for visualizing and navigating through hierarchical data, similar to the directory structure in Windows Explorer.
A Treeview widget allows you to display data in a tree-like format, with expandable and collapsible nodes that represent different levels of the hierarchy. Each item in the tree can have multiple attributes, making it possible to represent complex data structures effectively.
In a Python GUI application, the Treeview widget is particularly useful for organizing and displaying large amounts of structured data. For example, you might use a Treeview to display the file system hierarchy, a table of contents, or any other nested data structure. The ability to display and interact with hierarchical data makes the Treeview widget an essential tool in many types of applications.
Constructing a Hierarchical Treeview in Python Using Tkinter
To create a hierarchical Treeview in a Python GUI application, Tkinter is often the toolkit of choice due to its simplicity and built-in support for the Treeview widget. In the following example, we will demonstrate how to construct a basic Treeview that can represent hierarchical data within a Tkinter application.
import tkinter as tk
from tkinter import ttk
# Create the main application window
root = tk.Tk()
root.title("Hierarchical Treeview Example")
# Create a Treeview widget
tree = ttk.Treeview(root)
# Define the columns
tree['columns'] = ("Size", "Modified")
# Format the columns
tree.column("#0", width=270, minwidth=150) # The first column is for the tree hierarchy
tree.column("Size", width=100, minwidth=50, anchor=tk.CENTER)
tree.column("Modified", width=150, minwidth=100, anchor=tk.CENTER)
# Create column headings
tree.heading("#0", text="Name", anchor=tk.W)
tree.heading("Size", text="Size", anchor=tk.CENTER)
tree.heading("Modified", text="Modified", anchor=tk.CENTER)
# Insert parent nodes
folder1 = tree.insert("", "end", text="Folder 1", values=("2 KB", "01/01/2023"))
folder2 = tree.insert("", "end", text="Folder 2", values=("5 KB", "02/01/2023"))
# Insert child nodes
tree.insert(folder1, "end", text="File 1-1", values=("1 KB", "01/01/2023"))
tree.insert(folder1, "end", text="File 1-2", values=("1 KB", "01/01/2023"))
tree.insert(folder2, "end", text="File 2-1", values=("2 KB", "02/01/2023"))
# Pack the Treeview into the main window
tree.pack(pady=20)
# Run the application
root.mainloop()
Output:

Let us see another example:
# Python program to illustrate the usage
# of hierarchical treeview in python GUI
# application using tkinter
# Importing tkinter
from tkinter import *
# Importing ttk from tkinter
from tkinter import ttk
# Creating app window
app = Tk()
# Defining title of the app
app.title("GUI Application of Python")
# Defining label of the app and calling a geometry
# management method i.e, pack in order to organize
# widgets in form of blocks before locating them
# in the parent widget
ttk.Label(app, text ="Treeview(hierarchical)").pack()
# Creating treeview window
treeview = ttk.Treeview(app)
# Calling pack method on the treeview
treeview.pack()
# Inserting items to the treeview
# Inserting parent
treeview.insert('', '0', 'item1',
text ='Codemagnet')
# Inserting child
treeview.insert('', '1', 'item2',
text ='Computer Science')
treeview.insert('', '2', 'item3',
text ='GATE papers')
treeview.insert('', 'end', 'item4',
text ='Programming Languages')
# Inserting more than one attribute of an item
treeview.insert('item2', 'end', 'Algorithm',
text ='Algorithm')
treeview.insert('item2', 'end', 'Data structure',
text ='Data structure')
treeview.insert('item3', 'end', '2020 paper',
text ='2020 paper')
treeview.insert('item3', 'end', '2021 paper',
text ='2021 paper')
treeview.insert('item4', 'end', 'Python',
text ='Python')
treeview.insert('item4', 'end', 'Java',
text ='Java')
# Placing each child items in parent widget
treeview.move('item2', 'item1', 'end')
treeview.move('item3', 'item1', 'end')
treeview.move('item4', 'item1', 'end')
# Calling main()
app.mainloop()
Output:
In this example, we create a simple Tkinter application with a Treeview widget that displays a hierarchical structure, similar to a file directory. Each node in the Treeview represents either a folder or a file, and nodes can have child nodes, creating a hierarchy.
The Treeview widget is configured with columns for displaying additional information (such as size and modified date), making it a powerful tool for representing and interacting with structured data.
By utilizing the Treeview widget in your Python GUI applications, you can create intuitive interfaces that allow users to easily navigate and manipulate complex data sets.
Now, let us check out some advance examples for the above:
Creating advanced and innovative hierarchical Treeview examples in Tkinter involves incorporating custom styling, adding features like drag-and-drop, expanding/collapsing all nodes, and integrating other widgets to enhance the GUI’s usability. Below are some advanced coding examples showcasing these features.
1. Custom Styled Treeview with Expand/Collapse All
This example demonstrates a Treeview with custom styling, an option to expand or collapse all nodes at once, and additional features like tooltips and context menus.
import tkinter as tk
from tkinter import ttk
class AdvancedTreeviewApp:
def __init__(self, root):
self.root = root
self.root.title("Advanced Treeview Example")
self.root.geometry("600x500")
self.create_treeview()
self.create_controls()
def create_treeview(self):
# Define a custom style for the Treeview
style = ttk.Style()
style.configure("Treeview",
background="#333333",
foreground="#ffffff",
rowheight=25,
fieldbackground="#333333",
font=("Arial", 10))
style.configure("Treeview.Heading",
background="#555555",
foreground="#ffffff",
font=("Arial", 12, "bold"))
style.map("Treeview",
background=[('selected', '#444444')])
# Create the Treeview widget
self.tree = ttk.Treeview(self.root, columns=("Size", "Modified"), selectmode="extended")
self.tree.heading("#0", text="Name", anchor=tk.W)
self.tree.heading("Size", text="Size", anchor=tk.W)
self.tree.heading("Modified", text="Modified", anchor=tk.W)
self.tree.column("#0", width=200, stretch=tk.NO)
self.tree.column("Size", width=100, anchor=tk.CENTER)
self.tree.column("Modified", width=150, anchor=tk.CENTER)
# Add the treeview to the window
self.tree.pack(fill=tk.BOTH, expand=True)
# Insert data into the treeview
folder1 = self.tree.insert("", "end", text="Folder 1", values=("2 KB", "01/01/2023"))
folder2 = self.tree.insert("", "end", text="Folder 2", values=("5 KB", "02/01/2023"))
folder3 = self.tree.insert("", "end", text="Folder 3", values=("3 KB", "03/01/2023"))
self.tree.insert(folder1, "end", text="File 1-1", values=("1 KB", "01/01/2023"))
self.tree.insert(folder1, "end", text="File 1-2", values=("1 KB", "01/01/2023"))
self.tree.insert(folder2, "end", text="File 2-1", values=("2 KB", "02/01/2023"))
self.tree.insert(folder3, "end", text="File 3-1", values=("3 KB", "03/01/2023"))
# Bind events for tooltips
self.tree.bind("<Motion>", self.on_motion)
self.tree.bind("<Leave>", self.on_leave)
def create_controls(self):
# Create buttons for expanding/collapsing all nodes
button_frame = tk.Frame(self.root, bg="#2c2c2c")
button_frame.pack(fill=tk.X)
expand_button = tk.Button(button_frame, text="Expand All", command=self.expand_all, bg="#4caf50", fg="white", font=("Arial", 10))
collapse_button = tk.Button(button_frame, text="Collapse All", command=self.collapse_all, bg="#f44336", fg="white", font=("Arial", 10))
expand_button.pack(side=tk.LEFT, padx=10, pady=10)
collapse_button.pack(side=tk.LEFT, padx=10, pady=10)
def expand_all(self):
# Expand all nodes in the treeview
for item in self.tree.get_children():
self.tree.item(item, open=True)
for child in self.tree.get_children(item):
self.tree.item(child, open=True)
def collapse_all(self):
# Collapse all nodes in the treeview
for item in self.tree.get_children():
self.tree.item(item, open=False)
for child in self.tree.get_children(item):
self.tree.item(child, open=False)
def on_motion(self, event):
# Get the item under the mouse
item = self.tree.identify_row(event.y)
if item:
# Display the tooltip
text = self.tree.item(item, "text")
self.show_tooltip(event, text)
else:
# Hide the tooltip if not over an item
self.hide_tooltip()
def show_tooltip(self, event, text):
if not hasattr(self, 'tooltip'):
self.tooltip = tk.Label(self.root, text=text, background="#444444", foreground="white", relief=tk.SOLID, borderwidth=1, padx=5, pady=5)
self.tooltip.config(text=text)
self.tooltip.place(x=event.x_root + 20, y=event.y_root + 10)
def hide_tooltip(self, event=None):
if hasattr(self, 'tooltip'):
self.tooltip.place_forget()
def on_leave(self, event):
# Hide tooltip when the mouse leaves the Treeview
self.hide_tooltip()
if __name__ == "__main__":
root = tk.Tk()
app = AdvancedTreeviewApp(root)
root.mainloop()
Output:


Features of this Example:
- Custom Styling: The Treeview is styled with a modern, dark theme that enhances the visual appeal of the application.
- Expand/Collapse All Buttons: Buttons are provided to expand or collapse all nodes in the Treeview, making it easier to navigate large hierarchies.
- Tooltips: Hovering over each item in the Treeview shows a tooltip with the item’s name, providing additional context and improving user experience.
Creating a hierarchical Treeview in Tkinter provides a powerful way to visualize and manage hierarchical data structures within a Python GUI application. The Treeview widget, part of Tkinter’s ttk module, is a versatile tool that allows for the display and manipulation of data in a tree-like format, making it ideal for applications that require a structured view of information.
In this guide, we explored how to effectively use the Treeview widget to create an interactive and user-friendly hierarchical structure. We covered the essentials of setting up a Treeview, including configuring columns, inserting and organizing items, and applying custom styles to enhance the visual appeal of the interface.
Key features discussed include:
- Custom Styling: Utilizing
ttk.Styleto create visually appealing Treeviews with customized fonts, colors, and row heights, ensuring that the widget integrates seamlessly with the overall look and feel of your application. - Dynamic Interactions: Implementing features such as drag-and-drop reordering and context menus to enhance user interaction, making the Treeview more functional and engaging.
- Tooltips and Feedback: Adding tooltips to provide additional context for each item, improving usability by giving users instant feedback on the data they are interacting with.
The detailed examples provided in the guide illustrate advanced techniques for working with the Treeview widget, demonstrating how to incorporate features like drag-and-drop, dynamic updates, and real-time progress bars. These enhancements not only improve the functionality of the Treeview but also contribute to a more interactive and intuitive user experience.
In summary, mastering the Treeview widget in Tkinter opens up a range of possibilities for developing sophisticated and responsive GUI applications. By leveraging the power of Tkinter and its Treeview widget, developers can build applications that effectively handle and present hierarchical data, providing users with a robust and visually appealing interface.





Leave a Reply