本文介绍了Python tkinter treeview获取/返回所选项目的父名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在选择事件时返回 tkinter 树视图选择的父级,因此如果选择更改为子级",我希望它打印父级",下面的工作示例,目前它打印选择,而不是选择的父级:
I am trying to return the parent of a tkinter treeview selection upon a selection event, so if the selection changes to "child" I would like it to print "parent", working example below, currently it prints the selection, not the parent of the selection:
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()
当前在选择孩子时打印:
Currently prints upon selection of Child:
"Child"
选择孩子时的期望输出:
Desired output upon selection of child:
"Parent"
推荐答案
试试这个:
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'])
..它有据可查这里.
这篇关于Python tkinter treeview获取/返回所选项目的父名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!