kyrenia
kyrenia

Reputation: 5575

Copying string value to clipboard

I am trying to copy a string to clipboard in Python, as per the question How do I copy a string to the clipboard on Windows using Python?

My current code is:

  from Tkinter import Tk
  r = Tk()
  r.withdraw()
  r.clipboard_clear()
  variable_desired = "text to copy"
  r.clipboard_append(variable_desired)

However, when i paste into notepad, i get the name of the variable (e.g. "variable_desired") copied, rather than the value of that variable. Moreover, it doesn't paste into e.g. the chrome browser.

Upvotes: 0

Views: 746

Answers (1)

Hani
Hani

Reputation: 1424

the issue here is that tinker does not keep the value in clipboard after the application close

So to make your application work add this line at the end

r.mainloop()

this will prevent you application from ending and since it didnt end the values will keep being in clipboard and you can past them

So the code should look like this

  from Tkinter import Tk
  r = Tk()
  r.withdraw()
  r.clipboard_clear()
  variable_desired = "text to copy"
  r.clipboard_append(variable_desired)
  r.mainloop()

Note : the reason it was printing variable_desired is that you seemed to have copies that name to cliboard while writing the program and after the program close that is the last thing that is in the clipboard before starting the python app

Upvotes: 1

Related Questions