Advertisement
here2share

# tk_right_click_menu.py

Nov 27th, 2023
852
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # tk_right_click_menu.py
  2.  
  3. from tkinter import *
  4.  
  5. def make_right_menu(root):
  6.     global rightmenu
  7.     rightmenu = Menu(root,tearoff=0)
  8.     rightmenu.add_command(label='Cut',accelerator='Ctrl+X')
  9.     rightmenu.add_command(label='Copy',accelerator='Ctrl+C')
  10.     rightmenu.add_command(label='Paste',accelerator='Ctrl+V')
  11.     rightmenu.add_separator()
  12.     rightmenu.add_command(label='Select All',accelerator='Ctrl+A')
  13.  
  14. def select_all(event=None):
  15.     t1.tag_add(SEL,'1.0',END)
  16.     t1.mark_set(INSERT,'1.0')
  17.     t1.see(INSERT)
  18.     return 'break'
  19. def show_rightmenu(event):
  20.     widget = event.widget
  21.     rightmenu.entryconfigure('Cut',command=lambda:widget.event_generate('<<Cut>>'))
  22.     rightmenu.entryconfigure('Copy',command=lambda:widget.event_generate('<<Copy>>'))
  23.     rightmenu.entryconfigure('Paste',command=lambda:widget.event_generate('<<Paste>>'))
  24.     if type(widget) == Entry:
  25.          rightmenu.entryconfigure('Select All',command=lambda:widget.select_range(0,END))
  26.     elif type(widget) == Text:
  27.         rightmenu.entryconfigure('Select All',command=select_all)
  28.     rightmenu.tk.call('tk_popup',rightmenu,event.x_root,event.y_root)
  29.  
  30.    
  31. root = Tk()
  32. make_right_menu(root)
  33. root.bind_class('Text',"<Button-3><ButtonRelease-3>",show_rightmenu)
  34. root.bind_class('Entry',"<Button-3><ButtonRelease-3>",show_rightmenu)
  35.  
  36. t1 = Text(root)
  37. t1.pack()
  38. e1 = Entry(root)
  39. e1.pack()
  40. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement