我想用PIL加载图像,然后将其转换为数组(用于进一步的操作),然后将其转换回图像并在Tkinter Label元素中显示它。我有以下代码:
from tkinter import *
import PIL as pl
from PIL import ImageTk, Image
import numpy as np
root = Tk()
root_panel = Frame(root)
root_panel.pack(side="bottom", fill="both", expand="yes")
img_src = 'pic.jpg'
img = pl.Image.open(img_src)
img_arr = np.array(img)
img = pl.Image.fromarray(img_arr)
img_panel = Label(root_panel)
img_panel.configure(image=img)
img_panel.pack(side="bottom", fill="both", expand="yes")
root.mainloop()
当我跑步时出错了:
File "C:/Users/lazar/Documents/GitHub/Face-Features-Detection/ui.py", line 19, in <module>
img_panel.configure(image=img)
File "C:\Users\a\Miniconda3\lib\tkinter\__init__.py", line 1479, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\a\Miniconda3\lib\tkinter\__init__.py", line 1470, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "<PIL.Image.Image image mode=RGB size=295x400 at 0x28CAB9F5630>" doesn't exist
它似乎找到它(<PIL.Image.Image image mode=RGB size=295x400 at 0x28CAB9F5630>
),但由于某种原因打印出来它并不存在。任何人都可以建议可能导致此问题的原因吗?
答案 0 :(得分:1)
我解决了这个问题:
img_tk = ImageTk.PhotoImage(img)
img_panel = Label(root_panel)
img_panel.configure(image=img_tk)