Python Software Development - QR Code Generation

How to Build a QR Code Generator with Tkinter in Python

QR codes are everywhere, from business cards to websites, and creating one is easier than you think. With Python and Tkinter, you can build a simple QR code generator that not only creates QR codes but also lets users download them. In this blog, we'll walk through the process of building a QR code generator with a GUI using Tkinter and qrcode, alongside an image display and download functionality.



What You’ll Need

To get started, you'll need to install the required Python libraries:

  1. Tkinter: This comes pre-installed with Python, so you don't need to install it separately.
  2. qrcode: A Python library for generating QR codes.
  3. Pillow: A Python Imaging Library fork, which we'll use to display images in Tkinter.

You can install the necessary libraries with the following command:

pip install qrcode[pil] pillow



Building the QR Code Generator

Here is the code for our QR code generator using Tkinter:

import tkinter as tk
from tkinter import messagebox
import qrcode
from PIL import ImageTk

def generate_qr():
    text = entry.get()

    if not text:
        messagebox.showerror("Generate Error", "Please Enter Valid Text/ URL and click generate")
        return

    qr = qrcode.QRCode(version=2)
    qr.add_data(text)
    qr.make(fit=True)

    global img, imgtk
    img = qr.make_image()

    imgtk = ImageTk.PhotoImage(img)
    display_qr.config(image=imgtk)
    display_qr.image = imgtk
    headline.config(text="Image Generated Successfully")

def download_qr():
    global img
    if not img:
        messagebox.showwarning("Download Warning", "Please click generate first and then click download")
        return
    try:
        img.save("qrcode.jpg", "JPEG")
        messagebox.showinfo("Download Success", "File has been saved as qrcode.jpg")
    except Exception as e:
        messagebox.showerror("Download Error", "An error occurred while downloading QR code")

root = tk.Tk()
root.title("QR Code Generator")
root.geometry("400x500")

headline = tk.Label(root, text="Enter Text and Click Generate Button", font=("Arial", 12))
headline.pack(pady=12)

entry = tk.Entry(root, width=40, font=("Arial", 12))
entry.pack(pady=12)

frame = tk.Frame(root)
frame.pack(pady=12)
generate_button = tk.Button(frame, text="Generate", font=("Arial", 12), command=generate_qr)
generate_button.pack(side=tk.LEFT, padx=10)
download_button = tk.Button(frame, text="Download", font=("Arial", 12), command=download_qr)
download_button.pack(side=tk.LEFT, padx=10)

display_qr = tk.Label(root)
display_qr.pack(padx=10)

img = None
imgtk = None

root.mainloop()



How the Code Works

Let’s break down the key parts of the code:


Step 1: Importing Libraries

First, we import the necessary libraries:

  • tkinter: To create the graphical user interface (GUI).
  • qrcode: To generate the QR codes.
  • Pillow (with ImageTk): To display the generated QR code in the Tkinter window.
import tkinter as tk
from tkinter import messagebox
import qrcode
from PIL import ImageTk


Step 2: Defining the Generate Function

The generate_qr() function handles the core functionality of generating the QR code. Here’s how it works:

  1. It retrieves the user input from the entry widget.
  2. If the input is empty, it shows an error message using messagebox.showerror().
  3. If valid text or URL is provided, it uses the qrcode library to generate a QR code with the qr.make_image() method.
  4. The QR code image is then displayed in the Tkinter window using ImageTk.PhotoImage().
def generate_qr():
    text = entry.get()

    if not text:
        messagebox.showerror("Generate Error", "Please Enter Valid Text/ URL and click generate")
        return

    qr = qrcode.QRCode(version=2)
    qr.add_data(text)
    qr.make(fit=True)

    global img, imgtk
    img = qr.make_image()

    imgtk = ImageTk.PhotoImage(img)
    display_qr.config(image=imgtk)
    display_qr.image = imgtk
    headline.config(text="Image Generated Successfully")


Step 3: Adding the Download Functionality

Once the QR code is generated, the user may want to download the image. The download_qr() function allows them to save the QR code as a JPEG file.

  • It checks if an image has been generated before allowing the user to download it.
  • If an image exists, it saves it as qrcode.jpg in the working directory using img.save().
  • Success or error messages are shown accordingly.
def download_qr():
    global img
    if not img:
        messagebox.showwarning("Download Warning", "Please click generate first and then click download")
        return
    try:
        img.save("qrcode.jpg", "JPEG")
        messagebox.showinfo("Download Success", "File has been saved as qrcode.jpg")
    except Exception as e:
        messagebox.showerror("Download Error", "An error occurred while downloading QR code")


Step 4: Setting Up the GUI

The GUI is designed using Tkinter components:

  1. Label: A label (headline) guides the user to enter text and click the "Generate" button.
  2. Entry: A text entry field where the user can input the text or URL to encode.
  3. Buttons: Two buttons — one for generating the QR code and another for downloading it.
  4. Label for Image: A Label widget (display_qr) to display the generated QR code image.
root = tk.Tk()
root.title("QR Code Generator")
root.geometry("400x500")

headline = tk.Label(root, text="Enter Text and Click Generate Button", font=("Arial", 12))
headline.pack(pady=12)

entry = tk.Entry(root, width=40, font=("Arial", 12))
entry.pack(pady=12)

frame = tk.Frame(root)
frame.pack(pady=12)
generate_button = tk.Button(frame, text="Generate", font=("Arial", 12), command=generate_qr)
generate_button.pack(side=tk.LEFT, padx=10)
download_button = tk.Button(frame, text="Download", font=("Arial", 12), command=download_qr)
download_button.pack(side=tk.LEFT, padx=10)

display_qr = tk.Label(root)
display_qr.pack(padx=10)

img = None
imgtk = None

root.mainloop()



Running the Program

  1. Save this code in a Python file (e.g., qr_code_generator.py).
  2. Run the program, and a window will appear with a text input field, two buttons ("Generate" and "Download"), and an area where the QR code will be displayed.
  3. Enter text or a URL in the input field, click "Generate" to create the QR code, and click "Download" to save the QR code image as qrcode.jpg.


Conclusion

This simple QR code generator provides an easy and effective way to create and save QR codes using Python. With Tkinter, we’ve built an interactive GUI that makes it easy for users to input data, generate a QR code, and download it for use. This is a great beginner project to practice working with both Python’s image handling and GUI development.


Post a Comment

0 Comments