Python Tkinter TreeView – How to Use

In this Python tutorial, we will learn how to create Python Tkinter TreeView. Also, we will cover these topics:

  • What is Python Tkinter Treeview
  • Explaining Python Tkinter with an Example
  • How to change Value in Python Tkinter Treeview
  • How to add Scrollbars to Python Tkinter Treeview
  • How to use insert items in Python Tkinter Treeview
  • What is the role of Selection in Python Tkinter Treeview
  • Width in Python Tkinter Treeview
  • Python Tkinter Treeview Table
  • Height in Python Tkinter Treeview
  • Use of Selectmode in Python Tkinter Treeview

If you are new to Python Tkinter, check out Python GUI Programming.

What is Python Tkinter Treeview

  • Tkinter Treeview refers to hierarchical representation. When we have a relation between data in that case we have Treeview.
  • Python Tkinter Treeview gives an improved look to the data columns.
  • Python Tkinter Treeview is derived from tkinter.ttk module.
  • There is always one extra column created while creating Treeview. We call that column as ‘ghost column’. Note this is just for our reference.
python tkinter treeview demo
python tkinter treeview

Python Tkinter Treeview Example

Let us see the Python tkinter treeview example.

Code:

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws['bg']='#fb0'

tv = ttk.Treeview(ws)
tv['columns']=('Rank', 'Name', 'Badge')
tv.column('#0', width=0, stretch=NO)
tv.column('Rank', anchor=CENTER, width=80)
tv.column('Name', anchor=CENTER, width=80)
tv.column('Badge', anchor=CENTER, width=80)

tv.heading('#0', text='', anchor=CENTER)
tv.heading('Rank', text='Id', anchor=CENTER)
tv.heading('Name', text='rank', anchor=CENTER)
tv.heading('Badge', text='Badge', anchor=CENTER)

tv.insert(parent='', index=0, iid=0, text='', values=('1','Vineet','Alpha'))
tv.insert(parent='', index=1, iid=1, text='', values=('2','Anil','Bravo'))
tv.insert(parent='', index=2, iid=2, text='', values=('3','Vinod','Charlie'))
tv.insert(parent='', index=3, iid=3, text='', values=('4','Vimal','Delta'))
tv.insert(parent='', index=4, iid=4, text='', values=('5','Manjeet','Echo'))
tv.pack()


ws.mainloop()

Output:

python tkinter treeview demo
python tkinter treeview example

You may like, How to Create Countdown Timer using Python Tkinter?

Python Tkinter Treeview Change Value

  • In this section, we will learn how to change Python Tkinter Treeview Value.
  • There are two types of value in the case of Treeview.
  • One is the heading value that we see on the top of the table
  • Another is the record that we see on the table.
  • to change the heading value we have to change it in columns as well as in headings. for better understanding, we have marked both the things in the below figure.
  • We have assumed that we want to change the value of heading from 1 to something else.
python tkinter treeview change heading value
fig . 1.1 Python Tkinter Treeview Change Value
  • To change the value of the record, we have to create a function that will change the value of the selected item in the Python Tkinter Treeview.
  • In this section, we will be changing only one item of the record.
  • tkk.tree.focus returns the selected item row in the Treeview. If nothing is selected then it returns an empty string (“”).
  • ttk.tree.item() takes tkk.tree.focus as an argument followed by ‘value‘. This will return all the values in the selected item. These values are returned in a tuple.
  • We will understand this with an example wherein the salary of the selected employee will be incremented by 5% of the current.

Code:

In this code, please pay attention to the update_item function.

  • tv.focus() hold the row number of the selected item in Treeview & the value for the same is stored in a variable named selected. You can view that by using the print function. print(selected).
  • tv.item() takes 2 arguments, selected & values. This means from the selected row, show all the values. These values will be displayed in a tuple format. This is stored in a variable named temp.
  • by using temp[0], temp[1], temp[2] we can access the items in the tuple.
  • sal_up variable holds the calculation to increment the salary.
  • tv.item() method is used to provide new values to the record.
from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title("PythonGuides")

tv = ttk.Treeview(ws, columns=(1, 2, 3), show='headings', height=8)
tv.pack()

tv.heading(1, text="name")
tv.heading(2, text="eid")
tv.heading(3, text="Salary")

