Python3下zbar模块报错:AttributeError: module 'zbar' has no attribute 'ImageScanner'
解决Python3下zbar模块的AttributeError问题
嘿,这个问题我之前在最新版Ubuntu上也碰到过——确实和你怀疑的一样,是Python3环境下zbar的API兼容问题。
问题根源
你代码里用的zbar.Scanner()是Python2时代的旧写法,但现在Python3的zbar绑定不管是官方源的python3-zbar还是pip装的旧zbar包,都已经没有这个类了。而且qrtools这个库早就停止维护了,对Python3的支持很差,混用它和zbar反而容易出问题。
两种解决方案
方案1:调整zbar代码适配Python3 API
如果不想换库,可以改成zbar在Python3下的正确用法:
import pyqrcode from PIL import Image import zbar # 生成二维码这部分没问题,保留 qr = pyqrcode.create("She got two little horns and they get me a little bit") qr.png("horn.png", scale=6) # 解码部分改成Python3兼容的写法 # 先把PIL图像转成zbar能处理的灰度图和字节流 image = Image.open("horn.png").convert('L') width, height = image.size raw_image_data = image.tobytes() # 创建ImageScanner(注意不是Scanner)实例 scanner = zbar.ImageScanner() scanner.parse_config('enable') # 启用扫描配置 # 构建zbar的Image对象 zbar_img = zbar.Image(width, height, 'Y800', raw_image_data) # 执行扫描 scanner.scan(zbar_img) # 输出解码结果 for symbol in zbar_img: print("解码内容:", symbol.data.decode('utf-8'))
方案2:换成更现代的库(推荐)
qrtools已经没人维护了,pyzbar是zbar的Python3友好绑定,用起来更省心:
- 先清理旧的冲突包:
sudo apt remove python3-zbar python-qrtools pip3 uninstall zbar qrtools -y
- 安装新依赖:
sudo apt install libzbar0 pip3 install pyqrcode pyzbar pillow
- 简化后的代码:
import pyqrcode from pyzbar.pyzbar import decode from PIL import Image # 生成二维码 qr = pyqrcode.create("She got two little horns and they get me a little bit") qr.png("horn.png", scale=6) # 解码一步到位 decoded_results = decode(Image.open("horn.png")) for res in decoded_results: print("解码结果:", res.data.decode('utf-8'))
这个方案不仅代码更简洁,而且几乎不会碰到版本兼容问题,我自己在最新版Ubuntu上试过,完全没问题。
小提示
之前你装的依赖可能混了Python2和Python3的包,导致调用了错误的模块版本,所以先清理再安装是关键哦。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

