简体   繁体   中英

Tkinter paste image in textbox from clipboard

I am trying to paste get an image from clipboard and paste it into the textbox/label in tkinter. My code is below.

# page4 buttons and functions

f7 = Frame(page4)
f7.grid(row=0, column=0, sticky='NESW')

f8 = Frame(page4)
f8.grid(row=0, column=0, columnspan=2, sticky='NESW')

tb8 = Label(f7, width=82)
tb8.grid(row=0, column=0, sticky='NESW')

tb9 = Text(f7, width=30)
tb9.grid(row=0, column=1, sticky='NESW')


 def imgps():
   try:
    image = root.selection_get(selection='CLIPBOARD')
    img = ImageTk.PhotoImage(Image.open(image))
    tb8.config(page4, image=img)
    tb8.clipboard_clear()
  except:
    messagebox.showinfo(message="Clipboard is Empty.")

 pbtn11 = Button(f8, text="IMAGE", activebackground="lavender",
            activeforeground="RoyalBlue", bd="5", bg="aquamarine2",
            command=imgps, fg="purple", font=('arial', 10, 'bold'))
 pbtn11.grid(row=0, column=0, sticky='NESW')

Nothing appears on the area intended and neither any error is shown up. But, whence I close the application. the Messagebox turns up. Seems like weird coding. Can somebody help.

Here is a simple example of adding an image to the label.

Keep in mind you will need to make sure that a reference to the image is saved or else you will not see an image in your app.

Update:

I believe this updated answer should work for you. The code will try to grab the image from clipboard using the ImageGrab method in PIL if there is one and then it saves the image to a temp folder. We then load that image to the label and then delete the image from the temp folder.

import tkinter as tk
import os
from tkinter import messagebox
from PIL import ImageTk, ImageGrab

root = tk.Tk()
tb8 = tk.Label(root, width=82)
tb8.grid(row=0, column=0, sticky='nsew')

def imgps():
    try:
        temp_path = "./TempImage/some_image.gif" # Whatever temp path you want here
        im = ImageGrab.grabclipboard() # Get image from clipboard
        im.save(temp_path) # save image to temp folder
        load_for_label = ImageTk.PhotoImage(file=temp_path) # load image from temp folder
        tb8.config(image=load_for_label) # set image to label
        tb8.image = load_for_label # save reference to image in memory
        tb8.clipboard_clear() # clear clipboard
        os.remove(temp_path) # delete temp file
    except:
        messagebox.showinfo(message="Clipboard is Empty.")

pbtn11 = tk.Button(root, text="IMAGE", command=imgps)
pbtn11.grid(row=1, column=0, sticky='nsew')

root.mainloop()

I did try several ways to load the image directly from the clipboard but I kept running into errors. So my above solutions might not be 100% the fastest way to implement this but should work well enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM