Treeview Tkinter (ttk) – Python Tutorial

In this tutorial we will cover the ttk Tkinter Treeview Widget through a series of examples. The Treeview widget is used to display items in a tabular or hierarchical manner. It has support for features like creating rows and columns for items, as well as allowing items to have children as well, leading to a hierarchical format.


Tkinter ttk Treeview – Syntax

The syntax require to create a Tkinter Treeview Object.

tree = ttk.Treeview(container, **options)

Options that the Treeview Class accepts:

OptionDescription
columnsA list of column names.
displaycolumnsA list of column identifiers (either symbolic or integer indices) specifying which data columns are displayed and the order in which they appear, or the string “#all”.
heightThe number of rows visible.
paddingSpecifies the internal padding for the widget. Can be either an integer or a list of 4 values.
selectmodeOne of “extended”, “browse” or “none”. If set to “extended” (default), multiple items can be selected. If “browse”, only a single item can be selected at a time. If “none”, the selection cannot be changed by the user.
showA list containing zero or more of the following values, specifying which elements of the tree to display. The default is “tree headings”, i.e., show all elements.

Treeview Example# 1

In this example we will create a simple Treeview ttk Widget and fill in some data into it. We have some data already stored in a text file which will be reading and adding to the Treeview widget in our read_data() widget.

The Data

This is what the data looks like, stored in CSV format.

Bob,[email protected],20000
Harrison,[email protected],23000
Jane,[email protected],19000
Mark,[email protected],15000
Emilia,[email protected],27000
John,[email protected],21000
Morax,[email protected],0
Ali,[email protected],30000
Shaman,[email protected],5000
Coder,[email protected],25000

Using the Python split() function, we can easily break each line around the commas and obtain all three values (the name, email and salary) in a list.

Using the Python split() function on the first line would give us:

[ "Bob", "[email protected]", "20000" ]

Creating the Treeview Widget

Now let’s focus back on the actual Treeview widget.

        columns = ("email", "salary")

        self.tree= ttk.Treeview(frame, columns=columns ,height = 20)
        self.tree.pack(padx = 5, pady = 5)

As shown in the above code, we first need to define a list/tuple of column names. We have left out the column “Name” because there already exists a (default) column with a blank name. We will later rename it to “Name”.

We then assign that list/tuple to the columns option in Treeview. The height option defines the number of rows to be shown.

        self.tree.heading('#0', text='Name')
        self.tree.heading('email', text='Email')
        self.tree.heading('salary', text='Salary')

Next up we define the “headings”. There is a difference between column and heading, where the column is the actual column, whereas the heading is just the title of the column that appears when the widget is displayed. As you can see in the code above, we are giving each a column a name. “#0” is the name of the default column.

    def read_data(self):
        f = open("Data.txt", "r")

        for index, line in enumerate(f):
            temp = line.rstrip().split(',')
            self.tree.insert('', tk.END, iid = index, 
                                 text = temp[0], values = temp[1:])

Finally there is the read_data() function, which does everything we said before. We read the data line by line, using the rstrip() function to get rid of extra trailing spaces and newline characters, and then split(“,”) to split the line across the commas.

Finally we call the tree.insert() function, which takes many parameters. The first is the parent, which is left as an empty string if there is none. Second is the position where we want to add the new item. Right now we are just appending it, so we do tk.END, which appends it to the end.

Next is iid, which is the item ID used to later track the item in question. Then we have text to which we will assign the first value in the list (the name), and into value we will pass the the other 2 values we obtained from the file.

The complete code:

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import simpledialog


class Window:
    def __init__(self, master):
        self.master = master
        columns = ("email", "salary")

        self.tree= ttk.Treeview(self.master, columns=columns ,height = 20)
        self.tree.pack(padx = 5, pady = 5)

        self.tree.heading('#0', text='Name')
        self.tree.heading('email', text='Email')
        self.tree.heading('salary', text='Salary')

        self.read_data()


    def read_data(self):
        f = open("Data.txt", "r")

        for index, line in enumerate(f):
            temp = line.rstrip().split(',')
            self.tree.insert('', tk.END, iid = index, 
                                 text = temp[0], values = temp[1:])


root = tk.Tk()
window = Window(root)
root.mainloop()

The output: