如何使用 tkinter 将剪贴板中的图像数据保存到 Debian 上的 Python 3

我正在尝试使用该tkinter解决方案获取从 GIMP 复制的剪贴板图像数据,但无法使其工作,将数据保存到文件:


from tkinter import Tk

r = Tk()

r.withdraw()

clip = r.clipboard_get(type="image/png")

r.update()

r.destroy()

with open("testbytes.png", mode="bw+") as f:

    f.write(clip.encode())

当我尝试打开 testbytes.png 文件时,图像查看器报告一个致命错误,而不是一个 PNG 文件。我用 获得了调用的type参数,它返回:clipboard_get()r.selection_get(selection='CLIPBOARD', type='TARGETS')


'TIMESTAMP TARGETS MULTIPLE SAVE_TARGETS image/png image/bmp image/x-bmp image/x-MS-bmp image/x-icon image/x-ico image/x-win-bitmap image/vnd.microsoft.icon application/ico image/ico image/icon text/ico image/tiff image/jpeg '

我认为剪贴板上的数据格式是PNG。我也尝试过 JPEG、BMP 和 TIFF,但它们会导致类似的错误。


我究竟做错了什么?


富国沪深
浏览 218回答 2
2回答

qq_笑_17

使用在单独的 SO question 中获得的转换方法,对于tkinter从剪贴板提供的 PNG 数据的 hexdump ,正确的代码是:from tkinter import Tkr = Tk()r.withdraw()clip = r.clipboard_get(type="image/png")r.update()r.destroy()# Convert hexdump to bytesclip = bytes([eval(h) for h in clip.strip().split(' ')])with open("testbytes.png", mode="bw+") as f:    f.write(clip)除了写出一个 PNG 文件,数据也可以用pillow模块(以前称为PIL)加载:import iofrom PIL import Imagecf = io.BytesIO(clip)cim = Image.open(cf)cim.show()据我所知,这是在 Linux (Debian) 上将剪贴板中的 PNG 文件读取到 Python 3 的最佳方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python