How to add/get image data in the OS clipboard using Python?

谁说我不能喝 提交于 2019-12-06 01:31:27

I don't think you could interact with the clipboard without external module.

Clipboard APIs are different from different Operating systems.

I suggest you to use the clipboard module.

https://pypi.python.org/pypi/clipboard/0.0.4

The xerox library is simple and capable.

Here's a Python function based on this answer that replaces/returns clipboard text using Tkinter.

def use_clipboard(paste_text=None):
    import tkinter # For Python 2, replace with "import Tkinter as tkinter".
    tk = tkinter.Tk()
    tk.withdraw()
    if type(paste_text) == str: # Set clipboard text.
        tk.clipboard_clear()
        tk.clipboard_append(paste_text)
    try:
        clipboard_text = tk.clipboard_get()
    except tkinter.TclError:
        clipboard_text = ''
    r.update() # Stops a few errors (clipboard text unchanged, command line program unresponsive, window not destroyed).
    tk.destroy()
    return clipboard_text

This method creates a quickly hidden window which is closed quickly so
that shouldn't be a problem. Also, it only supports using plain text in the
clipboard, not images which I asked for in the question above.

As stated by Martin---

Pyperclip is definitely a good option and works like a charm.

I don't know why you shouldn't be using it.

Its as simple as 3 lines below,

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
paste= pyperclip.paste()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!