Generate QR Codes with Python in Minutes

Published on: June 1, 2026
Reading time: 3 minutes
Geração automática de QR Code usando Python

Generating a Quick Response code — the famous QR Code — has become an essential skill for developers bridging the physical and digital worlds. Whether sharing a website link, Wi-Fi credentials, or payment data, knowing how to generate QR codes with Python lets you build personalized solutions extremely quickly. Python stands out for its simplicity and vast library ecosystem, making this task accessible even for beginners.

Why automate QR code creation with Python?

Third-party websites can generate QR codes for free, but relying on external tools becomes a bottleneck when you need to generate hundreds at once or integrate them into a larger system. With Python you gain the autonomy to apply this feature in automation scripts, inventory systems, or personalized digital invitations.

Imagine working at a company and needing a unique code for each employee to access an internal portal. Doing it manually would be impractical. With Python you can read a list of names from a file and generate all the codes in seconds — and save them in organized folders using the os module to create directories automatically.

Installing the required libraries

pip install qrcode[pil]

The [pil] suffix ensures Pillow is also installed. Without it the library can generate QR code data but cannot turn it into a visual file like PNG or JPG.

Creating your first simple QR code

import qrcode

# Define the destination link
link = "https://www.wikipedia.org"

# Generate the QR code image
image = qrcode.make(link)

# Save the file
image.save("my_first_qrcode.png")

Running this script creates a file called my_first_qrcode.png in the same folder as your Python file. The make() method is a convenience function that uses default settings to create the code quickly — an ideal starting point for anyone following a Python beginner’s guide.

Customizing with the QRCode class

For more control over design and error tolerance, use the QRCode class. Key parameters include version (1-40, controls size and data capacity), error_correction (readability when damaged), box_size (pixels per module), and border (white border thickness).

import qrcode

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

qr.add_data("https://www.python.org")
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
img.save("custom_qrcode.png")

The fit=True parameter instructs the library to automatically find the smallest version that fits the data, optimizing the final image size.

Batch generation with loops

import qrcode

links = {
    "Google":  "https://www.google.com",
    "Python":  "https://www.python.org",
    "GitHub":  "https://github.com"
}

for name, url in links.items():
    img = qrcode.make(url)
    img.save(f"qrcode_{name}.png")
    print(f"Code for {name} generated successfully!")

Adding custom colors

# Custom color example
img = qr.make_image(fill_color="darkblue", back_color="lightyellow")
img.save("colored_qrcode.png")

When choosing colors, ensure sufficient contrast so phone cameras can scan the code reliably. Very light fill colors can make the code unreadable in real environments.

Complete project script

import qrcode
import os

def generate_custom_qr(content, filename, fill="black", back="white"):
    try:
        # Create output folder if it doesn't exist
        os.makedirs("my_qrcodes", exist_ok=True)

        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=10,
            border=4,
        )

        qr.add_data(content)
        qr.make(fit=True)

        img = qr.make_image(fill_color=fill, back_color=back)
        output_path = os.path.join("my_qrcodes", f"{filename}.png")
        img.save(output_path)
        print(f"Success! Code saved to: {output_path}")

    except Exception as e:
        print(f"Error generating code: {e}")

if __name__ == "__main__":
    generate_custom_qr("https://www.python.org", "python_tutorial", "darkgreen", "white")

QR codes can encode plain text (quick notes or safety instructions), vCards (digital business cards that save contacts), Wi-Fi credentials (auto-connect without typing a password), and email templates (open a mail app with recipient and subject pre-filled).

Frequently Asked Questions

Can I create a QR code that never expires?

Yes. Locally generated QR codes are static — the information is encoded directly in the image. As long as the destination link or text remains valid, the code works forever.

Can I add a logo in the center?

Yes, but it requires using Pillow directly to overlay images. Use the highest error correction level (ERROR_CORRECT_H) so the code remains scannable with the logo on top.

Which file formats can I save?

PNG, JPG, BMP, and SVG are the most common. PNG is recommended because it preserves transparency and does not lose quality through compression.

Can Python also read QR codes?

Yes. Libraries like opencv or pyzbar can identify and decode information from an image file or webcam feed.

Is internet required to generate QR codes?

No. Once the libraries are installed on your machine, all image processing happens offline without connecting to external servers.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Criação de chatbot com API da OpenAI usando Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Chatbot with the OpenAI API

    Build a Python chatbot with the OpenAI Responses API, secure environment variables, conversation memory, model configuration, and practical error handling.

    Ler mais

    Tempo de leitura: 7 minutos
    10/07/2026
    Chatbot simples em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Simple Chatbot with Python

    Build a simple Python chatbot with rules, input normalization, intents, random replies, JSON data, conversation loops, tests, and practical extension

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Criptografia e segurança de dados em Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Secure Password Generator in Python

    Build a secure password generator in Python with secrets, configurable character rules, a CLI, passphrases, validation, and practical tests.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Jogo da forca para iniciantes desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Hangman Game in Python

    Build a complete Hangman game in Python with random words, input validation, repeated-letter checks, lives, ASCII art, and replay support.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    Quiz interativo no terminal desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Terminal Quiz Game in Python

    Build a terminal quiz game in Python with questions, input validation, scoring, shuffled answers, replay support, JSON loading, and tests.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Jogo de adivinhação de números desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Number Guessing Game in Python

    Build a number guessing game in Python with random numbers, input validation, hints, limited attempts, replay support, and clean functions.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026