def update_item():
    selected = tv.focus()
    temp = tv.item(selected, 'values')
    sal_up = float(temp[2]) + float(temp[2]) * 0.05
    tv.item(selected, values=(temp[0], temp[1], sal_up))

tv.insert(parent='', index=0, iid=0, values=("vineet", "e11", 1000000.00))
tv.insert(parent='', index=1, iid=1, values=("anil", "e12", 120000.00))
tv.insert(parent='', index=2, iid=2, values=("ankit", "e13", 41000.00))
tv.insert(parent='', index=3, iid=3, values=("Shanti", "e14", 22000.00))

Button(ws, text='Increment Salary', command=update_item).pack()

style = ttk.Style()
style.theme_use("default")
style.map("Treeview")

ws.mainloop()

Output:

In this output, Python Tkinter Treeview is displayed. We have feed sample data of en employees. The button at the bottoms holds functionality to increment the salary of selected employee by 5%. Shanti did a great job she deserves an increment. Her previous salary was 22000 after applying 5% increment it becomes 23100.

python tkinter treeview update value
python tkinter treeview update value

Python Tkinter Treeview Scrollbars

Scrollbars are the complex term for beginners and is one of the widely used widget that you can’t ignore. So in this section of Python Tkinter Treeview, we will learn to create scrollbars for Treeview.

  • The best practice to implement a scrollbar is by using a frame widget.
  • Frame widget can hold other widgets. So we will place Treeview & Scrollbar widgets on the frame.
  • the command to create scrollbar: sb = Scrollbar(frame, orient=VERTICAL)
    • we are placing this widget in frame
    • orient decides whether scrollbars will be horizontal or vertical.
  • the command to place scrollbar on the screen is sb.pack(side=RIGHT, fill=Y)
    • Treeview will be packed to LEFT and Scrollbars to the RIGHT.
    • fill=Y will fill the scrollbar in the available space. This will make the scrollbar look larger than its actual size.
  • Configuring or binding scrollbar with Treeview is the most important step.
    • tv.config(yscrollcommand=sb.set) this command configures the Treeview and binds it with Scrollbar.
    • sb.config(command=tv.yview) this command configures the scrollbar and binds it with Treeview.

So in this way, we can implement the scrollbar with Treeview. Since we have used frame here so this method can be implement on any widget & you save yourself from confusion. I hope You have understood how to use scrollbars in Python Tkinter Treeview. We have also provides a small application with the implementation of scrollbar.

Note: If you have implemented the scrollbar correctly but still not showing up properly then please increase the number of rows in the data. Still not working please leave a comment.

Code:

In this code, we have carried forward the previous application of providing increment to employees. But this time we have more number of employees. Since the screen is not sufficient to display the entire data so we have used scrollbars.

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title("PythonGuides")


frame = Frame(ws)
frame.pack(pady=20)

tv = ttk.Treeview(frame, columns=(1, 2, 3), show='headings', height=8)
tv.pack(side=LEFT)

tv.heading(1, text="name")
tv.heading(2, text="eid")
tv.heading(3, text="Salary")

sb = Scrollbar(frame, orient=VERTICAL)
sb.pack(side=RIGHT, fill=Y)

tv.config(yscrollcommand=sb.set)
sb.config(command=tv.yview)

def update_item():
    selected = tv.focus()
    temp = tv.item(selected, 'values')
    sal_up = float(temp[2]) + float(temp[2]) * 0.05
    tv.item(selected, values=(temp[0], temp[1], sal_up))

tv.insert(parent='', index=0, iid=0, values=("vineet", "e11", 1000000.00))
tv.insert(parent='', index=1, iid=1, values=("anil", "e12", 120000.00))
tv.insert(parent='', index=2, iid=2, values=("ankit", "e13", 41000.00))
tv.insert(parent='', index=3, iid=3, values=("Shanti", "e14", 22000.00))
tv.insert(parent='', index=4, iid=4, values=("vineet", "e11", 1000000.00))
tv.insert(parent='', index=5, iid=5, values=("anil", "e12", 120000.00))
tv.insert(parent='', index=6, iid=6, values=("ankit", "e13", 41000.00))
tv.insert(parent='', index=7, iid=7, values=("Shanti", "e14", 22000.00))
tv.insert(parent='', index=8, iid=8, values=("vineet", "e11", 1000000.00))
tv.insert(parent='', index=9, iid=9, values=("anil", "e12", 120000.00))
tv.insert(parent='', index=10, iid=10, values=("ankit", "e13", 41000.00))
tv.insert(parent='', index=11, iid=11, values=("Shanti", "e14", 22000.00))

