2016-06-12 108 views
6

當我使用PIL時,必須導入大量的PIL模塊。我用三種方式嘗試做到這一點,但只有最後一部作品,儘管所有的都是邏輯對我說:爲什麼我的Python PIL導入不起作用?

導入完整PIL並調用它的模塊代碼:沒

>>> import PIL 
>>> image = PIL.Image.new('1', (100,100), 0) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'module' object has no attribute 'Image' 

導入一切從PIL:沒

>>> from PIL import * 
>>> image = Image.new('1', (100,100), 0) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'Image' is not defined 

導入一些模塊由PIL:OK

>>> from PIL import Image 
>>> image = Image.new('1', (100,100), 0) 
>>> image 
<PIL.Image.Image image mode=1 size=100x100 at 0xB6C10F30> 
>>> # works... 

我沒有在這裏得到什麼?

回答

3

PIL不會自行導入任何子模塊。這實際上很常見。

所以當你使用from PIL import Image,你居然找到Image.py文件和導入,而當你嘗試只是調用import PILPIL.Image,你嘗試空模塊上的屬性查詢(因爲你沒有進口任何子模塊)。

相同的推理適用於爲什麼from PIL import *不起作用 - 您需要顯式導入圖像子模塊。在任何情況下,from ... import *被認爲是不好的做法,由於名稱空間污染將發生 - 你最好的選擇是使用from PIL import Image

此外,PIL不再被保留,但爲了向下兼容的目的,你應該使用from PIL import Image你可以確保你的代碼將繼續與仍然保持Pillow(如只使用import Image oppposed)兼容。

相關問題