ttk.Treeview – Get count of all items

We can get a total count of all items in a treeview widget – including sub-items.

img

Snippet

def get_count(item_iid="") -> int:
    """
    Count and return the number of items and sub-items in the treeview widget.
    """
    count = 0

    # Enumerate over the given iid's sub-items.
    # If no item iid has been provided, it will enumerate over the parent items.
    for item in treeview_test.get_children(item_iid):

        # Count the parent item that we're currently on.
        count += 1

        # Count all the sub-items of the current parent that we're on.
        count += get_count(item)

    return count

Full code

import tkinter as tk
from tkinter import ttk


root = tk.Tk()

def on_get_count_clicked():
    """
    The 'Get count' button has been clicked.
    """
    total_count = get_count()
    print(total_count)

def get_count(item_iid="") -> int:
    """
    Count and return the number of items and sub-items in the treeview widget.
    """
    count = 0

    # Enumerate over the given iid's sub-items.
    # If no item iid has been provided, it will enumerate over the parent items.
    for item in treeview_test.get_children(item_iid):

        # Count the parent item that we're currently on.
        count += 1

        # Count all the sub-items of the current parent that we're on.
        count += get_count(item)

    return count

treeview_test = ttk.Treeview(root, show="tree")
btn_move = ttk.Button(root, text="Get count", command=on_get_count_clicked)

treeview_test.pack(expand=True, fill=tk.BOTH)
btn_move.pack()

treeview_test.insert(parent="", index="end", text="Orange")

treeview_test.insert(parent="", index="end", iid="apple", text="Apple")
treeview_test.insert(parent="apple", index="end", text="Apple Juice")

treeview_test.insert(parent="", index="end", iid="banana", text="Banana")
treeview_test.insert(parent="banana", index="end", text="Banana Milk Shake")
treeview_test.insert(parent="banana", index="end", text="Banana Bread")
treeview_test.insert(parent="banana", index="end", text="Banana Cake")

root.mainloop()