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

时间:2018-06-03 02:24:40

标签: python-3.x tkinter pillow yolo

我正在使用Yolo3-4-PY来实现它与tkinter。

我到处查了一下,但无法解决问题。

当我运行该程序时,显示画布但是当我点击开始视频( btton )时,我收到以下错误:

从weight / yolov3.weights加载权重...完成! /usr/local/lib/python3.5/dist-packages/PIL/ImageTk.py:119:FutureWarning:元素比较失败;返回标量,但将来会执行元素比较   如果模式不在[" 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'

3 个答案:

答案 0 :(得分:1)

问题

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

这是PIL.ImageTk的源代码,提及PhotoImage的 init ()。

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图像,并将其传递给方法。

参考

我从this source中提取了将numpy数组转换为PIL Image的代码。

答案 1 :(得分:1)

就我而言,只需添加此行即可纠正

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

答案 2 :(得分:0)

将image变量放置在标签中时,必须将image变量初始化为“ image”。

例如:(正确的方法)

overview=simplified

例如:(错误的方法)

photo = PhotoImage(file = "C://Users//Carl//Downloads//download.png")
label1 = Label(image = photo)
label1.pack()