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

Nei*_*ein 6 python import python-import python-3.x pillow

当我使用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'
Run Code Online (Sandbox Code Playgroud)

从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 
Run Code Online (Sandbox Code Playgroud)

从PIL导入一些模块:好的

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

我没有得到什么?

mir*_*ulo 3

PIL 本身不导入任何子模块。这实际上很常见。

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

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

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