from tkinter import ttk
What is ttk ?
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.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.
headings: Show the headings without the column marked as #0tree: 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.
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)
def data_collect():
print("hi")
p_id = trv.selection()[0] # collect selected row id
trv.bind("<<TreeviewSelect>>", data_collect())
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)
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("<<TreeviewSelect>>",data_collect) # On select event or row
my_w.mainloop()

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
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])
for item in trv.get_children():
trv.delete(item)
or
trv.delete(*trv.get_children())# delete all rows from treeview
The delete() method removes all selected items from both the Treeview display and the widget's internal memory. This action is permanent for the widget, meaning you must re-insert the data from your source if you need to display those rows again.
| Attribute | Description | Example |
|---|---|---|
columns |
Specifies the column identifiers in the Treeview. Columns are used to display additional data for each item. | tree = ttk.Treeview(columns=('Name', 'Age')) |
cursor |
Specifies the cursor to be displayed when hovering over the Treeview. | tree = ttk.Treeview(cursor='hand2') |
height |
Specifies the number of visible rows in the Treeview widget. | tree = ttk.Treeview(height=15) |
padding |
Adds padding around the Treeview widget (useful for layout purposes). | tree = ttk.Treeview(padding=(10, 10, 10, 10)) |
selectmode |
Defines the selection behavior. Options: 'browse', 'extended', 'none'. |
tree = ttk.Treeview(selectmode='extended') |
show |
Controls which parts of the Treeview are visible. Options are 'tree', 'headings', or both. |
tree = ttk.Treeview(show='headings') |
style |
Specifies the style of the Treeview, such as background and text color. | tree = ttk.Treeview(style='Custom.Treeview') |
takefocus |
Specifies whether the widget can accept focus during keyboard navigation. | tree = ttk.Treeview(takefocus=True) |
xscrollcommand |
Links the horizontal scrollbar to the Treeview widget. |
scrollbar = ttk.Scrollbar(orient='horizontal', command=tree.xview)
|
yscrollcommand |
Links the vertical scrollbar to the Treeview widget. |
scrollbar = ttk.Scrollbar(orient='vertical', command=tree.yview)
|
selectmode and cursor enhance the usability of the Treeview widget.The following table lists commonly used Tkinter Treeview methods, along with their descriptions and examples for better understanding.
| Method | Description | Example |
|---|---|---|
insert(parent, index, iid=None, text='', values=()) |
Inserts a new item into the Treeview under the specified parent. | tree.insert('', 'end', text="Row 1", values=("Value 1", "Value 2")) |
delete(item) |
Deletes an item or multiple items from the Treeview. | tree.delete('item_id') |
item(item, option=None, **kw) |
Retrieves or sets an item's attributes, such as text or values. | tree.item('item_id', 'values') |
parent(item) |
Returns the parent of the specified item. | tree.parent('item_id') |
children(item) |
Returns a tuple of all children of the specified item. | tree.children('item_id') |
move(item, parent, index) |
Moves an item to a new parent and position. | tree.move('item_id', 'new_parent_id', 'end') |
selection() |
Returns the currently selected items as a tuple of item IDs. | selected_items = tree.selection() |
selection_set(items) |
Sets the selection to the specified items. | tree.selection_set(('item1', 'item2')) |
selection_add(items) |
Adds the specified items to the current selection. | tree.selection_add('item_id') |
selection_remove(items) |
Removes the specified items from the current selection. | tree.selection_remove('item_id') |
selection_clear() |
Clears all selections in the Treeview. | tree.selection_clear() |
yview_moveto(fraction) |
Scrolls the Treeview vertically to the specified position (0.0 to 1.0). | tree.yview_moveto(0.5) |
xview_moveto(fraction) |
Scrolls the Treeview horizontally to the specified position. | tree.xview_moveto(0.2) |
yview_scroll(number, what) |
Scrolls vertically by the specified number of units or pages. | tree.yview_scroll(3, 'units') |
xview_scroll(number, what) |
Scrolls horizontally by the specified number of units or pages. | tree.xview_scroll(-2, 'pages') |
column(column, option=None, **kw) |
Configures or queries a column's properties, such as width or anchor. | tree.column('#1', width=100) |
heading(column, option=None, **kw) |
Configures or queries the column heading's properties, such as text or anchor. | tree.heading('#1', text='Column 1') |
tag_configure(tagname, option=None, **kw) |
Configures a tag, such as its foreground or background color. | tree.tag_configure('red_tag', background='red') |
tag_bind(tagname, sequence=None, callback=None) |
Binds an event to a specific tag. | tree.tag_bind('red_tag', ' |
focus(item=None) |
Sets or gets the item currently in focus. | current_focus = tree.focus() |
see(item) |
Ensures the specified item is visible by scrolling to it if necessary. | tree.see('item_id') |
identify_row(y) |
Returns the ID of the item at the specified y-coordinate. | item_id = tree.identify_row(50) |
identify_column(x) |
Returns the column at the specified x-coordinate. | column_id = tree.identify_column(30) |
identify_region(x, y) |
Identifies the region (e.g., heading, cell) at the specified coordinates. | region = tree.identify_region(30, 50) |
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.


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
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')
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.