Button(
    ws, 
    text='Increment Salary', 
    command=update_item, 
    padx=20, 
    pady=10, 
    bg='#081947', 
    fg='#fff', 
    font=('Times BOLD', 12)
    ).pack(pady=10)

style = ttk.Style()
style.theme_use("default")
style.map("Treeview")

ws.mainloop()

Output:

In this output, the data is displayed in the Python Tkinter Treeview. You can see a scrollbar added to the window. No matter how much data is added to it but it can be viewed by scrolling the window.

python tkinter treeview scrollbar
Python Tkinter Treeview Scrollbars

Python Tkinter TreeView Insert

method of tkinter.ttk.Treeview instance Creates a new item and returns the item identifier of the newly created item.

Syntax:

insert(parent, index, iid=None, **kw)
  • the parent is the item ID of the parent item, or the empty string to create a new top-level item.
  • the index is an integer or the value end, specifying wherein the list of parent’s children to insert the new item. If the index is less than or equal to zero, the new node is inserted at the beginning and if the index is greater than or equal to the current number of children, it is inserted at the end.
  • iid is used as the item identifier, iid must not already exist in the tree. Otherwise, a new unique identifier is generated.

Python Tkinter Treeview Selection

  • Selection in Python Tkinter Treeview returns the tuple of selected items.
  • Selection method returns the row index of selected items in Treeview.
  • It can return more than one indexes at a time in a tuple format.
  • Selection is useful is many ways, the value of selection can be stored in a variable and then using if-else it can be put to condition.
  • After knowing the row, items of that row can be accessed or altered by providing then index number.
  • example: row[3], row[1], row[2]

Code:

In this code, please pay attention to the show_selected() function. here, print(tv.selection()) prints the selected row .

from tkinter import *
from tkinter import ttk

def show_selected():
    print(tv.selection())

ws = Tk()
ws.title('PythonGuides')

tv = ttk.Treeview(
    ws, 
    columns=(1, 2, 3), 
    show='headings', 
    height=3
    )
tv.pack()

tv.heading(1, text='roll number')
tv.heading(2, text='name')
tv.heading(3, text='class')

tv.insert(parent='', index=0, iid=0, values=(21, "Krishna", 5))
tv.insert(parent='', index=1, iid=1, values=(18, "Bhem", 3))
tv.insert(parent='', index=2, iid=2, values=(12, "Golu", 6))
tv.insert(parent='', index=3, iid=3, values=(6, "amul", 3))
tv.insert(parent='', index=4, iid=4, values=(12, "nestle", 6))
tv.insert(parent='', index=5, iid=5, values=(6, "zebronics", 3))

style = ttk.Style()
style.theme_use("default")
style.map("Treeview")


Button(ws, text="Show Selected", command=show_selected).pack()

ws.mainloop()

Output:

In this output, first we have selected one and clicked on the button. so in the output we can notice ('1',). This means row on index 1 is selected. Now when we selected two rows and clicked on the button it gave us ('1', '2') which means rows on index 1 and index 2 are selected as we can see in the figure.

python tkinter treeview selection
Python Tkinter Treeview Selection

Python Tkinter TreeView Width

In this section of Python Tkinter Treeview we will learn how to implement Width in Treeview.

  • Width is the horizontal length of each column in the Treeview.
  • A change in the width will lead to a change in the horizontal space of the application.
  • Width is declared under column section. It is not mandatory option.
  • by default each column has 20 pixels of width.

Python Tkinter Treeview Table

  • Python Tkinter Treeview is a tabular representation of the data as it has all the properties of the table.
  • Treeview has rows, columns, and heading.
    • rows: Horizontal space determined by the data. More data more rows.
    • columns: vertical space determines the heading. More headings more columns.
    • heading: Heading is the top row.

Python Tkinter Treeview Height

In this section of Python Tkinter Treeview we will learn how to implement height.

  • Height is the vertical length of the Treeview.
  • It also determines the number of rows in the Treeview
  • A change in the height will lead to a change in the number of rows displayed on the screen.

Syntax:

tv = ttk.Treeview(ws, columns=(1, 2, 3), show='headings', height=3)
tv.pack(side=LEFT)

