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', '[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()
uj5u.com熱心網友回復:
您系結到錯誤的事件,您想系結到鍵的釋放,而不是鍵本身的單擊:
self.tree.bind('<KeyRelease-Up>', self.tree_key)
self.tree.bind('<KeyRelease-Down>', self.tree_key)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/407810.html
標籤:
