2012-08-11 76 views
9

我使用python2.6,今天早上出了问题。它说'模块'没有属性'图像'。这是我的输入。为什么我第一次不能使用PIL.Image?Python PIL没有属性'图像'

>>> 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'> 

回答

14

PIL的__init__.py只是一个普通的空存根。它本身不会神奇地导入任何东西。

当你做from PIL import Image它在PIL包中查找并找到文件Image.py并导入它。当你做PIL.Image时,你实际上是在PIL模块上做一个属性查找(除非你明确地导入东西,否则它只是一个空的存根)。

实际上,导入模块通常是并不是导入子模块。 os.path是一个着名的例外,因为os模块是神奇的。

更多信息:
The Image Module

-1

代替from PIL import Imageimport PIL
尝试

`PIL.Image` 
2

你可以这样做:

try: 
    import Image 
except ImportError: 
    from PIL import Image 

它更好地使用枕头代替PIL。