ttk.Treeview – Get selected row items

We can get the text of selected items in a treeview widget.

.selection() method

The .selection() method returns the iid of all selected items.

1
2
3
4
# Get the selected iids
selected_item_iids = self.treeview_food.selection()

print(selected_item_iids)

img

In the animated GIF above, I002 is the Pizza item, I003 is the Juice Slice item. The .selection() method returns the selected items as a tuple.

If there are no selections in the treeview, the .selection() method will return an empty tuple. It will not raise an exception.

Get selected item row text

Once we know the iid of the selected item(s), we can get the row text that is displayed in the treeview.

First, we have to get the item’s details as a dictionary using .item()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Get the selected iids
selected_item_iids = self.treeview_food.selection()

# Loop through the selected iids one by one
for item_iid in selected_item_iids:

    # Details of the row
    item_details = self.treeview_food.item(item_iid)

    # Values contains the text
    row_text = item_details.get("values")
    print(row_text)

img

If there are no selections in the treeview, the .selection() method will return an empty tuple. It will not raise an exception.