问题
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.
回答1:
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)
回答2:
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"
.
回答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
回答4:
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)
回答5:
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.
来源:https://stackoverflow.com/questions/7862362/python-ttk-treeview-how-to-select-and-set-focus-on-a-row