【问题标题】:Odd bugs when image processing with Pillow (in tkinter)使用 Pillow 处理图像时出现奇怪的错误(在 tkinter 中)
【发布时间】: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

【问题讨论】:

    标签: python jpeg gif pillow


    【解决方案1】:

    问题出在这一行:

    img = tk.PhotoImage(file = src)
    

    您正在使用来自 tkinter 的股票 PhotoImage。它与PIL 不兼容,你想从PIL 使用ImageTk

    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()
    

    这里是 stock PhotoImage class: http://effbot.org/tkinterbook/photoimage.htm 的文档,它只接受构造函数中的路径。

    【讨论】:

    • 我遇到另一个奇怪的错误...请检查我的编辑。
    • 抱歉耽搁了,看来问题出在file = src。不要命名该参数或正确命名,即image = src
    • 啊……谢谢!我知道这可能是我错过的一件小事......我正在扯掉我的头发。你太棒了!
    猜你喜欢
    • 1970-01-01
    • 2010-12-29
    • 2015-05-05
    • 2018-09-25
    • 2021-08-27
    • 2012-05-11
    • 2015-05-21
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多