0

I'm working in Python 3.5 and TKinteer. Inside of a text widget, I have created a context menu that appears when the user right-clicks. However, when I try and create the commands I want (cut, copy, paste), the commands seem to have no effect.

The relevant code is as follows:

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()
3
  • I suspect the problem is that at the moment one of your popup commands is being invoked, the Text definitely doesn't have focus, and therefore won't receive your (simulated) keyboard events. You could try explicitly focusing the Text before the event_generate(). Commented Mar 12, 2018 at 2:45
  • Are you running on OSX by any chance? Commented Mar 12, 2018 at 2:51
  • Bryan Oakley's answer works, but so does the suggestion from jasonharper. Commented Mar 12, 2018 at 23:39

1 Answer 1

1

You don't want to generate <Control-x>, etc. Instead, generate the virtual events <<Cut>>, <<Copy>> and <<Paste>>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.