Tkinter将图像从剪贴板粘贴到文本框中

时间:2018-06-27 14:15:14

标签: python image tkinter clipboard

我试图粘贴从剪贴板中获取的图像并将其粘贴到tkinter中的文本框/标签中。我的代码在下面。

# 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')

目标区域上没有任何显示,也没有显示任何错误。但是,从那里我关闭了应用程序。消息框出现。好像是奇怪的编码。有人可以帮忙吗。

1 个答案:

答案 0 :(得分:0)

这是在标签上添加图像的简单示例。

请记住,您需要确保已保存对图像的引用,否则您将无法在应用程序中看到图像。

更新:

我相信这个最新的答案应该对您有用。该代码将尝试使用ImageGrab中的PIL方法从剪贴板中获取图像(如果有的话),然后将图像保存到临时文件夹中。然后,我们将该图像加载到标签上,然后从temp文件夹中删除该图像。

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()

我确实尝试了几种方法直接从剪贴板加载图像,但是我一直遇到错误。因此,我上面的解决方案可能不是100%的最快解决方案,但应该可以很好地工作。