Python Tkinter Treeview Shift-Up 绑定落后于输入一次迭代

Python Tkinter Treeview Shift-Up binding is one iteration behind input

我还希望能够使用 <Shift-Up> 键 select 浏览树视图中的项目。没有给出错误,但 selection 晚了一个元素。在我的代码中,我打算 selection 与焦点相同,但 selection 最终位于列表下方的元素上。

我的猜测是,在我绑定之后向上箭头键的默认绑定是 运行。

我已经搜索了一个虚拟事件来替换我的绑定中的 <Up> - 具有与 <<TreeviewSelect>> 类似的功能而不是 <ButtonPress-1> - 但没有成功。

知道如何在按下 <Shift-Up> 时同步 select 离子和焦点吗?

注意:树的 select 模式设置为 none 因为在我的主要应用程序中我需要 selection 与默认设置略有不同。

import tkinter as tk
from tkinter import ttk
class Treeview_Select:
    def __init__(self, tree):
        tree.bind('<Shift-Up>', self.ShiftUp, add='+')
    def ShiftUp(self, event):
        if event.widget.index(event.widget.focus()) is not '':
            print(event.widget.index(event.widget.focus()))
            event.widget.selection_set(event.widget.focus())
app = tk.Tk()
tree = ttk.Treeview(app)
v_scrollbar = ttk.Scrollbar(app, orient='vertical', command=tree.yview)
tree.config(selectmode='none', yscrollcommand=v_scrollbar.set)
tree.grid(row=0, column=0, sticky='nesw')
v_scrollbar.grid(row=0, column=1, sticky='nes')
Treeview_Select(tree)
for i in range(14):
    tree.insert("", 'end', text=i)
app.mainloop()

您应该使用 tree.prev(item) 进行此类操作。如果要实现 <Shift-Down>,请使用 tree.next(item).

def ShiftUp(self, event):
    if event.widget.index(event.widget.focus()) is not '':
        previous = event.widget.prev(event.widget.focus()) #use current focus to get previous one
        event.widget.selection_set(previous)
        event.widget.see(previous) #make sure the new selection is shown