9

I have a ttk.Treeview widget with some rows of data. How do I set the focus to and select (highlight) a specified item?

tree.focus_set()

does nothing

tree.selection_set(0)

complains that: Item 0 not found, although the widget is plainly populated with more than zero items. Trying item 1 does no better.

EDIT: to select an item, find its id, then use tree.selection_set(id). Neither tree.focus(id) nor tree.focus_set(id) appears to do anything.

foosion
  • 7,619
  • 25
  • 65
  • 102

5 Answers5

14

Get the id of treeview item you want to highlight/select

child_id = tree.get_children()[-1] # for instance the last element in tuple

To highlight the item, use both focus() and selection_set(item_id)

tree.focus(child_id)
tree.selection_set(child_id)
itsmysterybox
  • 2,748
  • 3
  • 21
  • 26
Cat
  • 324
  • 2
  • 8
  • 1
    tree.selection_set(iid) works for me, focus does not. (Neither focus(iid) nor focus_set(iid)). I'm using Python 3.6.8. What I find surprising is that you can selection_set() before entering mainloop() – testalucida Aug 06 '19 at 07:19
  • On python 3.10.6 I read the selected item using selected = tree.focus() before sorting a column, after I select the item again with tree.focus(selected) and tree.selection_set(selected) and it works. – Jack Griffin Dec 29 '22 at 10:45
3

Come across this question when I'm looking to solve the exact same problem.

Found out this:

tree.selection_set(item) highlights the item

tree.focus(item) or tree.focus_set(item) selects the item

Richard Wong
  • 3,498
  • 4
  • 19
  • 19
  • `tree.selection_set(item)` and `tree.focus(item)` worked for me. I'm using Python 2.7. Thanks! – Joe Jul 27 '18 at 13:15
3

Note: I haven't worked with python.

Looking at this link, the focus method with optional parameter item, should highlight the node.

If not, look at selectmode option & set it to "browse".

shahkalpesh
  • 33,172
  • 3
  • 63
  • 88
  • 1
    focus doesn't seem to work. selection_set() wants an item id, not a position, which can be obtained when inserting or by iterating tree.get_children(). +1 for forcing me to re-read the docs. This get me highlight, but not focus. – foosion Oct 22 '11 at 21:00
2
def mycallback(event):
    _iid = treeview.identify_row(event.y)
    global  last_focus
    if _iid != last_focus:
        if last_focus:
            treeview.item(last_focus, tags=[])
        treeview.item(_iid, tags=['focus'])
        last_focus = _iid

treeview.tag_configure('focus', background='red')
global last_focus
last_focus = None
treeview.bind("<Motion>", mycallback)
1

Use tree.selection_add(item_iid)

The reason why tree.selection_set(0) doesn't work is because 0 is not the item iid, it's the index you're referring to and Treeview is expecting an iid.