1

I want to have a copy function in my program, but after it is copied, and the window is closed, my clipboard is wiped of all copied or cut text from my program.

Go Sonic
  • 11
  • 3
  • Have a look at this answer - it seems like you will find a solution there: https://stackoverflow.com/questions/46178950/tk-only-copies-to-clipboard-if-paste-is-used-before-program-exits – ScottC Oct 04 '22 at 08:44

2 Answers2

0

How do I copy a string to the clipboard?

I think there you can find the answer

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('text')
r.update() # now it stays on the clipboard after the window is closed

m0shpe
  • 21
  • 2
  • I'm not having any luck. I'm trying to copy from an Entry widget and used a function that used entry.event_generate("<>"). Now I am trying to use this in its function instead, but it just closes my window without adding anything to the clipboard. – Go Sonic Oct 04 '22 at 09:08
0

As of March 2023, on Kubuntu 20.04, I was not able to make it work with either Tkinter (as in a previous answer), or pyperclip, or pandas.

What finally did work for me was xerox:

import xerox

#produce the string you want to copy to the clipboard
my_string = "here_is_a_nontrivial_string"

#set the clipboard contents to the string
xerox.copy(my_string)

After execution, the string "here_is_a_nontrivial_string" remained in the clipboard, and I was able to paste it into e.g. a text file, using ctrl+v.

Note that I had the same results regardless of whether I saved the code in a .py file and ran it using the command python3, or whether I saved it as a bash script (adding the line #!/usr/bin/python3 at the top), making it executable, and invoking it as a command from the terminal.