tkinter app添加右键单击上下文菜单?

时间:2012-08-17 23:04:17

标签: python user-interface tkinter contextmenu

我有一个python-tkinter gui应用程序,我一直试图找到一些方法来添加一些功能。我希望有一种方法可以右键单击应用程序列表框区域中的项目并显示上下文菜单。 tkinter能够做到这一点吗?我会更好地研究gtk或其他一些gui-toolkit吗?

3 个答案:

答案 0 :(得分:33)

您将创建一个Menu实例并编写一个调用
的函数 其post()tk_popup()方法。

tkinter documentation目前没有关于tk_popup()的任何信息 请阅读Tk documentation以获取说明或来源:

library/menu.tcl in the Tcl/Tk source

::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 in the Python source

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 in the Tcl/Tk source

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()

an example on effbot中观察到grab_release()的使用 它的影响可能在所有系统上都不一样。

答案 1 :(得分:1)

我对上面的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()

答案 2 :(得分:0)

from tkinter import *
root=Tk()
root.geometry("500x400+200+100")

class Menu_Entry(Entry):
    def __init__(self,perant,*args,**kwargs):
        Entry.__init__(self,perant,*args,**kwargs)
        self.popup_menu=Menu(self,tearoff=0,background='#1c1b1a',fg='white',
                                     activebackground='#534c5c',
                             activeforeground='Yellow')
        self.popup_menu.add_command(label="Cut                     ",command=self.Cut,
                                    accelerator='Ctrl+V')
        self.popup_menu.add_command(label="Copy                    ",command=self.Copy,compound=LEFT,
                                    accelerator='Ctrl+C')
    
        self.popup_menu.add_command(label="Paste                   ",command=self.Paste,accelerator='Ctrl+V')
        self.popup_menu.add_separator()
        self.popup_menu.add_command(label="Select all",command=self.select_all,accelerator="Ctrl+A")
        self.popup_menu.add_command(label="Delete",command=self.delete_only,accelerator=" Delete")
        self.popup_menu.add_command(label="Delete all",command=self.delete_selected,accelerator="Ctrl+D")
        self.bind('<Button-3>',self.popup)
        self.bind("<Control-d>",self.delete_selected_with_e1)
        self.bind('<App>',self.popup)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Cut")
        self.context_menu.add_command(label="Copy")
        self.context_menu.add_command(label="Paste")
         
    def popup(self, event):
      try:
        self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
      finally:
        self.popup_menu.grab_release()

    def Copy(self):
      self.event_generate('<<Copy>>')

    def Paste(self):
      self.event_generate('<<Paste>>')

    def Cut(self):
      self.event_generate('<<Cut>>')

    def delete_selected_with_e1(self,event):
      self.select_range(0, END)
      self.focus()
      self.event_generate("<Delete>")

    def delete_selected(self):
      self.select_range(0, END)
      self.focus()
      self.event_generate("<Delete>")

    def delete_only(self):
      self.event_generate("<BackSpace>")

    def select_all(self):
      self.select_range(0, END)
      self.focus()



ent=Menu_Entry(root)
ent.pack()


root.mainloop()