PIL图像导入错误

7

我在虚拟环境中安装了Pillow和qrcode模块。

从Python shell中,我可以使用PIL编程方式创建一个测试图像:

>>> from PIL import Image
>>> img = Image.new('1', (200, 200))
>>> img.save('test-image.jpeg', 'JPEG')

好的,这正如我所希望的那样运作。然而,当我尝试使用依赖于PIL模块的模块时,出现了以下错误:

>>> import qrcode
>>> qr_code = qrcode.make("1") 
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/home/vagrant/.virtualenvs/env1/local/lib/python2.7/site-packages/qrcode/main.py", line 8, in make
     return qr.make_image()
   File "/home/vagrant/.virtualenvs/env1/local/lib/python2.7/site-packages/qrcode/main.py", line 186, in make_image
     from qrcode.image.pil import PilImage
   File "/home/vagrant/.virtualenvs/env1/local/lib/python2.7/site-packages/qrcode/image/pil.py", line 5, in <module>
     import Image
ImportError: No module named Image

为什么qrcode不能导入PIL的Image类,但从shell中可以工作?

1
这有点冒险,但是... from PIL import ImageDraw 在 shell 上也能用吗?如果该模块在 PIL 包中某种方式丢失,qrcode 将假定 Image 也从 PIL 包中丢失,并尝试从顶层导入它,这将导致你看到的问题。 - abarnert
更有可能的情况是您实际上没有从正确的虚拟环境进行测试。在您的shell中,在from PIL import Image之后,只需键入Image并查看它给出的路径。它是否在/home/vagrant/.virtualenvs/env1/blah/blah内部? - abarnert
1个回答

6
这是您安装的问题: Image 模块已作为 PIL 模块的子包进行安装,而您正在使用的库期望直接在Python路径中找到 Image 模块。最简单的解决方法是将以下内容替换为:
import Image

使用:

from PIL import Image

在文件qrcode/image/pil.py中。

是的,老派的PIL有时会以一种方式安装,有时会以另一种方式安装。许多人会明确地将该软件包添加到“sys.path”中以解决此问题,但这总是一个可怕的想法。Pillow选择了更明智的方法并始终坚持它,但还有一些其他软件包期望使用另一种方式。 - abarnert
但是... 这样做行不通。 如果你看一下源代码,它已经尝试使用from PIL import Image,只有当失败时才会退回到import Image - abarnert
在这种情况下,你的虚拟环境肯定出了问题。我刚测试过,它是可以工作的:我运行了 virtualenv so && source so/bin/activate && pip install pillow qrcode six && python,然后输入 import qrcode; qrcode.make("1").show()。对于糟糕的注释格式化,我很抱歉。 - Stefano Sanfilippo
我启动了一个新的vagrant box,并进行了全新的安装,一切都按预期工作。感谢您指引我正确的方向。 - Marc Wilson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接