首页 > 解决方案 > Pillow 处理 JPG 格式

问题描述

from tkinter import *
from glob import glob
import demoCheck
import random
import quitter
from PIL import ImageTk

gifdir = 'd:/Python/Jupyter/Programming Python/Chap 8 - GUI/pic/'


class buttonpics(Frame):
    def __init__(self, parent=None, dir='./gifs/', **kwargs):
        Frame.__init__(self, parent, **kwargs)
        self.pack()
        self.lbl = Label(self, text='None', bg='blue', fg='red')
        self.lbl.pack(fill=BOTH)
        self.btn = Button(self, text='Press me', bg='white', command=self.draw)
        self.btn.pack()
        self.quitter = quitter.Quitter(self)
        self.quitter.pack(anchor=S)
        self.files = glob(dir+'*.jpg')
        self.images = [(file, ImageTk.PhotoImage(file=file))
                       for file in self.files]

    def draw(self):
        name, photo = random.choice(self.images)
        self.btn.config(image=photo)
        self.lbl.config(text=name)


buttonpics(dir=gifdir).mainloop()

这些代码试图通过 Pillow 的 ImageTk 模块将 jpg 格式的图片加载到 Tkinter。但是,系统产生了以下错误:

> Traceback (most recent call last):   File
> "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 31, in <module>
>     buttonpics(dir=gifdir).mainloop()   File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in __init__
>     self.images = [(file, ImageTk.PhotoImage(file=file))   File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in <listcomp>
>     self.images = [(file, ImageTk.PhotoImage(file=file))   File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 89,
> in __init__
>     image = _get_image_from_kw(kw)   File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 58,
> in _get_image_from_kw
>     return Image.open(source)   File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 2930,
> in open
>     raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file 'd:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/pic\\IMG_4147.jpg' Exception ignored in: <function
> PhotoImage.__del__ at 0x00000226CF6CFD30> Traceback (most recent call
> last):   File
> "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 118,
> in __del__
>     name = self.__photo.name AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

如果扩展名改成png,程序就可以流畅运行了。这是由于与 jpg 格式的兼容性问题还是有其他原因?感谢您的帮助!

标签: pythontkinterpython-imaging-libraryjpeg

解决方案


推荐阅读