我试图在选择事件时返回tkinter树视图选择的父级,因此如果选择更改为" child"我希望打印" parent",下面的工作示例,目前它打印的是选择,而不是选择的父级:
try:
import tkinter as tk
import tkinter.ttk as ttk
except ImportError:
import Tkinter as tk
import ttk
class App:
def __init__(self):
self.root = tk.Tk()
self.tree = ttk.Treeview(selectmode='browse')
self.tree.pack(side="top", fill="both")
self.tree.bind('<<TreeviewSelect>>', self.tree_select_event)
self.parent_iid = self.tree.insert("", "end", text="Parent")
self.child_iid = self.tree.insert(self.parent_iid, "end", text="Child")
self.root.mainloop()
def tree_select_event(self, event):
print (self.tree.item(self.tree.selection()[0])['text'])
if __name__ == "__main__":
app = App()
目前在选择Child时打印:
"Child"
选择孩子时所需的输出:
"Parent"
答案 0 :(得分:6)
试试这个:
def tree_select_event(self, event):
item_iid = self.tree.selection()[0]
parent_iid = self.tree.parent(item_iid)
if parent_iid:
print(self.tree.item(parent_iid)['text'])
else:
print(self.tree.item(item_iid)['text'])
..并且记录良好here。