python ttk treeview: how to select and set focus on a row?

倖福魔咒の 提交于 2019-12-05 08:49:11
Cat

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)

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".

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

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)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!