在Python中为Tkinter Treeview创建弹出菜单

时间:2015-12-10 14:33:56

标签: python tkinter treeview

当单击树视图中的项目时,是否可以在包含弹出菜单的子窗口中放置tkinter树视图。目前,右键单击显示菜单并指向相应的功能,但是我无法识别树视图中选择的项目。

有没有办法识别菜单使用后在树视图中选择的行?

提前致谢

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

1 个答案:

答案 0 :(得分:2)

我尝试将原始代码更新为以下内容,现在可以使用了。另请参阅此问题: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()