当我使用PIL时,我必须导入大量的PIL模块。我正在尝试三种方法来做到这一点,但只有最后一种方法才有效,尽管对我来说是合乎逻辑的:
导入完整的PIL并在代码中调用它的模块:NOPE
>>> 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导入所有内容:NOPE
>>> 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导入一些模块:确定
>>> from PIL import Image
>>> image = Image.new('1', (100,100), 0)
>>> image
<PIL.Image.Image image mode=1 size=100x100 at 0xB6C10F30>
>>> # works...
我没有得到什么?
答案 0 :(得分:3)
PIL不会自行导入任何子模块。这实际上很常见。
因此,当您使用from PIL import Image
时,实际上找到Image.py
文件并导入该文件,而当您尝试在PIL.Image
之后调用import PIL
时,您正在尝试空模块上的属性查找(,因为您没有导入任何子模块)。
同样的推理适用于from PIL import *
无效的原因 - 您需要显式导入Image子模块。无论如何,from ... import *
被视为不良做法,因为会发生命名空间污染 - 最好的办法是使用from PIL import Image
。
此外,不再维护PIL,但出于向后兼容的目的,如果您使用from PIL import Image
,则可以确保您的代码与仍然维护的Pillow保持兼容(仅反对使用{ {1}})。