Python PIL没有'Image'属性。

60

我正在使用Python2.6,并在今天遇到了一个问题。它显示“module”没有属性“Image”。这是我的输入。为什么第一次我不能使用PIL.Image?

>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
4个回答

79

__init__.py是PIL中的一个空占位符,这在常见。它本身不会自动导入任何内容。

当你执行from PIL import Image时,它会在PIL包中查找文件Image.py并将其导入。当你执行PIL.Image时,实际上是对PIL模块进行属性查找(除非你明确导入其他东西,否则该模块只是一个空占位符)。

事实上,导入模块通常不会导入子模块。 os.path是一个著名的例外,因为os模块是特殊的。

更多信息:
图像模块


45

如果你和我一样,发现被接受的答案有点令人困惑,因为你肯定之前能够使用

import PIL
PIL.Image

有时候,造成这种情况的一个潜在原因是如果您的Python会话中运行了from PIL import Imageimport PIL.Image,即使它在完全不同的作用域中,您也将能够访问PIL.Image

特别地,当导入matplotlib时,它也会执行这样的操作。所以如果您运行

import matplotlib
import PIL
PIL.Image

它有效了。谢谢,Python。

不要相信任何人。不要相信Python。使用import PIL.Image


4
这个答案很有启发性,应该成为主要答案的一部分。 - akonsk

9

您可以做:

try:
    import Image
except ImportError:
    from PIL import Image

使用Pillow而不是PIL更好。


1

解决方案是

不要使用这种形式

import PIL
PIL.Image

使用这个表单
from PIL import Image
Image

在Linux系统中,这两种形式都可以正常工作。

enter image description here

但在Windows中,存在一个问题

enter image description here


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