Mat*_*tir 0 python jpeg gif python-imaging-library
当尝试使用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()
Run Code Online (Sandbox Code Playgroud)
(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()
Run Code Online (Sandbox Code Playgroud)
这会导致一个非常奇怪和丑陋的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
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的文件、不同的文件类型,甚至重新安装 Pillow,但仍然收到错误。
有谁知道这是怎么回事?我错过了一些完全明显的事情吗?
编辑:
当我尝试建议的修复时,我收到这个令人毛骨悚然的错误:
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
Run Code Online (Sandbox Code Playgroud)
问题出在这一行:
img = tk.PhotoImage(file = src)
Run Code Online (Sandbox Code Playgroud)
您正在使用PhotoImagetkinter 的库存。PIL它与您想要使用的ImageTkfrom不兼容PIL。
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
src = Image.open("C:\\Users\\Matt\\Desktop\\K8pnR.gif")
img = ImageTk.PhotoImage(file = src)
label = tk.Label(image = img, master = root)
label.pack()
Run Code Online (Sandbox Code Playgroud)
这是stockPhotoImage类的文档: http: //effbot.org/tkinterbook/photoimage.htm,它只接受构造函数中的路径。
| 归档时间: |
|
| 查看次数: |
835 次 |
| 最近记录: |