tkinter上下文菜单命令无效(python 3)

时间:2018-03-12 02:37:10

标签: python python-3.x tkinter

我在Python 3.5和TKinteer中工作。在文本小部件内部,我创建了一个在用户右键单击时显示的上下文菜单。但是,当我尝试创建我想要的命令(剪切,复制,粘贴)时,命令似乎没有效果。

相关代码如下:

from tkinter import *
class Application:
    def __init__(self,master):
        self.master = master
        self.initUI()

    def initUI(self):
        root.title("Simple Text Editor")
        scrollBar = Scrollbar(root)
        self.textPad = Text(root, width=100, height=100, wrap='word',
                       yscrollcommand=scrollBar.set,
                       borderwidth=0, highlightthickness=0)
        scrollBar.config(command=self.textPad.yview)
        scrollBar.pack(side='right', fill='y')
        self.textPad.pack(side='left', fill='both', expand=True)

class PopupMenu:
    def __init__(self, master, *args, **kwargs):
        self.popup_menu = Menu(root, tearoff=0)
        self.popup_menu.add_command(label="Cut",
                                    command=lambda: app.textPad.event_generate('<Control-x>'))
        self.popup_menu.add_command(label="Copy",
                                    command=lambda: app.textPad.event_generate('<Control-c>'))
        self.popup_menu.add_command(label="Paste",
                                    command=lambda: app.textPad.event_generate('<Control-v>'))

        app.textPad.bind("<Button-3>", self.popup)
        self.popup_menu.bind("<FocusOut>",self.popupFocusOut)

    def popup(self, event):
        self.popup_menu.post(event.x_root, event.y_root)
        self.popup_menu.focus_set()

    def popupFocusOut(self, event=None):
        self.popup_menu.unpost()

root = Tk()
app = Application(root)
popupMenu = PopupMenu(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

您不想生成<Control-x>等。而是生成虚拟活动<<Cut>><<Copy>><<Paste>>