python - 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 格式的兼容性问题还是有其他原因?感谢您的帮助!
解决方案
推荐阅读
- android - 过滤时显示的 RecyclerView 项目类型不正确
- python - 如何测试应该在列表中与不同类的其他对象混合的对象的字段值?
- python - 如何将 csv 文件读取到 numpy ndarrays
- python - 使用 Python 和 Flask 在网络上更新图像
- r - 关闭 saveGIF 显示 RStudio
- sql-server - 将 XML 导入 SQL Server DB - 得到空白结果
- linux - 如何通过用户权限在 Linux debian 中隐藏 Python 代码?
- javascript - 将一些初始数据传递到新窗口的正确方法是什么?
- python - 通过 for 循环用用户输入填充列表
- r - 为什么训练数据上的线性回归拟合值和预测值存在差异?