2012-08-11 70 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。