Python Tkinter Treeview


from tkinter import ttk
What is ttk ?

Treeview tree
ttk.Treeview displays a hierarchical collection of items and also displays tabular data. We can add child node so can create a view which can be expanded.

Tkitner Treeview to get Parent Child nodes and display data in hierarchical order

Here is a basic Treeview with tree.
from tkinter import ttk
import tkinter as tk
# Creating tkinter my_w
my_w = tk.Tk()
my_w.geometry("260x280") 
my_w.title("www.plus2net.com")  
# Using treeview widget
trv = ttk.Treeview(my_w, selectmode ='browse')
trv.grid(row=1,column=1,padx=30,pady=20)

# column identifiers 
trv["columns"] = ("1", "2")
# Defining headings, other option is tree
trv['show'] = 'tree' 
# width of columns and alignment 
trv.column("#0", width = 80, anchor ='c')
trv.column("1", width = 10, anchor ='c')
trv.column("2", width = 100, anchor ='c')
# Headings  
# respective columns
trv.heading("#0", text ="Label",anchor='c')
trv.heading("1", text ="id")
trv.heading("2", text ="Name",anchor='c')

trv.insert("",'end',iid=1,text='First',values=(1,'n1-Alex'))
trv.insert("",'end',iid=2,text='second',values=(2,'n2-Ravi'))
trv.insert("",'end',iid=3,text='third',values=(3,'n3-Ronn'))

my_w.mainloop()
Watch the column with #0, this column will display in Tree and show the text part given in each row. The line saying trv['show'] = 'tree' can take the value as headings trv['show'] = 'headings' and the column with #0 will be hidden.

show option: trv['show'] = 'tree' 🔝

headings: Show the headings without the column marked as #0
tree: Show tree view with expanding the child node. No header row.
tree headings : (Default) Show both heading and expanding child node.
'' : Neither tree view nor headings are shown.

Treeview headings

Parent-child node 🔝

We can set the parent and child rows or nodes to the Treeview.
Treeview Parent-child nodes

Getting list of data from Treeview 🔝

my_list=[]           
for child in trv.get_children():
    my_list.append(trv.item(child)["values"][1])
    #print(trv.item(child)["values"])
    #print(trv.item(child)["values"][1]) # for Name
print(my_list)

On select event of treeview 🔝

def data_collect():
    print("hi")
    p_id = trv.selection()[0] # collect selected row id
trv.bind("<<TreeviewSelect>>", data_collect())  

Displaying selected item value 🔝

def show():
    p_id = trv.selection()[0] # collect selected row id
    print(trv.item(p_id)) # Dictionary of all options
    print(trv.item(p_id)['values']) # List of values
b1=tk.Button(my_w,text='Show',command=show)
b1.grid(row=2,column=1)

Adding Buttons to move UP or DOWN the row selection 🔝

Buttons to move UP or DOWN row selection in Tkinter Treeview
from tkinter import ttk
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("450x380")  # width and height of window
my_w.title("www.plus2net.com")  # title of the window
i=0
def my_move(direction):
    global i
    if(direction=='Up'): # Up button is clicked
        i=int(i)-1
    else:
        i=int(i)+1
    trv.selection_set(i)
bt1=tk.Button(my_w,text='Up',command=lambda:my_move('Up'))
bt1.grid(row=1,column=0,padx=5,pady=10)
bt2=tk.Button(my_w,text='Down',command=lambda:my_move('Down'))
bt2.grid(row=1,column=1,padx=5,pady=10)

trv=ttk.Treeview(my_w,selectmode='browse',show='headings')
trv.grid(row=2,column=0,columnspan=3,padx=30,pady=10)
# column identifiers
trv["columns"] = ("1", "2","3","4")
trv.column("1", width = 50, anchor ='w')
trv.column("2", width = 150, anchor ='c')
trv.column("3", width = 100, anchor ='c')
trv.column("4", width = 70, anchor ='c')

trv.heading(1, text ="id",anchor='w')
trv.heading(2, text ="Name",anchor='c')
trv.heading(3, text ="Class",anchor='c')
trv.heading(4, text ="Mark",anchor='c')

trv.insert("",'end',iid=1,values=(1,'Alex1','Four',78))
trv.insert("",'end',iid=2,values=(2,'Alex2','Four',80))
trv.insert("",'end',iid=3,values=(4,'Alex3','Four',78))
trv.insert("",'end',iid=4,values=(5,'Alex4','Five',80))
trv.insert("",'end',iid=5,values=(6,'Alex5','Sixr',40))
trv.insert("",'end',iid=6,values=(7,'Alex6','Four',70))
trv.insert("",'end',iid=7,values=(8,'Alex7','Three',50))

