Nirupam Kapoor
Nirupam Kapoor

Reputation: 77

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

I want user to select multiple nodes from different branches of Tkinter Tree. So that I can do further process I should know the parent branch of each selection.

How can I get the parent node of all selections done simultaneously?

Here is my working code:

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()

Current output:

enter image description here

Able to display parent name when selecting one node only

When done multiple selection parent of only the first one displayed, expecting parent name for each node selected.

Branch1 displayed i.e only for the first selection:

enter image description here

Upvotes: 0

Views: 693

Answers (1)

Ethan Field
Ethan Field

Reputation: 4740

selection()

Returns a tuple of selected items.

(source) (emphasis mine)


.selection() returns a tuple of all items selected in the Treeview. On the first line of the function, you are explicitly only selecting the first item:

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

Making a simple change to the function to make it loop through all elements of the tuple will resolve this:

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

Upvotes: 1

Related Questions