Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make menubar cut/copy/paste with Python/Tkinter

Tags:

python

tkinter

I'd like to make menu items (in the menubar, not in a right click pop-up window) that can cut/copy/paste whatever text is selected.

The equivalent keyboard commands already work without my having done anything to enable them. For example, I can enter text in an entry box, cut it with Control-X, and paste it back (or elsewhere) with Control-C.

The posts on the topic I've seen boil down to cut/copy/paste for individual widgets, but that already works. How do I make the menu items activate them?

Thanks.

EDIT: Just to be clear, The issues are:

  • how to make the menu items for cut/copy act on whatever text is selected in any widget
  • how to have the paste menu item paste text wherever the text cursor is

Again, the key commands to do this (Control-x, Control-c, Control-v) already work without my having done anything. I know how to make the menus; the question is just what command I should attach to the menu items to have the desired effect.

EDIT 2: Ok, I've got a way that works. Since the key commands already work, we can just generate them. In my case, everything is a a notebook named noteBook so

lambda: self.noteBook.event_generate('<Control-x>')

cuts as desired. For example:

editmenu.add_command(label="Cut", accelerator="Ctrl+X", command=lambda: self.noteBook.event_generate('<Control-x>'))

In use: https://github.com/lnmaurer/qubit-control-interface/commit/c08c10a7fbc4a637c1e08358fb9a8593dfdf116e

Still, there's probably a cleaner way to do this; please reply if you know it.

like image 885
lnmaurer Avatar asked Dec 09 '11 17:12

lnmaurer


1 Answers

try this: source

import Tkinter

def make_menu(w):
    global the_menu
    the_menu = Tkinter.Menu(w, tearoff=0)
    the_menu.add_command(label="Cut")
    the_menu.add_command(label="Copy")
    the_menu.add_command(label="Paste")

def show_menu(e):
    w = e.widget
    the_menu.entryconfigure("Cut",
    command=lambda: w.event_generate("<<Cut>>"))
    the_menu.entryconfigure("Copy",
    command=lambda: w.event_generate("<<Copy>>"))
    the_menu.entryconfigure("Paste",
    command=lambda: w.event_generate("<<Paste>>"))
    the_menu.tk.call("tk_popup", the_menu, e.x_root, e.y_root)

t = Tkinter.Tk()
make_menu(t)

e1 = Tkinter.Entry(); e1.pack()
e2 = Tkinter.Entry(); e2.pack()
e1.bind_class("Entry", "<Button-3><ButtonRelease-3>", show_menu)

t.mainloop()
like image 98
John Riselvato Avatar answered Oct 05 '22 23:10

John Riselvato