当我使用 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/