【问题标题】:Why do my Python PIL imports not working?为什么我的 Python PIL 导入不起作用?
【发布时间】:2016-10-12 18:55:22
【问题描述】:

当我使用 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 导入一些模块:OK

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

我在这里没有得到什么?

【问题讨论】:

    标签: python python-3.x import python-import pillow


    【解决方案1】:

    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 相对)。

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 2018-05-27
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      相关资源
      最近更新 更多