Search code examples
pythontkintertreeviewttk

how to using keyboard to select data in treeview without mouse


Firstly, When my cursor is in the entry box (entrybox.focus()), I would like to using F4 key on keyboard (GUI.bind('<F4>', directselection)) to select the first data in my treeview directly instead of using mouse.

I don't have any idea to create the function. I'm trying to use

def directselection(event = None):
    treeviewtable.focus()

but it doesn't work.


Solution

  • Use .get_children() to get a list of row IDs and then use .selection_set() to select the first row:

    def directselection(event=None):
        # get all row IDs
        idlist = treeviewtable.get_children()
        if idlist:
            # select and focus on first row
            treeviewtable.selection_set(idlist[0])
            treeviewtable.focus(idlist[0])
            # transfer keyboard focus to treeviewtable
            treeviewtable.focus_force()