Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 40 ยท Styling with ttk

Tkinter Treeview: Tables, Trees, Sorting and Scrollbars

Use ttk.Treeview as a data table or hierarchical tree: define columns, insert, edit and delete rows, read the selection, sort by clicking headings and add scrollbars.

ttk.Treeview is the most powerful display widget in Tkinter. It plays two roles. As a table it shows rows and columns with clickable headings, like a spreadsheet grid. As a tree it shows nested items that open and close, like a file explorer. It is the right choice whenever a Listbox is too limited: several columns, icons, sorting or hierarchy.

This lesson covers building both kinds, managing rows by id, reading selections, sorting, filtering and scrolling. The Treeview code is read-only because it needs a display; the runnable blocks reproduce the data work (sorting, filtering, building a tree from paths) in plain Python.

A table with columns

Python
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("Employees")

columns = ("name", "dept", "salary")
tree = ttk.Treeview(root, columns=columns, show="headings", height=8)
tree.heading("name", text="Name")
tree.heading("dept", text="Department")
tree.heading("salary", text="Salary")
tree.column("name", width=140, anchor="w")
tree.column("dept", width=120, anchor="w")
tree.column("salary", width=90, anchor="e")

rows = [("Ana", "Sales", 52000), ("Bo", "IT", 61000), ("Cy", "IT", 58000)]
for row in rows:
    tree.insert("", "end", values=row)

tree.pack(fill="both", expand=True)
root.mainloop()

A table appears with three headed columns and three rows; salaries are right-aligned. Key points:

  • columns= names the data columns. Tkinter also has a hidden first column #0 that holds the tree part (the expand arrow and a label). show="headings" hides it, giving a plain table. Use show="tree headings" (the default) when you want a hierarchy.
  • heading(col, text=...) sets the title; column(col, width=, anchor=, stretch=, minwidth=) sets the size and alignment.
  • insert(parent, index, values=...) adds a row: parent "" means the top level, index "end" appends. It returns the row's item id (like "I001"), or you can pass your own with iid="emp-7". Unique ids make it easy to find the row for a database record.
  • height is the number of visible rows.

Reading and changing rows

Python
item = tree.insert("", "end", iid="emp-4", values=("Di", "HR", 49000))
tree.item(item, values=("Di", "HR", 51000))     # replace all values
tree.set(item, "salary", 53000)                 # change a single cell
print(tree.item(item)["values"])                # ['Di', 'HR', 53000]
tree.delete(item)                               # remove one row
tree.delete(*tree.get_children())               # clear the whole table

tree.item(id) returns a dict with text, values, tags, open and image. Careful: Treeview stores values as strings internally and returns strings or numbers depending on content ("007" becomes 7). If you need exact text, such as leading zeros, tag or store the real record elsewhere and keep the id in iid.

Selection

Python
tree.bind("<<TreeviewSelect>>", on_select)

def on_select(event):
    selected = tree.selection()          # tuple of item ids
    if not selected:
        return
    values = tree.item(selected[0], "values")
    status.set(f"{values[0]} selected")

selectmode can be "browse" (one row), "extended" (many, the default) or "none". tree.focus() returns the row with the keyboard focus, and tree.selection_set(id), tree.see(id) select and scroll to a row from code. To react to a double click, bind <Double-1> and use tree.identify_row(event.y) to find the row under the mouse.

Sorting by clicking a heading

Treeview does not sort by itself, but a heading accepts a command. Read all rows, sort in Python, and re-insert them with move:

Python
def sort_by(col, descending):
    rows = [(tree.set(k, col), k) for k in tree.get_children("")]
    try:
        rows.sort(key=lambda t: float(t[0]), reverse=descending)   # numeric column
    except ValueError:
        rows.sort(key=lambda t: t[0].lower(), reverse=descending)  # text column
    for index, (_, k) in enumerate(rows):
        tree.move(k, "", index)
    tree.heading(col, command=lambda: sort_by(col, not descending))

for col in columns:
    tree.heading(col, text=col.title(), command=lambda c=col: sort_by(c, False))

