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

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

当我使用 PIL 时,我必须导入大量 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...

我没有得到什么?

最佳答案

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

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

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

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

关于python - 为什么我的 Python PIL 导入不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771395/

相关文章:

Python CSV 作为字典读入,第 n 行作为标题

python - 安装了 Django AllAuth,找不到登录或注册

python-3.x - 使用 Python 加密文本 - RaspberryPi Org 项目

python - Python 中的字符串格式化 %i

python - VS Code 无法识别 SQLAlchemy

csv - 如何将 csv 导入 chart.js?

python - 如何将所有数据从 sqlite 数据库导入到 Django 非相关数据库

python - 使用 pandas python reshape 为二进制变量

python 新的 AST 优化器

javascript - Firefox 扩展中的 Google 搜索 API