I'm working on Windows XP, with Python 2.6.x and TKinter. Using a text widget in the app, but the standard popup menu (cut, copy, paste, delete, select all) is missing. How to make it appear?
Tkinter Text widget is an Input widget that supports multiline user input. It is also known as Text Editor which allows users to write the content and data in it. The content of the text widget can be cleared by defining the delete(0, END) command.
A popup Menu can be created by initializing tk_popup(x_root,y_root, False) which ensures that the menu is visible on the screen. Now, we will add an event which can be triggered through the Mouse Button (Right Click). The grab_release() method sets the mouse button release to unset the popup menu.
The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.
In the case of textvariable , which is mostly used with Entry and Label widgets, it is a variable that will be displayed as text. When the variable changes, the text of the widget changes as well.
I found a way, thanks to this post. I made some modifications. At the bottom part there's a minimal main
to try it.
from Tkinter import *
def rClicker(e):
''' right click context menu for all Tk Entry and Text widgets
'''
try:
def rClick_Copy(e, apnd=0):
e.widget.event_generate('<Control-c>')
def rClick_Cut(e):
e.widget.event_generate('<Control-x>')
def rClick_Paste(e):
e.widget.event_generate('<Control-v>')
e.widget.focus()
nclst=[
(' Cut', lambda e=e: rClick_Cut(e)),
(' Copy', lambda e=e: rClick_Copy(e)),
(' Paste', lambda e=e: rClick_Paste(e)),
]
rmenu = Menu(None, tearoff=0, takefocus=0)
for (txt, cmd) in nclst:
rmenu.add_command(label=txt, command=cmd)
rmenu.tk_popup(e.x_root+40, e.y_root+10,entry="0")
except TclError:
print ' - rClick menu, something wrong'
pass
return "break"
def rClickbinder(r):
try:
for b in [ 'Text', 'Entry', 'Listbox', 'Label']: #
r.bind_class(b, sequence='<Button-3>',
func=rClicker, add='')
except TclError:
print ' - rClickbinder, something wrong'
pass
if __name__ == '__main__':
master = Tk()
ent = Entry(master, width=50)
ent.pack(anchor="w")
#bind context menu to a specific element
ent.bind('<Button-3>',rClicker, add='')
#or bind it to any Text/Entry/Listbox/Label element
#rClickbinder(master)
master.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With