[英]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
即使我ctrl + C文件并打印
self.parent.clipboard_get()
,我得到loc
How can I achieve this?我怎样才能做到这一点?
I don't think tkinter has method to copy files, but if you are on windows you can use the powershell command Set-Clipboard
.我不认为 tkinter 有复制文件的方法,但如果你在 windows 上,你可以使用 powershell 命令
Set-Clipboard
。 You can use subprocess
module to run this command.您可以使用
subprocess
模块来运行此命令。 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.现在您可能想从另一个线程运行
copy_file
。 Here is a reference to my old answer这是对我的旧答案的参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.