Skip to content

Instantly share code, notes, and snippets.

@angeloped
Created June 24, 2019 12:40
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save angeloped/91fb1bb00f1d9e0cd7a55307a801995f to your computer and use it in GitHub Desktop.
Save angeloped/91fb1bb00f1d9e0cd7a55307a801995f to your computer and use it in GitHub Desktop.
A simple Tkinter Cut, Copy, and Paste contextmenu for Entry widgets.
import Tkinter
def make_textmenu(root):
global the_menu
the_menu = Tkinter.Menu(root, tearoff=0)
the_menu.add_command(label="Cut")
the_menu.add_command(label="Copy")
the_menu.add_command(label="Paste")
the_menu.add_separator()
the_menu.add_command(label="Select all")
def callback_select_all(event):
# select text after 50ms
root.after(50, lambda:event.widget.select_range(0, 'end'))
def show_textmenu(event):
e_widget = event.widget
the_menu.entryconfigure("Cut",command=lambda: e_widget.event_generate("<<Cut>>"))
the_menu.entryconfigure("Copy",command=lambda: e_widget.event_generate("<<Copy>>"))
the_menu.entryconfigure("Paste",command=lambda: e_widget.event_generate("<<Paste>>"))
the_menu.entryconfigure("Select all",command=lambda: e_widget.select_range(0, 'end'))
the_menu.tk.call("tk_popup", the_menu, event.x_root, event.y_root)
root = Tkinter.Tk()
make_textmenu(root)
e1 = Tkinter.Entry(); e1.pack()
e2 = Tkinter.Entry(); e2.pack()
# bind the feature to all Entry widget
root.bind_class("Entry", "<Button-3><ButtonRelease-3>", show_textmenu)
root.bind_class("Entry", "<Control-a>", callback_select_all)
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment