Treeview - how to get the index of the selected row after pressing the up/down arrow
I'm trying this way but it returns the row index before hitting the keys. I need the index of the current row not the previous row.
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', '[email protected]'))
self.tree.insert('', END, values=('1', 'nono1', '[email protected]'))
self.tree.insert('', END, values=('2', 'nono2', '[email protected]'))
self.tree.insert('', END, values=('3', 'nono3', '[email protected]'))
self.tree.insert('', END, values=('4', 'nono4', '[email protected]'))
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()
You are binding to wrong event, you want to bind to the release of the keys, not to the click of the keys itself:
self.tree.bind('<KeyRelease-Up>', self.tree_key)
self.tree.bind('<KeyRelease-Down>', self.tree_key)