4

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"
4
  • 1
    Have you read any documentation? The method for obtaining the parent of an item is documented. Commented Apr 28, 2017 at 13:16
  • @BryanOakley Yes but it requires the iid of the selected item .parent(iid) and I am trying to cover both mouse click selection and arrow key selection of items in treeview and I can't see how I get the iid of an item from an arrow key release event from the documentation. So I am using .bind('<<TreeviewSelect>>') to cover both and I can only return the text of a selected item using this event so it's difficult, having multiple IDs (with the same name but different iid) with different parents to get the parent of an ID Commented Apr 28, 2017 at 13:19
  • 2
    I don't understand your response. You have code that can return an id. There is a method that takes an id and returns a parent. I'm not sure what the problem is. Commented Apr 28, 2017 at 13:23
  • @BryanOakley Yes I am realizing that .selection() returns an iid also, I read elsewhere it just returns text values from the treeview, sorry Commented Apr 28, 2017 at 13:24

1 Answer 1

14

Try this:

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

..and it's well documented here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.