Clicking "Salary" sorts rows by number; clicking it again reverses the order; clicking "Name" sorts alphabetically. Note the c=col trick in the loop: without it every heading would sort the last column (a late-binding closure bug). The core idea, comparing numbers as numbers and text as text, is shown here without the GUI:

Python Stand-in: sorting rows like a clickable heading

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line shows the classic bug: as text, "9000" sorts after "61000". Converting to numbers fixes it.

Filtering and searching

There is no built-in filter. Keep your data in a list of records, and when the search box changes, clear the tree and insert only matching records. For big tables use detach(item) to hide an item without deleting it and reattach(item, "", index) to bring it back.

Python Stand-in: live filter on a record list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A tree: parents and children

For hierarchy, insert children with the parent's id:

Python
tree = ttk.Treeview(root)                       # show="tree headings" by default
tree.heading("#0", text="Project")
src = tree.insert("", "end", text="src", open=True)
tree.insert(src, "end", text="main.py")
tree.insert(src, "end", text="utils.py")
docs = tree.insert("", "end", text="docs")
tree.insert(docs, "end", text="README.md")

The result is a collapsible list: src (open) containing two files and docs (closed) with one file. open=True expands a node, tree.item(id, open=True) does it later, and tree.get_children(id) returns the children, tree.parent(id) the parent. To load a real folder you would walk it with os.scandir and insert recursively, usually loading children lazily when a node is opened (<<TreeviewOpen>>) so huge directories do not freeze the program.

The stand-in builds the nested structure from path strings, the step you need whenever the data is a flat list:

Python Stand-in: build a tree from flat paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the real widget, each recursion step would call tree.insert(parent_id, "end", text=name) and pass the returned id to its children.

Tags and styling

Tags give rows colors and fonts, and let one handler serve many rows:

Python
tree.tag_configure("low", background="#fde8e8")
tree.tag_configure("high", foreground="#116611", font=("Segoe UI", 10, "bold"))
tree.insert("", "end", values=("Ana", "Sales", 52000), tags=("high",))

Row height and heading look come from styles: style.configure("Treeview", rowheight=28) and style.configure("Treeview.Heading", font=("Segoe UI", 10, "bold")) (Styles and Themes). On some Windows Tk versions, tag_configure colors are ignored unless you fix a known bug in the style map; if row colors do not show, apply the standard workaround of re-mapping background and foreground in style.map("Treeview", ...).

Scrollbars

A Treeview scrolls only when you connect a scrollbar in both directions:

Python
frame = ttk.Frame(root)
frame.pack(fill="both", expand=True)
tree = ttk.Treeview(frame, columns=columns, show="headings")
vsb = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
tree.configure(yscrollcommand=vsb.set)
tree.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)

The table gets a vertical scrollbar on its right edge that moves with the rows. Put the tree and bar in their own frame so they resize together; add orient="horizontal" and xview the same way for wide tables.

Common mistakes

  • Assuming show="headings" removes the #0 column data: the column is hidden, but text= is still stored.
  • Sorting strings when the column is numeric.
  • Using tree.item(id)["values"] and expecting the original types back.
  • Writing command=lambda: sort_by(col, False) in a loop (all headings sort the last column).
  • Rebuilding the whole table on every small change instead of updating the one row with tree.item or tree.set.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does show='headings' do?

    The default shows the tree column; 'headings' shows only the data columns and their titles.
  2. 2. How do you read the currently selected row's values?

    selection() returns item ids; item(id, 'values') returns that row's values.
  3. 3. Why is command=lambda: sort_by(col, False) inside a for loop a bug?

    Bind the value with a default argument: lambda c=col: sort_by(c, False).
  4. 4. How does Treeview represent a child row?

    insert(parent_id, index, ...) places the new item under that parent.

Summary

  • ttk.Treeview is a table (show="headings") or a tree (parent ids).
  • Rows have ids; use insert, item, set, delete, move, detach.
  • Read selection with selection() and the <<TreeviewSelect>> event.
  • Sort and filter in Python, then update the widget.
  • Connect scrollbars in both directions and put widget and bar in one frame.

Next: Notebook, PanedWindow and Container Widgets