使用tkinter和枕头显示图像

问题描述 投票:1回答:1

这是我的代码

import tkinter as tk
import cv2
import PIL.Image, PIL.ImageTk

window = tk .Tk()

img = cv2.imread('bee1.jpg')

height, width, no_channels = img.shape

canvas = tk.Canvas(window, width = width, height = height)
canvas.pack()

photo = PIL.ImageTk(0,0,image=photo,anchor=tk.NW)


window.mainloop()

我正在Pycharm 2019.3中运行,Ubuntu(最新)

我收到此错误:

ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/__init__.py)

我要加载的图像是:

enter image description here

tkinter pycharm python-imaging-library ubuntu-18.04 cv2
1个回答
0
投票

代码中有几处错误:

  • 您需要使用from PIL import Image导入PIL,否则您将收到所看到的错误,

  • 您不应该真正使用OpenCV在这里读取图像,原因有两个...首先,无论如何它都在下面使用PIL,因此您添加了不必要的依赖,其次,因为OpenCV使用BGR顺序而不是RGB,所以一切都回来了-to-front,除非您进行更改,这意味着您最好首先使用PIL读取图像。


无论如何,我的自鸣得意,这是一些有效的代码:

#!/usr/bin/env python3

import tkinter as tk
from PIL import Image, ImageTk

window = tk.Tk()

img = Image.open('bee.jpg')
width, height = img.size

canvas = tk.Canvas(window, width = width, height = height)
canvas.pack()

photo = ImageTk.PhotoImage(img)
canvas.create_image(width//2, height//2, image=photo)

window.mainloop()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.