为什么我的 Python PIL 导入不起作用?

Why do my Python PIL imports not working?

当我使用 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 导入所有内容:否

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

我没有得到什么?

PIL 不会自行导入任何子模块。这实际上很常见。

因此,当您使用 from PIL import Image 时,您实际上找到了 Image.py 文件并将其导入,而当您尝试在 import PIL 之后调用 PIL.Image 时,您重新尝试对空模块进行属性查找(因为您没有导入任何子模块)。

相同的推理适用于为什么 from PIL import * 不起作用 - 您需要显式导入 Image 子模块。在任何情况下,由于会发生名称空间污染,from ... import * 被视为不好的做法 - 最好的选择是使用 from PIL import Image

此外,PIL 不再被维护,但出于向后兼容的目的,如果您使用 from PIL import Image,您可以确保您的代码将与仍在维护的 Pillow 保持兼容(与仅使用 import Image).