Tkinter的应用程序添加右键单击上下文菜单?(tkinter app adding a righ

2019-06-27 03:08发布

我有我一直在试图找到某种方式在某些功能添加一个Python-Tkinter的GUI应用程序。 我希望会有办法在应用程序的列表框区域上的项目右键单击并弹出一个快捷菜单。 是的Tkinter能做到这一点? 我会过得更好寻找到GTK或一些其他的GUI工具包?

Answer 1:

您可以创建一个菜单实例,并编写调用一个函数
post()tk_popup()方法。

该Tkinter的文档目前还没有任何关于tk_popup()
阅读Tk的文档的说明,或源:

library/menu.tcl在Tcl / Tk的源 :

::tk_popup --
This procedure pops up a menu and sets things up for traversing
the menu and its submenus.

Arguments:
menu  - Name of the menu to be popped up.
x, y  - Root coordinates at which to pop up the menu.  
entry - Index of a menu entry to center over (x,y).  
        If omitted or specified as {}, then menu's  
        upper-left corner goes at (x,y).  

tkinter/__init__.py在Python源 :

def tk_popup(self, x, y, entry=""):
    """Post the menu at position X,Y with entry ENTRY."""
    self.tk.call('tk_popup', self._w, x, y, entry)

您在功能通过右键点击相关联:
the_widget_clicked_on.bind("<Button-3>", your_function)

然而,右键单击关联的数字是不是每一个平台上都相同。

library/tk.tcl在Tcl / Tk的源 :

On Darwin/Aqua, buttons from left to right are 1,3,2.  
On Darwin/X11 with recent XQuartz as the X server, they are 1,2,3; 
other X servers may differ.

这是我写的一个例子,增加了一个上下文菜单列表框:

import tkinter # Tkinter -> tkinter in Python 3

class FancyListbox(tkinter.Listbox):

    def __init__(self, parent, *args, **kwargs):
        tkinter.Listbox.__init__(self, parent, *args, **kwargs)

        self.popup_menu = tkinter.Menu(self, tearoff=0)
        self.popup_menu.add_command(label="Delete",
                                    command=self.delete_selected)
        self.popup_menu.add_command(label="Select All",
                                    command=self.select_all)

        self.bind("<Button-3>", self.popup) # Button-2 on Aqua

    def popup(self, event):
        try:
            self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popup_menu.grab_release()

    def delete_selected(self):
        for i in self.curselection()[::-1]:
            self.delete(i)

    def select_all(self):
        self.selection_set(0, 'end')


root = tkinter.Tk()
flb = FancyListbox(root, selectmode='multiple')
for n in range(10):
    flb.insert('end', n)
flb.pack()
root.mainloop()

使用grab_release()中观察到上effbot一个例子 。
其效果可能不会在所有系统上相同。



Answer 2:

我做了一些改动conext菜单上面的代码,以调整我的需求,我认为这将是分享有用:

版本1:

import tkinter as tk
from tkinter import ttk

class Main(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        master.geometry('500x350')
        self.master = master
        self.tree = ttk.Treeview(self.master, height=15)
        self.tree.pack(fill='x')
        self.btn = tk.Button(master, text='click', command=self.clickbtn)
        self.btn.pack()
        self.aMenu = tk.Menu(master, tearoff=0)
        self.aMenu.add_command(label='Delete', command=self.delete)
        self.aMenu.add_command(label='Say Hello', command=self.hello)

        # attach popup to treeview widget
        self.tree.bind("<Button-3>", self.popup)

    def clickbtn(self):
        text = 'Hello ' + str(self.num)
        self.tree.insert('', 'end', text=text)
        self.num += 1

    def delete(self):
        print(self.tree.focus())
        if self.iid:
            self.tree.delete(self.iid)

    def hello(self):
        print ('hello!')

    def popup(self, event):
        self.iid = self.tree.identify_row(event.y)
        if self.iid:
            # mouse pointer over item
            self.tree.selection_set(self.iid)
            self.aMenu.post(event.x_root, event.y_root)            
        else:
            pass

版本2:

import tkinter as tk
from tkinter import ttk

class Main(tk.Frame):
    def __init__(self, master):
        master.geometry('500x350')
        self.master = master
        tk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self.master, height=15)
        self.tree.pack(fill='x')
        self.btn = tk.Button(master, text='click', command=self.clickbtn)
        self.btn.pack()
        self.rclick = RightClick(self.master)
        self.num = 0

        # attach popup to treeview widget
        self.tree.bind('<Button-3>', self.rclick.popup)
    def clickbtn(self):
        text = 'Hello ' + str(self.num)
        self.tree.insert('', 'end', text=text)
        self.num += 1

class RightClick:
    def __init__(self, master):

        # create a popup menu
        self.aMenu = tk.Menu(master, tearoff=0)
        self.aMenu.add_command(label='Delete', command=self.delete)
        self.aMenu.add_command(label='Say Hello', command=self.hello)

        self.tree_item = ''

    def delete(self):
        if self.tree_item:
            app.tree.delete(self.tree_item)

    def hello(self):
        print ('hello!')

    def popup(self, event):
        self.aMenu.post(event.x_root, event.y_root)
        self.tree_item = app.tree.focus()

root = tk.Tk()
app=Main(root)
root.mainloop()


文章来源: tkinter app adding a right click context menu?