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



Treeview-如何在按下上/下箭头后获得所选行的索引

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

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)

相关内容

  • 没有找到相关文章

最新更新