Skip to main content

QR code generator in Python

· 8 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

Creating a QR code generator in Python is remarkably straightforward, thanks to robust, community-maintained libraries. The most popular and simplest choice is the qrcode library. This article will focus on using this library to generate, customize, and save QR codes with minimal code.

Since there are multiple excellent libraries available for QR code generation in Python, I propose we focus this article on the simple and popular qrcode library, and then follow up with another article on the modern, standard-compliant segno library for advanced use cases (MicroQR codes, superior vector output, etc.).

Easy Python QR Code Generation with the qrcode Library

The qrcode library is a pure Python solution that handles all the technical details of QR code encoding, error correction, and drawing, allowing you to generate professional-quality codes with just a few lines of code.

Installation

Before you begin, you need to install the qrcode library. If you want to save the QR code as an image file (like PNG), you also need the Pillow library (PIL):

pip install qrcode[pil]

Basic QR Code Generation

The simplest way to create a QR code is to use the make() function, which creates an image object directly.

Code Example 1: Generate and Display (In Notebook/Shell)

If you are working in an interactive environment like a Jupyter Notebook or an IPython console, you can generate and display the QR code instantly.

import qrcode

# 1. Define the data you want to encode
data = "https://hrekov.com/docs/keep-scrolling"

# 2. Generate the QR code image
img = qrcode.make(data)

# 3. Display the image (for interactive environments)
# img.show()

# 4. Save the image as a PNG file
img.save("basic_qrcode.png")

print("Basic QR code saved to basic_qrcode.png")
Output FileAnnotation
basic_qrcode.pngA default, black-and-white QR code that links to the specified URL.

Customizing QR Code Appearance and Size

For more control over the QR code's size, error correction, colors, and border, you should use the QRCode class constructor instead of the simple make() function.

Code Example 2: Setting Size, Border, and Colors

The QRCode class allows fine-tuning:

  • version: Controls the size of the QR code matrix (1 to 40). None (default) selects the smallest possible size based on the data.
  • error_correction: Sets the robustness of the code. Options include:
    • constants.ERROR_CORRECT_L (7% of data can be restored)
    • constants.ERROR_CORRECT_M (15% - default)
    • constants.ERROR_CORRECT_Q (25%)
    • constants.ERROR_CORRECT_H (30% - highest correction)
  • box_size: How many pixels each "box" or module of the QR code is.
  • border: How many boxes thick the border around the code should be (standard is 4 or more).
import qrcode
from qrcode import constants

def create_custom_qrcode(data, filename, fill_color, back_color):
"""Generates a customized QR code and saves it."""

qr = qrcode.QRCode(
version=1,
error_correction=constants.ERROR_CORRECT_H, # Highest error correction (30%)
box_size=10, # Each module is 10x10 pixels
border=5, # 5 boxes wide border
)

# Add data to the QR code object
qr.add_data(data)
qr.make(fit=True)

# Create the image using the PilImageFactory and set colors
img = qr.make_image(
fill_color=fill_color,
back_color=back_color,
# Use the appropriate factory for image generation
image_factory=qrcode.image.pil.PilImage
)

# Save the image
img.save(filename)
print(f"Custom QR code saved to {filename}")

# Generate a green-on-white QR code
url_data = "https://hrekov.com/apps/"
create_custom_qrcode(url_data, "custom_green_qrcode.png", "green", "white")

# Generate a blue-on-yellow QR code
text_data = "Custom Text: Hello, world! This text is encoded."
create_custom_qrcode(text_data, "custom_blue_yellow_qrcode.png", "#1a73e8", "#ffecb3")
Output FileCustomization Detail
custom_green_qrcode.pngHigh error correction and a green foreground.
custom_blue_yellow_qrcode.pngCustom blue foreground and light yellow background (using hex codes).

Generating QR Codes as SVG or other formats

The qrcode library is not limited to PNG. By specifying a different image_factory, you can output the QR code as a Vector Graphic (SVG) or another format, which is ideal for printing and high-resolution scaling.

Code Example 3: Saving as Scalable Vector Graphics (SVG)

To use the SVG factory, you need to install the dependency first:

pip install qrcode[svg]
import qrcode

# The data for the QR code
repo_data = "https://github.com/hrekov/my-private-lib"

# 1. Instantiate the QRCode class
qr = qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=12,
border=4,
)
qr.add_data(repo_data)
qr.make(fit=True)

# 2. Use the SvgImage factory
# There are multiple SVG factories:
# SvgImage: simple, path-based SVG
# SvgFillImage: SVG with 'fill' attribute
# SvgFragmentImage: SVG without XML declaration, for embedding
img_svg = qr.make_image(
image_factory=qrcode.image.svg.SvgPathImage,
fill_color="black",
back_color="transparent" # Transparent backgrounds work well with SVG
)

# 3. Save the SVG file
svg_filename = "repo_link_qrcode.svg"
img_svg.save(svg_filename)

print(f"Vector QR code saved to {svg_filename}")
Output FileAnnotation
repo_link_qrcode.svgA vector graphic file that can be scaled infinitely without pixelation.

Conclusion and Next Steps

The qrcode library offers a powerful and flexible way to integrate QR code generation into any Python application, whether for simple URLs or complex data strings.

Your next article should focus on segno for modern compliance and advanced features not covered here.

Sources and Further Reading

  1. qrcode Library Documentation: pypi.org/project/qrcode
  2. QR Code Error Correction Levels Explained: qrcode.com/en/about/error_correction
  3. Python PIL/Pillow Documentation (for image handling): pillow.readthedocs.io/en/stable/
  4. How to Use SVG for High-Resolution QR Codes: youtube.com/watch?v=R9_m8L9vG2Q