【发布时间】:2015-12-07 07:50:44
【问题描述】:
我在尝试使用 Pillow 在 tkinter 中显示图像时遇到了一个奇怪的问题。
我最初尝试以默认的 tkinter 方式显示图像,这对 gif 效果很好:
import tkinter as tk
root = tk.Tk()
src = tk.PhotoImage(file = "C:\\Users\\Matt\\Desktop\\K8pnR.gif")
label = tk.Label(root, image = src)
label.pack()
(K8pnR 只是我在 imgur 上找到的一个随机 gif)
这很好用,但唯一的问题是我想显示其他文件类型。这将我引向 Pillow,因为我正在使用 Python 3.4。我尝试从显示相同的文件开始,但使用 Pillow:
import tkinter as tk
from PIL import Image
root = tk.Tk()
src = Image.open("C:\\Users\\Matt\\Desktop\\K8pnR.gif")
img = tk.PhotoImage(file = src)
label = tk.Label(image = img, master = root)
label.pack()
这会导致一个非常奇怪和丑陋的no such file or directory错误:
Traceback (most recent call last):
File "C:\Users\Matt\Desktop\pil test.py", line 7, in <module>
img = tk.PhotoImage(file = src)
File "C:\Python34\lib\tkinter\__init__.py", line 3416, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python34\lib\tkinter\__init__.py", line 3372, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "<PIL.GifImagePlugin.GifImageFile image mode=P size=494x260 at 0x26A6CD0>": no such file or directory
我尝试了不同的文件、不同的文件类型,甚至重新安装了 Pillow,但仍然出现错误。
有谁知道这里发生了什么?我错过了一些非常明显的东西吗?
编辑:
当我尝试 suggested 修复时,我得到了这个诡异的错误:
Traceback (most recent call last):
File "C:\Users\Matt\Desktop\pil test.py", line 6, in <module>
img = ImageTk.PhotoImage(file = src)
File "C:\Python34\lib\site-packages\PIL\ImageTk.py", line 84, in __init__
image = Image.open(kw["file"])
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2297, in open
prefix = fp.read(16)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 632, in __getattr__
raise AttributeError(name)
AttributeError: read
【问题讨论】: