[Tkinter-discuss] Copy image to clipboard

Michael Lange klappnase at web.de
Wed Feb 28 05:29:53 EST 2024


On Thu, 22 Feb 2024 10:22:06 +0000
Vasilis Vlachoudis <Vasilis.Vlachoudis at cern.ch> wrote:

> Dear all,
>
> I am trying in X11 to copy an image to clipboard but with out success.
(...)

Hi Vasilis,

sorry for the belated reply.

This is tricky, I tried several suggestions found in the web to no avail.
Finally for once an AI engine proved useful and provided me with an
almost working solution which it seems I could fix with a little
try-and-error :-)

Here's the fixed AI code example:

##########################################

import tkinter as tk
from PIL import Image, ImageTk
import io

root = tk.Tk()
root.geometry("700x500")
root.title("Copy a Picture from Tkinter Canvas to Clipboard")
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

image = Image.open("image.jpg")
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(0, 0, anchor="nw", image=image_tk)

def copy_image_to_clipboard():
    # Retrieve the image from the canvas
    canvas_image = canvas.postscript()

    # Create an in-memory file-like object
    image_buffer = io.BytesIO()

    # Save the canvas image to the buffer in PNG format
    image = Image.open(io.BytesIO(canvas_image.encode('utf-8')))
    image.save(image_buffer, format="PNG")
    image_buffer.seek(0)

    # Copy the image to the clipboard
    root.clipboard_clear()
    root.clipboard_append(image_buffer.getvalue(), type="image/png")

copy_button = tk.Button(root, text="Copy Image",
command=copy_image_to_clipboard) copy_button.pack()

root.mainloop()

##########################################

The trick is apparently to change format="image/png" (suggested by our
artificial friend) to type="image/png" in clipboard_append(). With
format="image/png" when trying to paste the clipboard into lowriter I got
only a mess of characters.

Have a nice day,

Michael





More information about the Tkinter-discuss mailing list