DEV Community

qing
qing

Posted on

Build a QR Code Generator with Python

Build a QR Code Generator with Python

Imagine walking into a coffee shop, holding your phone up to a tiny square on the counter, and instantly pulling up your order history without typing a single character. That magic isn’t reserved for big tech companies with millions in R&D; you can build that exact same capability in your own Python script this afternoon. QR codes have evolved from clunky marketing tools into essential bridges between the physical and digital worlds, and Python is the perfect language to bridge them yourself.

Let’s get straight to the code. We’ll build a functional QR code generator that takes user input, creates a scannable image, and saves it to your disk. No complex frameworks, no cloud APIs—just pure, local Python.

Setting Up Your Environment

Before writing a single line of logic, you need the right tools. The Python ecosystem offers a few libraries for this, but the most robust and widely used one is qrcode. It’s powerful, supports color customization, and integrates seamlessly with the Pillow image library for saving files.

Open your terminal or command prompt and run this installation command:

pip install qrcode[pil]
Enter fullscreen mode Exit fullscreen mode

This installs the qrcode library along with its dependency, Pillow (often abbreviated as pil), which handles image processing. If you’re on a system where pip isn’t recognized, try pip3 instead. Once the installation finishes without errors, you’re ready to code.

Building the Basic Generator

Now, let’s create a script that generates a QR code from a URL. We’ll start with the simplest version: a black-and-white code that redirects to a website.

Create a new file named qr_generator.py and add the following code:

import qrcode

# The data you want to encode (e.g., a URL)
data = "https://www.example.com"

# Generate the QR code
qr = qrcode.make(data)

# Save the QR code as an image file
qr.save("my_website.png")

print("QR code generated and saved as 'my_website.png'")
Enter fullscreen mode Exit fullscreen mode

Run this script with python qr_generator.py. If you open the resulting my_website.png file in your image viewer, you’ll see a crisp QR code. Point your phone’s camera at it, and you should be redirected to https://www.example.com.

This is the core of QR generation: import the library, pass your data to make(), and save the result. It’s that simple. But let’s make it more practical and interactive.

Making It Interactive and Customizable

A static URL is useful, but a real-world tool needs to accept user input. Let’s upgrade our script to ask the user for their desired URL or text, and even let them customize the colors.

Here’s the enhanced version:

import qrcode

def generate_custom_qr():
    # Get user input
    data = input("Enter the URL or text to encode: ").strip()
    if not data:
        print("Error: No data entered.")
        return

    # Optional: Customize colors (default is black on white)
    fill_color = input("Enter fill color (e.g., 'black', '#0000FF'): ").strip() or 'black'
    back_color = input("Enter background color (e.g., 'white', '#FFFFFF'): ").strip() or 'white'

    # Generate QR code with custom colors
    qr = qrcode.QRCode(
        version=1,
        box_size=10,
        border=5
    )
    qr.add_data(data)
    qr.make(fill_color=fill_color, back_color=back_color)

    # Save the image
    filename = input("Enter filename to save (e.g., 'custom_qr.png'): ").strip() or "custom_qr.png"
    qr.save(filename)

    print(f"✅ QR code generated and saved as '{filename}'")

if __name__ == "__main__":
    generate_custom_qr()
Enter fullscreen mode Exit fullscreen mode

This script does three things better than the basic version:

  1. Interactive Input: It prompts the user for the data to encode, making it reusable for any URL or text.
  2. Color Customization: Users can specify hex codes or color names for the fill and background, turning generic black squares into branded assets.
  3. Dynamic Filenames: The user decides the output filename, avoiding accidental overwrites.

Try running this and entering a URL like https://github.com with a blue fill color (#0000FF) and white background. You’ll get a vibrant, branded QR code ready for your next project.

Why This Matters for Your Projects

QR codes aren’t just for fun—they’re practical tools for developers. You can use this generator to:

  • Create contactless menus for restaurants by encoding URLs to menu pages.
  • Build event check-in systems where attendees scan a code to register.
  • Generate unique login tokens for authentication flows.
  • Add quick links to printed documentation or physical products.

Because this script runs locally, it’s secure and fast. You don’t need to rely on third-party APIs that might throttle requests or expose your data. Plus, you can integrate this logic into larger applications, like a web dashboard that generates QR codes for user profiles or a CLI tool for DevOps pipelines.

Next Steps: Take It Further

Now that you have a working generator, here’s how to push it even further:

  • Add Error Handling: Wrap the input and save logic in try-except blocks to catch invalid filenames or encoding errors.
  • Support Multiple Formats: Use Pillow to save the image as PNG, JPEG, or even PDF.
  • Create a Web Interface: Wrap this script in a Flask or FastAPI app so users can generate QR codes via a browser.
  • Batch Generation: Loop through a list of URLs to generate hundreds of QR codes in one run.

The beauty of Python is that these extensions are just a few lines of code away. You’ve already built the foundation; now you’re free to expand it.

Your Turn to Build

You don’t need a degree in computer science or a team of engineers to create powerful tools. With just a few lines of Python, you’ve built a QR code generator that’s ready to use today. Whether you’re automating a workflow, enhancing a product, or just exploring a new skill, this script is a solid starting point.

Try it now: Run the interactive script, generate a QR code for your favorite website, and scan it with your phone. Then, tweak the colors to match your brand. Once you’ve done that, share your creation on Dev.to or Twitter and tag me—I’d love to see what you build.

The best part? You can do this in under 10 minutes. So go ahead, open your terminal, and let’s make something scannable.


If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!

Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.

Top comments (0)