简体   繁体   English

ttk.Treeview - 如何在不先单击的情况下更改选择

[英]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.我认为在 ttk.Treeview 中设置要默认选择的行将不必先单击以开始使用键盘上的箭头按钮来更改选择。 This didn't work so I tried setting focus on the Treeview but nothing worked after much trial and error.这不起作用,所以我尝试将焦点设置在 Treeview 上,但经过多次反复试验后没有任何效果。 I looked in the source code for ttk to see if the Treeview widget has a binding to the mouse but no such thing.我查看了 ttk 的源代码,看看 Treeview 小部件是否绑定到鼠标,但没有这样的东西。 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.我已经习惯了 Windows 文件资源管理器,它可以在打开后立即使用选项卡或箭头按钮进行无鼠标导航。

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.我尝试了几个 Treeview 小部件的在线示例,它们都必须先单击一行,然后箭头键才能更改选择。 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()

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.我尝试了几个 Treeview 小部件的在线示例,它们都必须先单击一行,然后箭头键才能更改选择。 How can this be overriden?这怎么能被覆盖?

Sadly, the ttk widgets are a bit quirky.遗憾的是,ttk 小部件有点古怪。 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() :在调用focus_set()后添加以下内容:

tree.focus('gallery1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM