In a custom entry, I have a context menu, with the function copy the selected text, which is performed by pyperclip.
When executing the 'copy_to_clipboard' function from the context menu, everything works fine... The selected text is copied to clipboard. When I close the program the text remains on the clipboard and I can paste it into any other application.
But when I run the same 'copy_to_clipboard' function using the keyboard shortcut 'Control C', the text is copied to the clipboard normally, but when I close the tkinter application the clipboard is erased.
How to solve this?
example:
from tkinter import *
import pyperclip
class Menu_Entry(Entry):
def __init__(self,perant,*args,**kwargs):
Entry.__init__(self,perant,*args,**kwargs)
self.popup_menu=Menu(self,tearoff=0)
self.popup_menu.add_command(label="nnnnnnnnnnnnnnnnnn")
self.popup_menu.add_command(label="nnnnnnnnnnnnnnnnnn")
self.popup_menu.add_separator()
self.popup_menu.add_command(label="Copy",command=self.copy_to_clipboard, accelerator='Ctrl C')
self.bind('<Button-3>',self.popup)
self.bind('<Menu>',self.popup)
self.bind("<Control-a>",self.select_all)
self.bind("<Control-A>",self.select_all)
self.bind("<Control-c>",self.copy_to_clipboard)
self.bind("<Control-C>",self.copy_to_clipboard)
def popup(self, event):
if self.select_present():
self.popup_menu.entryconfig("Copy", state=NORMAL)
else:
self.popup_menu.entryconfig("Copy", state=DISABLED)
self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
def select_all(self, event=None):
self.select_range(0, END)
self.icursor(END)
return 'break'
def copy_to_clipboard(self, event=None):
if self.select_present():
self.clipboard_clear()
self.update()
pyperclip.copy(self.selection_get())
self.update()
print('string: ', self.selection_get())
root = Tk()
root.title('test')
root.geometry('400x400')
root.ent_user = Menu_Entry(root)
root.ent_user.insert(-1, 'Select me ')
root.ent_user.pack()
root.mainloop()
CodePudding user response:
Here I use Linux Mint 20.2 x64 Cinnamon x11, The code wasn't working, I managed to fix the copy function to work here for me, adding this line at the end of the function:
return 'break'
fixed:
def copy_to_clipboard(self, event=None):
self.clipboard_clear()
self.update()
pyperclip.copy(self.selection_get())
self.update()
return 'break'