在Python TKinter文本部件中右键点击时弹出标准上下文菜单

9 投票
4 回答
10459 浏览
提问于 2025-04-16 07:32

我在使用Windows XP,Python 2.6.x和TKinter进行开发。在我的应用程序中,有一个文本框,但标准的弹出菜单(剪切、复制、粘贴、删除、全选)不见了。请问怎么才能让它显示出来呢?

4 个回答

1

感谢Gonzo的代码和bluish的'<Control-c>',我的文本小部件的右键按钮终于能用了。虽然我的声望没有达到50,但我遇到了一个问题,就是无论点击的位置如何,右键都会触发一个功能。我是这样解决这个问题的:

    def show_menu(self, e):
       if e.widget==self.text:
          self.tk.call("tk_popup", self.menu, e.x_root, e.y_root)

现在,只有在点击文本小部件时,右键的弹出菜单才会被触发。

4

我想分享一下我的解决方案,这个方案是基于StackOverflow上几个代码片段的。它包含了一个最简单的应用程序来进行测试:

补充说明:类绑定可能不太好用。如果真是这样的话,可以使用普通的绑定,并在select_all函数中返回“break”。

import Tkinter as tk

if 1:  # nice widgets
    import ttk
else:
    ttk = tk

class EntryPlus(ttk.Entry):
    def __init__(self, *args, **kwargs):
        ttk.Entry.__init__(self, *args, **kwargs)
        _rc_menu_install(self)
        # overwrite default class binding so we don't need to return "break"
        self.bind_class("Entry", "<Control-a>", self.event_select_all)  
        self.bind("<Button-3><ButtonRelease-3>", self.show_menu)

    def event_select_all(self, *args):
        self.focus_force()
        self.selection_range(0, tk.END)

    def show_menu(self, e):
        self.tk.call("tk_popup", self.menu, e.x_root, e.y_root)

class TextPlus(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)
        _rc_menu_install(self)
        # overwrite default class binding so we don't need to return "break"
        self.bind_class("Text", "<Control-a>", self.event_select_all)  
        self.bind("<Button-3><ButtonRelease-3>", self.show_menu)

    def event_select_all(self, *args):
        self.focus_force()        
        self.tag_add("sel","1.0","end")

    def show_menu(self, e):
        self.tk.call("tk_popup", self.menu, e.x_root, e.y_root)


def _rc_menu_install(w):
    w.menu = tk.Menu(w, tearoff=0)
    w.menu.add_command(label="Cut")
    w.menu.add_command(label="Copy")
    w.menu.add_command(label="Paste")
    w.menu.add_separator()
    w.menu.add_command(label="Select all")        

    w.menu.entryconfigure("Cut", command=lambda: w.focus_force() or w.event_generate("<<Cut>>"))
    w.menu.entryconfigure("Copy", command=lambda: w.focus_force() or w.event_generate("<<Copy>>"))
    w.menu.entryconfigure("Paste", command=lambda: w.focus_force() or w.event_generate("<<Paste>>"))
    w.menu.entryconfigure("Select all", command=w.event_select_all)        


if __name__ == "__main__":

    class SampleApp(tk.Tk):
        def __init__(self, *args, **kwargs):
            tk.Tk.__init__(self, *args, **kwargs)

            self.entry = EntryPlus(self)
            self.text = TextPlus(self)

            self.entry.pack()
            self.text.pack()

            self.entry.insert(0, "copy paste")
            self.text.insert(tk.INSERT, "copy paste")

    app = SampleApp()
    app.mainloop()
10

我找到了一种方法,感谢这篇帖子。我做了一些修改。在底部有一个简单的main,可以用来试一下。

from Tkinter import *

def rClicker(e):
    ''' right click context menu for all Tk Entry and Text widgets
    '''

    try:
        def rClick_Copy(e, apnd=0):
            e.widget.event_generate('<Control-c>')

        def rClick_Cut(e):
            e.widget.event_generate('<Control-x>')

        def rClick_Paste(e):
            e.widget.event_generate('<Control-v>')

        e.widget.focus()

        nclst=[
               (' Cut', lambda e=e: rClick_Cut(e)),
               (' Copy', lambda e=e: rClick_Copy(e)),
               (' Paste', lambda e=e: rClick_Paste(e)),
               ]

        rmenu = Menu(None, tearoff=0, takefocus=0)

        for (txt, cmd) in nclst:
            rmenu.add_command(label=txt, command=cmd)

        rmenu.tk_popup(e.x_root+40, e.y_root+10,entry="0")

    except TclError:
        print ' - rClick menu, something wrong'
        pass

    return "break"


def rClickbinder(r):

    try:
        for b in [ 'Text', 'Entry', 'Listbox', 'Label']: #
            r.bind_class(b, sequence='<Button-3>',
                         func=rClicker, add='')
    except TclError:
        print ' - rClickbinder, something wrong'
        pass


if __name__ == '__main__':
    master = Tk()
    ent = Entry(master, width=50)
    ent.pack(anchor="w")

    #bind context menu to a specific element
    ent.bind('<Button-3>',rClicker, add='')
    #or bind it to any Text/Entry/Listbox/Label element
    #rClickbinder(master)

    master.mainloop()

撰写回答