#trv.selection_set('b')
#p_id=trv.selection()[0]
#print(p_id)
def data_collect(*args):
    global i
    i=trv.selection()[0] #iid value of the selection 
    print(i)
trv.bind("<>",data_collect) # On select event or row

my_w.mainloop()

Edit and update selected item value 🔝

Update data for selected Node
Here only the Name column data we will select and update. We kept one button to show the selected node value and another button to Update the name of the selected node.
def show():
    p_id = trv.selection()[0] # collect selected row id
    print(trv.item(p_id)) # Dictionary of all options
    print(trv.item(p_id)['values']) # List of values
def upd():
    p_id = trv.selection()[0] # collect selected row id
    trv.item(p_id, values=[trv.item(p_id)['values'][0],e1.get()])
b1=tk.Button(my_w,text='Show',command=show)
b1.grid(row=2,column=2)    
e1=tk.Entry(my_w)
e1.grid(row=3,column=1)
b1=tk.Button(my_w,text='Update',command=upd)
b1.grid(row=3,column=2)
Full code to Edit selected item of treeview is here

Reading all rows of Treeview 🔝

for line in trv.get_children():
        print(trv.item(line)['values'])
For specific column value we can use like this
print(trv.item(line)['values'][3])

Delete all items ( rows ) of Treeview 🔝

get_children() returns the list of children belonging to item. If item is not specified, returns root children.
Here we are removing all rows.
for item in trv.get_children():
        trv.delete(item)
or
trv.delete(*trv.get_children())# delete all rows from treeview

Attributes of Treeview 🔝

OptionsDetails
columnsColumn identifier strings. These are in addition to the icon column
cursorShape of the cursor when mouse is over it. A list of available cursor shapes are here.
displaycolumnsSelect columns to be displayed and the order
heightNumber of rows ( default value is 10 ).
paddingExtra space around the data inside the widget
selectmodebrowse | extend | none ,
browse : Select one item only
extend : Select more than one item
none : No selection
takefocusTrue | False , specify whether the widget is visited during focus traversal

Wrapping text 🔝

We have imported textwrap module. Added style to give the rowheight and created one function to wrap the text.
from tkinter import *
from tkinter import ttk
import textwrap
def wrap(string, length=20):
    return '\n'.join(textwrap.wrap(string, length))
my_w = Tk()
trv = ttk.Treeview(my_w, height=3)
trv['show'] = 'headings'
s = ttk.Style()
s.configure('Treeview', rowheight=60)
trv["columns"] = ("1", "2")
trv.column("1", width=100)
trv.column("2", width=100)
trv.heading("1", text="col 1")
trv.heading("2", text="col 2")
item = trv.insert("", "end", values=(wrap("This is long text,i want to wrap"),
                                         wrap("and this text also length is more")))
item = trv.insert("", "end", values=("No wrap","No Wrap"))
trv.grid(row=0, column=0)
my_w.mainloop()
Output is here.
Treeview with text wrpping

Adding scrollbar to Treeview 🔝

Vertical Scrollbar for Treeview
Since Treeview is used to show tabular data, we may have to show more rows by allowing the user to scroll up or down by using scrollbar.
vs = ttk.Scrollbar(my_w,orient="vertical", command=trv.yview)#V Scrollbar
trv.configure(yscrollcommand=vs.set)  # connect to Treeview
vs.grid(row=1,column=2,sticky='ns')
How Vertical scrollbar is added to Treeview while displaying MySQL records

Adding horizontal Scrollbar 🔝

Update the column stretch=False
trv.column(i, anchor ='c', width=20,stretch = False)
hs = ttk.Scrollbar(my_w,orient="horizontal", command=trv.xview)#H Scrollbar 
trv.configure(xscrollcommand=hs.set)  # connect to Treeview
hs.grid(row=2,column=1,sticky='ew')

Using Google sheets data with Treeview 🔝

Treeview data from Python Google sheets
We can collect data from google sheet and use as data for a Treeview by using pygsheets library and google drive API.
Data of Treeview from Google sheet data


Using Excel data with Treeview 🔝

Treeview data from MS Excel
We can collect data from MS Excel by using openpyxl library and use as data for a Treeview
Excel Data to create Treeview
Managing style of Treeview Treeview insert Adding image to Treeview Adding row to Treeview after inserting to MySQL table Records of MySQL Pagination of Records of MySQL Delete Records Update Record Treeview using data from Google sheet Select -Edit-update MySQL Product table using Treeview Dynamic Creation of Header & Columns in Treeview ( with different sources of data ) Query window & displaying records in Treeview Generating Invoice by adding products using Treeview Showing directory and file structure using Treeview Showing record details in a Treeview Treeview Columns sorting using Pandas DatraFrame
Tkinter Report - Monthly
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer