0

I have the path to a file, will usually be an image or a video, and I would like to copy this file to the clipboard so I can paste it somewhere else, eg: another folder, websites etc.

Disappointingly, the following doesn't work

loc="C:/Path/To/File"
root.clipboard_clear()
root.clipboard_append(loc)

even though if I ctrl + C the file and print self.parent.clipboard_get(), I get loc

How can I achieve this?

FieryRMS
  • 91
  • 3
  • 11
  • Try adding another line that says `root.clipboard_append(loc, type="FILE_NAME")`. (You still want the existing append, to provide a plaintext version of the data in case the user pastes it into something that doesn't deal with files.) – jasonharper Feb 04 '22 at 19:02
  • @jasonharper I cant get it to work using that line, still works the same way as before, and if I remove ```root.clipboard_append(loc)```, the copy paste function stops working completely. – FieryRMS Feb 05 '22 at 04:41
  • https://stackoverflow.com/a/70994384/18440600 Can I copy only the files inside the folder? – dubleA Jun 25 '22 at 15:18

2 Answers2

1

I don't think tkinter has method to copy files, but if you are on windows you can use the powershell command Set-Clipboard. You can use subprocess module to run this command. Here is a minimal example.

import subprocess
import tkinter as tk

def copy_file():
    #cmd = r"ls '{}' | Set-Clipboard".format(absolute_path) # if you only want the contents of folder to be copied
    cmd = r"gi '{}' | Set-Clipboard".format("background.png") # copies both folder and its contents
    subprocess.run(["powershell", "-command", cmd], shell=True)  # windows specific

root = tk.Tk()

copyfile = tk.Button(root, text="Copy file from c:\\", command=copy_file)
copyfile.pack()
root.mainloop()

Now you might want to run the copy_file from another thread. Here is a reference to my old answer

Art
  • 2,836
  • 4
  • 17
  • 34
  • Works excellent for one file, thanks. What about pasting multiple files to the clipboard? I have a list of filepath strings, any way to pass it to Powershell so that when the user hits Ctrl+v all the files will be pasted? – Wojciech Dec 05 '22 at 14:31
0

As a complement to Art's answer, you can use this powershell command to copy multiple files or directories:

Get-Item -LiteralPath C:/Path/To/File1,C:/Path/To/File1,C:/Path/To/Dir1 | Set-Clipboard

So the python code will look like this:

import subprocess

def copy_file(paths):
    cmd = r"Get-Item -LiteralPath {} | Set-Clipboard".format(','.join(paths))
    subprocess.run(["powershell", "-command", cmd], shell=True)

Please note that you may need to add '' for each file/directory path.