QR Code Generator
The `qrcode` library is a pure Python QR Code image generator, enabling users to encode various data types into QR code format. It offers extensive control over QR code appearance, including size, border, error correction levels, and colors. The current stable version is 8.2. The library maintains an active release cadence, with multiple recent releases, including significant updates like version 8.0, indicating ongoing development and support.
Warnings
- gotcha To save QR codes as image files (e.g., PNG, JPEG), the Pillow library is required. Installing `qrcode` without the `[pil]` extra will not install Pillow, leading to errors when calling image-related methods like `make_image()` or `save()` if a pure Python PNG encoder (like `pypng`) is not implicitly used or insufficient.
- gotcha The QR code's visual size and density can vary significantly based on the `version` and `fit` parameters. If `version` is set to `None` (default for `QRCode` class) and `fit` is `True`, `qrcode` will automatically determine the smallest version that fits the data, potentially resulting in different sizes for slightly varied input data. This can be problematic for consistent sizing in layouts.
- gotcha Choosing the correct `error_correction` level (L, M, Q, H) is crucial. Higher error correction allows the QR code to be scanned even if partially damaged, but it increases the data density, making the QR code physically larger and potentially harder to print or scan in some scenarios. The default is `ERROR_CORRECT_M`.
Install
-
pip install qrcode -
pip install "qrcode[pil]"
Imports
- qrcode
import qrcode
- QRCode
from qrcode import QRCode
- constants
from qrcode import constants
Quickstart
import qrcode
import os
# Data to encode
data = "https://checklist.day/"
# --- Simple QR code generation (shortcut) ---
img_simple = qrcode.make(data)
img_simple.save("simple_qrcode.png")
print("Simple QR code saved as simple_qrcode.png")
# --- Advanced QR code generation (QRCode class for more control) ---
qr = qrcode.QRCode(
version=1, # Controls the size (1-40), None for automatic (fits data)
error_correction=qrcode.constants.ERROR_CORRECT_L, # Error correction level (L, M, Q, H)
box_size=10, # Number of pixels per 'box' or module
border=4, # Number of boxes thick the border should be (minimum 4)
)
qr.add_data(data)
qr.make(fit=True) # Ensures the entire data fits into the QR code
img_advanced = qr.make_image(fill_color="black", back_color="white")
img_advanced.save("advanced_qrcode.png")
print("Advanced QR code saved as advanced_qrcode.png")
# To display in a notebook (requires Pillow and an interactive environment)
# img_advanced.show()