Luther
Luther

Reputation: 574

ttk.Treeview - How to change selection without clicking first

I thought setting a row to be selected by default in ttk.Treeview would make it unnecessary to click first to start using the arrow buttons on the keyboard to change the selection. This didn't work so I tried setting focus on the Treeview but nothing worked after much trial and error. I looked in the source code for ttk to see if the Treeview widget has a binding to the mouse but no such thing. This is puzzling, and I don't have enough experience to know where else to look. I'm used to Windows file explorer which is ready to navigate mouselessly as soon as it opens, with either tab or arrow buttons.

I tried several online examples of Treeview widgets and they all have to have a row clicked before the arrow keys will be able to change the selection. How can this be overriden? I suppose I'd have to simulate a button click but I couldn't find a callback for a button click in the source code. Thanks for any assistance.

(In my application there will usually be only a few rows so it doesn't make sense to click first).

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tree = ttk.Treeview(root, columns=('size', 'modified'), selectmode='browse')

tree.heading('size', text='SIZE')
tree.heading('modified', text='MODIFIED')

tree.insert('', 0, 'gallery1', text='Applications1')
tree.insert('', 1, 'gallery2', text='Applications2')

tree.selection_set('gallery1')

tree.focus_set()

tree.grid()
root.mainloop()

Upvotes: 2

Views: 3005

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

I tried several online examples of Treeview widgets and they all have to have a row clicked before the arrow keys will be able to change the selection. How can this be overriden?

Sadly, the ttk widgets are a bit quirky. You need to make sure the widget as a whole has focus, that an item is selected, and the selected item needs to have the focus. You've done the first two but not the third.

Add the following after calling focus_set():

tree.focus('gallery1')

Upvotes: 2

Related Questions