I am trying to copy the selected word from Text widget in Tkinter. Copying text using pyperclip.copy(text)
worked perfectly but when I try to paste the copied text using pyperclip.paste()
but got ᥈H֛
as output. I don't how this has happened and what causes this to happen.
System: Windows 10
Python Version: 3.7.8
Code Snippet
def get_selected_text(self):
'''Return the selected text if selection is available'''
try:
return self.text_widget.get('sel.first', 'sel.last').strip().strip('\n')
except TclError:
if 'found' in self.text_widget.tag_names():
return self.text_widget.get('found.first', 'found.last').strip().strip('\n')
def copy(self, event=None):
'''Copy functionality when user clicks cut option or presses Ctrl+C'''
text = self.get_selected_text()
pyperclip.copy(text)
def paste(self, event=None):
'''Cut functionality when user clicks cut option or presses Ctrl+X'''
cursor_pos = self.text_widget.index('insert')
print(pyperclip.paste()) # Getting weird value '䯀͏H' but when called inside copy function then I get the exact value but not in this function
self.text_widget.insert(cursor_pos, pyperclip.paste())
self.text_widget.see(cursor_pos)
return 'break'
What am I doing wrong?
This is not the problem of the pyperclip. The real problem lies in my code itself. So, the problem was that I have bind
ctrl+c
to copy andctrl+X
to cut text. According to this ifreturn break
not found in the function then the default binding by the widget and the custom binding gets executed which means when I press'Ctrl+X
thenpaste
function is executed before the default binding and when default binding by the text widget itself then the weird text gets printedcould not figure why this happens
But adding
return break
at the end ofcopy, cut and paste
function solved my problem.