QR Code Generator Using Python

PythonPythonBeginner
Practice Now

Introduction

This project will guide you through the process of creating a QR Code generator using Python. You will learn how to create a project file, import the required libraries, define the QR Code generation function, define the QR Code saving function, create the main window and elements for the QR Code generator interface, and execute the main function.

👀 Preview

Alt text

ðŸŽŊ Tasks

In this project, you will learn:

  • How to create a QR Code generator using Python
  • How to import libraries such as qrcode, tkinter, and PIL
  • How to define functions for generating and saving QR Codes
  • How to create a user interface for generating and saving QR Codes

🏆 Achievements

After completing this project, you will be able to:

  • Use the qrcode library to generate QR Codes
  • Use the tkinter library to create a graphical user interface
  • Save generated QR Codes to files
  • Display generated QR Codes on a canvas

Create the project files

To begin, create a new file named qr_code_generator.py and open it in your preferred code editor.

cd ~/project
touch qr_code_generator.py
âœĻ Check Solution and Practice

Import the required libraries

In the qr_code_generator.py file, import the following libraries at the beginning of your code:

import qrcode
import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import ImageTk, Image
import os

Install the required libraries using the following command:

pip3 install qrcode pillow
âœĻ Check Solution and Practice

Define the QR Code generation function

Add the following code to define a function named generate_qr, which takes in a text parameter and generates a QR Code image:

def generate_qr(text):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    qr.add_data(text)
    qr.make(fit=True)

    img = qr.make_image(fill='black', back_color='white')
    filename = 'qr_code.png'
    img.save(filename)
    return filename

Above, we use the qrcode library to generate a QR Code image. The generate_qr function takes in a text parameter, which is the text or URL that the QR Code will contain. The function then creates a QR Code object with the specified version, error correction level, box size, and border. The text is then added to the QR Code object, and the QR Code image is generated and saved to a file named qr_code.png. Finally, the function returns the filename of the generated QR Code image.

âœĻ Check Solution and Practice

Define the QR Code saving function

Next, add the following code to define a function named save_qr, which allows the user to save the generated QR Code:

def save_qr(filename):
    filepath = filedialog.asksaveasfilename(defaultextension='.png', filetypes=[('PNG Images', '*.png')])

    if filepath:
        os.rename(filename, filepath)
        messagebox.showinfo('QR Code Saved!')

The function takes in a filename parameter, which is the filename of the generated QR Code image. The function then opens a file dialog box, which allows the user to select a location and filename to save the QR Code image. If the user selects a location and filename, the function renames the generated QR Code image to the selected filename and displays a message box to inform the user that the QR Code has been saved.

âœĻ Check Solution and Practice

Create the main window and elements

Now, add the following code to define a function named create_window, which creates the main window, labels, entry field, canvas, and buttons needed for the QR Code generator interface:

def create_window():
    window = tk.Tk()
    window.title('QR Code Generator')

    label = tk.Label(window, text='Enter the text/URL:')
    label.pack()

    ent = tk.Entry(window)
    ent.pack()

    canvas = tk.Canvas(window, width=200, height=200)
    canvas.pack()

    def generate_and_display():
        text = ent.get()
        filename = generate_qr(text)
        photo = ImageTk.PhotoImage(Image.open(filename))
        canvas.create_image(100, 100, image=photo)
        button2 = tk.Button(window, text='Save QR Code', command=lambda: save_qr(filename))
        button2.pack()
        window.mainloop()

    button = tk.Button(window, text='Generate QR Code', command=generate_and_display)
    button.pack()

    window.mainloop()

We use the tkinter library to create the main window, labels, entry field, canvas, and buttons. The create_window function creates the main window and adds a label and entry field for the user to enter the text or URL that the QR Code will contain. The function also creates a canvas, which will be used to display the generated QR Code image. The function then defines a nested function named generate_and_display, which gets the text from the entry field, generates a QR Code image, and displays the QR Code image on the canvas. The function also creates a button that allows the user to save the generated QR Code image. Finally, the function creates a button that calls the generate_and_display function when clicked.

âœĻ Check Solution and Practice

Execute the main function

Finally, add the following code to execute the create_window function when the file is run:

if __name__ == '__main__':
    create_window()
    generate_qr('Hello World!')

The if __name__ == '__main__' block ensures that the create_window function is only executed when the file is run, and not when it is imported as a module. The block also calls the generate_qr function to generate a QR Code image with the text "Hello World!".

python qr_code_generator.py
Alt text
âœĻ Check Solution and Practice

Summary

You have successfully created a QR Code generator using Python. By following this step-by-step project, you've learned how to create a project file, import the necessary libraries, define functions for QR Code generation and saving, create a user interface with Tkinter, and run the project to generate and display QR Codes.

Other Python Tutorials you may like