Code:

In this code, we have set the height=5 that means only 5 rows will be displayed. We have also tried height=3. So you try by changing these values.

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title('PythonGuides')

tv = ttk.Treeview(
    ws, 
    columns=(1, 2, 3), 
    show='headings', 
    height=5
    #height=3
    )
tv.pack()

tv.heading(1, text='roll number')
tv.heading(2, text='name')
tv.heading(3, text='class')

tv.insert(parent='', index=0, iid=0, values=(21, "Krishna", 5))
tv.insert(parent='', index=1, iid=1, values=(18, "Bhem", 3))
tv.insert(parent='', index=2, iid=2, values=(12, "Golu", 6))
tv.insert(parent='', index=3, iid=3, values=(6, "amul", 3))
tv.insert(parent='', index=4, iid=4, values=(12, "nestle", 6))
tv.insert(parent='', index=5, iid=5, values=(6, "zebronics", 3))

style = ttk.Style()
style.theme_use("default")
style.map("Treeview")

ws.mainloop()

Output:

In this output, two pictures are displayed. First image has height=5 and the second image has height=3.

Python Tkinter Treeview Height
Python Tkinter Treeview Height

Python Tkinter TreeView Selectmode

In this section, we will understand what is Selectmode & types of Selectmode in Python Tkinter Treeview.

  • Selectmode controls how the built-in class bindings manage the selection. There are three ways to do so:
    • extended: allows the user to select multiple items.
    • browse: allows only a single selection of items at a time.
    • none: The selection will not be changed, the user will click but nothing will be selected.

Syntax:

in place of “none“, extended or browse can be put as per the use.

tv = Treeview(ws, selectmode="none")
tv.pack()

Code:

In this code, we have implemented all the three methods of Python Tkinter Selectmode. We have dedicated three buttons each with different task.

  • When none button is clicked then user will not see any markings on the Treeview.
  • When browse button is clicked the user will be able to select single item at a time.
  • When extended button is clicked the user will be able to select multiple items at the same time.
  • press and hold the shift key on the keyboard to select multiple items.
from tkinter import *
from tkinter import ttk


def selectmode_none():
    tv['selectmode']="none"

def selectmode_browse():
    tv['selectmode']="browse"

def selectmode_extended():
    tv['selectmode']="extended"

ws = Tk()

tv = ttk.Treeview(
    ws, 
    columns=(1, 2, 3), 
    show='headings', 
    height=8
    )
tv.pack()

tv.heading(1, text='roll number')
tv.heading(2, text='name')
tv.heading(3, text='class')

tv.insert(parent='', index=0, iid=0, values=(21, "Krishna", 5))
tv.insert(parent='', index=1, iid=1, values=(18, "Bhem", 3))
tv.insert(parent='', index=2, iid=2, values=(12, "Golu", 6))
tv.insert(parent='', index=3, iid=3, values=(6, "Priya", 3))


b1 = Button(
    ws, 
    text="Browse",
    pady=20,
    command=selectmode_browse
    )
b1.pack(side=LEFT, fill=X, expand=True)


b2 = Button(
    ws, 
    text="None",
    pady=20,
    command=selectmode_none
    )
b2.pack(side=LEFT, fill=X, expand=True)


b3 = Button(
    ws, 
    text="Extended",
    pady=20,
    command=selectmode_extended
    )
b3.pack(side=LEFT, fill=X, expand=True)

style = ttk.Style()
style.theme_use("default")
style.map("Treeview")

ws.mainloop()

Output:

In this output, a simple Python Tkinter Treeview application is displayed. There are three buttons at the bottom that will change the selectmode of the Treeview.

python tkinter treeview selectmode
Python Tkinter TreeView Selectmode

You may like the following Python tkinter tutorials:

In this tutorial, we have learned about Python Tkinter Treeview. Also, we have covered these topics:

  • What is Python Tkinter Treeview
  • Explaining Python Tkinter with an Example
  • How to change Value in Python Tkinter Treeview
  • How to add Scrollbars to Python Tkinter Treeview
  • How to use insert items in Python Tkinter Treeview
  • What is the role of Selection in Python Tkinter Treeview
  • Width in Python Tkinter Treeview
  • Python Tkinter Treeview Table
  • Height in Python Tkinter Treeview
  • Use of Selectmode in Python Tkinter Treeview