为何import PIL调用PIL.Image报错,而from PIL import Image正常?
PIL模块导入报错原因解析
这是因为PIL是Python包,而Image是它内部的子模块,Python的包导入规则导致了这个差异:
from PIL import Image这种写法,直接把PIL包下的Image子模块导入到当前命名空间,所以能直接调用Image.open()。import PIL仅导入了PIL包本身,但PIL的顶层命名空间里并没有自动包含Image子模块——因为PIL的__init__.py文件里没有把Image显式导入到包的顶层。这时候直接访问PIL.Image,Python会判定PIL模块没有该属性,抛出AttributeError。
如果想用import PIL的写法,需要额外显式导入子模块:
import PIL import PIL.Image # 显式导入Image子模块 image = PIL.Image.open("./x.png")
内容的提问来源于stack exchange,提问作者Pippomuc
相关产品推荐
相关产品推荐

