Reputation: 105
Is it possible to have a tkinter treeview located in a child window that contains a popup menu when an item in the treeview is clicked. At the moment the menu is displayed on a right click and is directed to the appropriate function, however I have been unable to then identify the item selected in the treeview.
Is there a way to identify the row that has been selected in the treeview after the menu has been used?
Thanks in advance
class Page(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button = ttk.Button(self, text="Treeview", command= self.ChildWindow)
button.pack()
def ChildWindow(self):
#Create menu
popup = Menu(self, tearoff=0)
popup.add_command(label="Next", command=self.selection)
popup.add_separator()
def do_popup(event):
# display the popup menu
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
# make sure to release the grab (Tk 8.0a1 only)
popup.grab_release()
#Create Treeview
win2 = Toplevel()
new_element_header=['1st']
treeScroll = ttk.Scrollbar(win2)
treeScroll.pack(side=RIGHT, fill=Y)
self.tree = ttk.Treeview(win2,columns=new_element_header, show="headings")
self.tree.heading("1st", text="1st")
self.tree.insert("" , 0, text="Line 1", values=("1A"))
self.tree.pack(side=LEFT, fill=BOTH)
self.tree.bind("<Button-3>", do_popup)
win2.minsize(600,30)
def selection(self, event):
selection = self.tree.set(self.tree.identify_row(event.y))
print selection
Upvotes: 5
Views: 7288
Reputation: 124
I've tried to update your original code to be the following and it now works. See also this question: how to pass values to popup command on right click in python tkinter
import Tkinter as tk
import ttk
class Page(tk.Frame):
def __init__(self, parent, controller):
self.root = parent;
self.button = tk.Button(parent, text="Treeview", command=self.ChildWindow)
self.button.pack()
def ChildWindow(self):
#Create menu
self.popup = tk.Menu(self.root, tearoff=0)
self.popup.add_command(label="Next", command=self.selection)
self.popup.add_separator()
def do_popup(event):
# display the popup menu
try:
self.popup.selection = self.tree.set(self.tree.identify_row(event.y))
self.popup.post(event.x_root, event.y_root)
finally:
# make sure to release the grab (Tk 8.0a1 only)
self.popup.grab_release()
#Create Treeview
win2 = tk.Toplevel(self.root)
new_element_header=['1st']
treeScroll = ttk.Scrollbar(win2)
treeScroll.pack(side=tk.RIGHT, fill=tk.Y)
self.tree = ttk.Treeview(win2, columns=new_element_header, show="headings")
self.tree.heading("1st", text="1st")
self.tree.insert("" , 0, text="Line 1", values=("1A"))
self.tree.pack(side=tk.LEFT, fill=tk.BOTH)
self.tree.bind("<Button-3>", do_popup)
win2.minsize(600,30)
def selection(self):
print self.popup.selection
root = tk.Tk()
Page(root, None)
root.mainloop()
def main():
pass
if __name__ == '__main__':
main()
Upvotes: 7