Tkinter:Treeview - 如何在按下 up/down 箭头后获取所选行的索引

Tkinter: Treeview - how to get the index of the selected row after pressing the up/down arrow

Treeview - 如何在按下 up/down 箭头后获取所选行的索引

我正在尝试这种方式,但它 returns 在按下键之前的行索引。我需要当前行的索引而不是前一行。

from tkinter import *
from tkinter import ttk


class MainFrame(Tk):
    def __init__(self):
        Tk.__init__(self)

        self.geometry('500x300')
        self.title('Tkinter')

        self.tree = ttk.Treeview(self, height=3, column=('col1', 'col2', 'col3'))
        self.tree.place(relx=0.02, y=25, relwidth=0.95, relheight=0.6)
        self.tree['show'] = 'headings'

        self.tree.heading('#1', text='cod')
        self.tree.heading('#2', text='name')
        self.tree.heading('#3', text='email')

        self.tree.column('#1', width=50)
        self.tree.column('#2', width=100)
        self.tree.column('#3', width=100)

        self.tree.insert('', END, values=('0', 'nono0', 'a@x.com'))
        self.tree.insert('', END, values=('1', 'nono1', 'b@x.com'))
        self.tree.insert('', END, values=('2', 'nono2', 'c@x.com'))
        self.tree.insert('', END, values=('3', 'nono3', 'd@x.com'))
        self.tree.insert('', END, values=('4', 'nono4', 'e@x.com'))

        self.tree.bind('<Up>', self.tree_key)
        self.tree.bind('<Down>', self.tree_key)


        iid = self.tree.get_children()[0]
        self.tree.selection_set(iid)
        self.tree.focus_force()
        self.tree.focus(iid)
        self.tree.see(iid)
        return


    def tree_key(self, event=None):
        selected_iid = self.tree.selection()[0]
        current_idx = self.tree.index(selected_iid)

        print('Current Row:',current_idx)
        return


if __name__== '__main__':
    app = MainFrame()
    app.mainloop()

您绑定到错误的事件,您想要绑定到按键的释放,而不是按键本身的点击:

self.tree.bind('<KeyRelease-Up>', self.tree_key)
self.tree.bind('<KeyRelease-Down>', self.tree_key)