Filedialog python的缩略图问题

时间:2019-04-22 00:11:00

标签: python tkinter

我遇到self.photo = ImageTk.PhotoImage(self.resized_img)的问题。它告诉我AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'。我使用缩略图功能做错了吗?

 def fileDialog(self):
    self.filename = filedialog.askopenfilename(title="Select file")
    self.label = ttk.Label(self.labelFrame, text = "")
    self.label.grid(column = 1, row = 2)
    self.label.configure(text=os.path.basename(self.filename))

    self.img = Image.open(self.filename)

    self.thumbNail_img = self.img.thumbnail((512, 512))

    self.photo = ImageTk.PhotoImage(self.thumbNail_img)
    self.display = ttk.Label(image=self.photo)
    self.display.place(relx=0.10, rely=0.10)

错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
 File "gui.py", line 44, in fileDialog
self.photo = ImageTk.PhotoImage(self.resized_img)
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\ImageTk.py", line 113, in __init__
mode = Image.getmodebase(mode)
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 326, in getmodebase
return ImageMode.getmode(mode).basemode
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\ImageMode.py", line 56, in getmode
return _modes[mode]

1 个答案:

答案 0 :(得分:1)

尝试

print(type(self.img), type(self.thumbNail_img)) 

你看到

<class 'PIL.JpegImagePlugin.JpegImageFile'> <class 'NoneType'>

这意味着self.imgImage,而self.thumbNail_imgNone

thumbnail()不会创建新图像。它将更改self.img中的原始图像并返回None
"in-place"有效。 Doc:Image.thumbnail

所以您必须使用self.img来显示它

 self.img = Image.open(self.filename)

 self.img.thumbnail((512, 512))

 self.photo = ImageTk.PhotoImage(self.img)

如果您需要原始图像,则可以.copy()

 self.img = Image.open(self.filename)

 self.thumbNail_img = self.img.copy()

 self.thumbNail_img.thumbnail((512, 512))

 self.photo = ImageTk.PhotoImage(self.thumbNail_img)