gpt4 book ai didi

Python tkinter treeview 获取/返回所选项目的父名称

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:53 25 4
gpt4 key购买 nike

我试图在选择事件时返回 tkinter treeview 选择的父级,所以如果选择更改为“子级”,我希望它打印“父级”,下面的工作示例,目前它打印选择,而不是选择的父级:

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"

选择 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'])

..它有据可查 here .

关于Python tkinter treeview 获取/返回所选项目的父名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com