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.
pip install qrcode Pillow
Python code
23 linesimport 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
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
- Generate an in-memory QR code as a bytes object using `io.BytesIO` instead of saving to file
- 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
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.