Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

How to Generate a QR Code in Python

Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.

Easy Python 3.9+ Jun 27, 2026 Automation & scripting 1 views 0 copies

Requires third-party packages — install first
pip install qrcode Pillow

Python code

23 lines
Python 3.9+
import qrcode

# Data to encode
data = "https://www.example.com"

# Create QR code instance
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

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

# Create an image from the QR code
img = qr.make_image(fill_color="black", back_color="white")

# Save the image
img.save("example_qr.png")
print("QR code generated and saved as example_qr.png")

Output

stdout
QR code generated and saved as example_qr.png

How it works

The qrcode.QRCode object defines the QR code's settings like error correction level and size. add_data() specifies the content to encode, and make(fit=True) automatically adjusts the QR code's version to fit the data. The make_image() method generates a PIL Image object, which is then saved to disk as example_qr.png. The library handles all encoding and error correction patterns internally.

Common mistakes

  • Forgetting to install the Pillow dependency, which is required for image creation
  • Using too low a box_size or border value causing the QR code to be unreadable when scanned
  • Passing invalid or unsupported data (e.g., binary content) that exceeds QR code capacity

Variations

  1. Generate an in-memory QR code as a bytes object using `io.BytesIO` instead of saving to file
  2. Customize colors or add a logo by overlaying an image after generation

Real-world use cases

  • Generating QR codes for event tickets or loyalty cards so users can present them on mobile
  • Creating shareable Wi-Fi login QR codes for guest networks
  • Producing batch QR codes for inventory labels from a spreadsheet of product URLs

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.