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

    Gerenciador de senhas simples desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Simple Password Manager in Python

    Build a simple Python password manager with Fernet encryption, file storage, password generation using secrets, and an interactive terminal menu.

    Ler mais

    Tempo de leitura: 4 minutos
    30/05/2026
    Conversor de moedas desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build a Python Currency Converter Step by Step

    Build a Python currency converter step by step using the requests library and a real exchange rate API, with user

    Ler mais

    Tempo de leitura: 4 minutos
    29/05/2026
    Calendário mensal gerado automaticamente com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Generate a Monthly Calendar in Python in 2 Minutes

    Generate a monthly calendar in Python in 2 minutes using the built-in calendar module, with user input, Sunday start, file

    Ler mais

    Tempo de leitura: 4 minutos
    29/05/2026
    Sistema de login simples desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Simple Python Login System with TXT Files

    Learn how to build a simple Python login system using TXT files, with user registration, password validation, error handling, and

    Ler mais

    Tempo de leitura: 5 minutos
    29/05/2026
    Sistema de lembretes e alarmes desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build an Alarm Reminder System in Python

    Learn how to build a Python alarm reminder system step by step, using datetime, playsound, input validation, and a complete

    Ler mais

    Tempo de leitura: 5 minutos
    29/05/2026
    Sistema de tradução automática desenvolvido com Python
    Projects
    Foto de perfil de Leandro Hirt da Academify

    Build an Automatic Translation System in Python

    Learn how to build an automatic translation system in Python using Googletrans, with language detection, batch translation, error handling, and

    Ler mais

    Tempo de leitura: 5 minutos
    28/05/2026