ttk.Treeview – Select all rows

It is possible to programmatically select all rows and sub-rows in a treeview.

img

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def select_all():
    # Iterate over all the root-level items in the treeview.
    # Then select the children and sub-children of each item.
    for item in treeview_food.getchildren():
        select_children(item)

def select_children(item):
    # Make sure the item is expanded so the user can see it.
    treeview_food.item(item, open=True)

    # Select the current item.
    treeview_food.selection_add(item)

    # Select all the children of the current item, if any.
    item_children = treeview_food.get_children(item)
    if item_children:
        for sub_item in item_children:
            select_children(sub_item)

In the example above, running the select_all() method will select all the items in the treeview widget.

treeview_food.item(item, open=True) causes an item to expand (open=True) so if it’s collapsed, it will reveal itself to the user.

If we don’t expand before selecting all the row items, the sub-items will still get selected, but they won’t appear as being selected, like in the example below:

img