【发布时间】:2016-01-31 14:53:33
【问题描述】:
我正在尝试使用 Pillow 在 Tkinter 中显示图像,但我收到一个奇怪的错误:“进程以退出代码 -1073741819 (0xC0000005) 完成”并且 Tkinter 窗口从未出现。
这是代码(简化到最大):
from PIL import Image, ImageTk
from tkinter import Tk
t = Tk()
i = Image.open('data/pic.jpg') # small picture (29kb, 100x100px)
i_tk = ImageTk.PhotoImage(i) # The problem disappears when this line is commented out.
t.mainloop()
我在 Windows 10 上使用 Python 3.5、Tcl/Tk 8.6、Pillow 3.0.0(全部为 64 位)
相同的脚本(用 Tkinter 替换 tkinter)在具有 Python 2.7.9、Tcl/Tk 8.5 和 Pillow 2.9.0 的同一台机器上完美运行(当我关闭 Tk 窗口时,出现 Tk 窗口并且退出代码为 0 )。
任何帮助将不胜感激。
编辑:根据用户 5510752 的建议,我将 i_tk = ImageTk.PhotoImage(i) 更改为 i_tk = tkinter.PhotoImage(i)。现在问题已经从我制作 PhotoImage 的位置转移到了我将其插入画布的位置。
这是新代码:
from PIL import Image
from tkinter import Tk, PhotoImage, Canvas
t = Tk()
c = Canvas(t, bg="blue")
c.grid(sticky="news")
c.i = Image.open("data/pic.jpg")
c.p = PhotoImage(c.i)
c.create_image(0, 0, image=c.p) # errors out here
t.mainloop()
这给出了这个错误TypeError: __str__ returned non-string (type JpegImageFile)。
Traceback (most recent call last):
File "D:/Workspace/PythonProjects/Puzzle 3.5/main.py", line 29, in <module>
c.create_image(0, 0, image=c.p)
File "C:\Python 3.5\lib\tkinter\__init__.py", line 2328, in create_image
return self._create('image', args, kw)
File "C:\Python 3.5\lib\tkinter\__init__.py", line 2319, in _create
*(args + self._options(cnf, kw))))
TypeError: __str__ returned non-string (type JpegImageFile)
我查看了 Python 3 的此函数的不同签名,但我找不到任何东西。不过,这一行适用于 Python 2.7(使用 ImageTk.PhotoImage)。更奇怪的是,如果我尝试将 c.i 而不是 c.p 加载到画布中,代码不会出错并且我得到一个空画布。
[编辑2]
按照 R4PH43L 的建议,我试过了:
from tkinter import Tk, PhotoImage, Canvas
t = Tk()
c = Canvas(t, bg="blue")
c.grid(sticky="news")
c.p=PhotoImage(file="data/pic.jpg")
c.create_image(0, 0, image=c.p) # errors out here
t.mainloop()
这给出了一个新错误:
Traceback (most recent call last):
File "D:/Workspace/PythonProjects/Puzzle 3.5/main.py", line 28, in <module>
c.p=PhotoImage(file="data/pic.jpg")
File "C:\Python 3.5\lib\tkinter\__init__.py", line 3393, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python 3.5\lib\tkinter\__init__.py", line 3349, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "data/pic.jpg"
我每次尝试使用不同的 JPEG 都无济于事。这次我也尝试使用 GIF 并且它有效(但我需要打开 JPEG,所以......)。值得注意的是,libjpeg 已安装在我的机器上,并且 Pillow 使用它似乎没有任何问题(除非我将图片传递给 ImageTk,然后我们又回到了我原来的错误)。
PS:如果有人设法在 python 3.5 的 tkinter 画布中显示 jpg 文件,请发布您正在使用的 Tcl/Tk、libjpeg 和 Pillow 的版本。我怀疑这可能只是因为两个模块在我当前的 Python 3 配置中不兼容。
【问题讨论】:
-
您缺少前导斜杠 Image.open('/data/pic.jpg')
-
我试过了,但是找不到带斜线的图片。
-
请给我们完整的错误信息,包括。调用栈
-
@R4PH43L:对不起,我忘了添加它。现在已经完成了。希望它有所帮助:)