用python生成一个二维码
时间: 2024-05-02 16:18:26 浏览: 190
可以使用qrcode库来生成二维码,安装方式如下:
```
pip install qrcode[pil]
```
其中,pil是一个可选依赖项,用于在终端中显示二维码图片。
生成二维码的代码如下:
```Python
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('http://www.baidu.com')
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.show()
```
其中,version表示二维码的版本,取值范围为1~40,值越大表示二维码可以容纳的信息越多;error_correction表示纠错水平,取值范围为ERROR_CORRECT_L、ERROR_CORRECT_M、ERROR_CORRECT_Q、ERROR_CORRECT_H,依次表示7%、15%、25%、30%的错误恢复能力;box_size表示每个小格子的像素大小;border表示边框的格子数。
add_data方法用于添加数据,make方法生成二维码,fit=True表示自动调整大小以适应数据。make_image方法用于生成图片,fill_color表示二维码的颜色,back_color表示背景颜色,可以自行调整。
运行代码后,会在终端中显示二维码图片,也可以通过img.save()方法保存图片到文件。
阅读全文
相关推荐

















