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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With