在 Tkinter 树中选择多个节点时打印每个选择的父名称

Print parent name for each selection when selected multiple nodes in Tkinter tree

我希望用户 select 来自 Tkinter 树不同分支的多个节点。为了做进一步的处理,我应该知道每个 selection 的父分支。

如何让所有 selection 的父节点同时完成?

这是我的工作代码:

import ttk
import Tkinter as tk

def select():
    item_iid = tree.selection()[0]
    parent_iid = tree.parent(item_iid)
    node = tree.item(parent_iid)['text']
    print node

root = tk.Tk()
tree = ttk.Treeview(root,show="tree")#, selectmode=EXTENDED)  
tree.config(columns=("col1"))

#SUb treeview
style = ttk.Style(root)
style.configure("Treeview")
tree.configure(style="Treeview")

tree.insert("", "0", "item1", text="Branch1",)
tree.insert("", "1", "item2", text="Branch2")

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("item2", "2", text="SOME")
tree.insert("item2", "2", text="NODES")
tree.insert("item2", "2", text="HERE")

tree.pack(fill=tk.BOTH, expand=True)
tree.bind("<Return>", lambda e: select()) 

root.mainloop()

当前输出:

当select只有一个节点时可以显示父名称

当完成多个 selection 父节点时,仅显示第一个节点,期望每个节点的父节点名称 selected.

Branch1 显示,即仅针对第一个 selection:

selection()

Returns a tuple of selected items.

(source)(强调我的)


.selection() returns 在 Treeview 中选择的所有项目的元组。在函数的第一行,您明确地只选择了第一项:

def select():
    item_iid = tree.selection()[0] #<---Right here you tell Python that you only want to use the first item from the tuple.
    parent_iid = tree.parent(item_iid)
    node = tree.item(parent_iid)['text']
    print node

对函数进行简单更改,使其循环遍历元组的所有元素即可解决此问题:

def select():
    for i in tree.selection():
        item_iid = i
        parent_iid = tree.parent(item_iid)
        node = tree.item(parent_iid)['text']
        print(node)