Search code examples
pythonpython-3.xtkinterclipboard

How to copy file from a folder to clipboard using tkinter?


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?


Solution

  • 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