AttributeError: 'PhotoImage' 对象没有属性 '_PhotoImage__photo'

新手上路,请多包涵

我正在研究 Yolo3-4-PY 以使用 tkinter 实现它。

我到处查找但无法解决问题。

当我运行该程序时,会显示画布,但是当我单击“开始视频”( btton ) 时,出现以下错误:

从 weights/yolov3.weights 加载权重…完成! /usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py:119: FutureWarning: elementwise 比较失败;返回标量,但如果模式不在 [“1”、”L”、”RGB”、”RGBA”] 中,将来将执行逐元素比较:

 Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
return self.func(*args)
File "webcam_demo.py", line 13, in start_video
show_frame()
File "webcam_demo.py", line 39, in show_frame
imgtk = ImageTk.PhotoImage(image=cv2image)
File "/usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py", line 120, in
__init__
mode = Image.getmodebase(mode)
File "/usr/local/lib/python3.5/dist-packages/PIL/Image.py", line 313, in
getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/local/lib/python3.5/dist-packages/PIL/ImageMode.py", line 55, in
getmode
return _modes[mode]
TypeError: unhashable type: 'numpy.ndarray'
Exception ignored in: <bound method PhotoImage.__del__ of
<PIL.ImageTk.PhotoImage object at 0x7f4b73f455c0>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py", line 130, in
__del__    name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

原文由 Sushant Tyagi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

问题

imgtk = ImageTk.PhotoImage(image=cv2image) 行中,您将传递一个 numpy 数组 (cv2image) 作为 ImageTk.PhotoImage 的输入。但是 PIL.ImageTk 的源代码提到它需要 PIL 图像。

这就是 PIL.ImageTk 的源代码中提到的 PhotoImageinit ()。

 class PhotoImage(object):
    .....
    :param image: Either a PIL image, or a mode string.  If a mode string is
              used, a size must also be given.

解决方案

所以基本上,您必须将 numpy 数组转换为 PIL 图像,然后将其传递给 ImageTk.PhotoImage()。

那么,您可以将 imgtk = ImageTk.PhotoImage(image=cv2image) 替换为 imgtk = ImageTk.PhotoImage(image=PIL.Image.fromarray(cv2image)) 吗?

这会将 numpy 数组转换为 PIL 图像,并将其传递到方法中。

参考

我从此源中提取了用于将 numpy 数组转换为 PIL Image 的 代码

原文由 Madhawa Vidanapathirana 发布,翻译遵循 CC BY-SA 4.0 许可协议

就我而言,只需添加这一行即可更正

root = tkinter.Tk()

完整代码:

 root = tkinter.Tk()
image = PIL.Image.open(r"C:\Users\Hamid\Desktop\asdasd\2.jpeg")
img = ImageTk.PhotoImage(image)
l = Label(image=img)
l.pack()

原文由 hamidjahandideh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题