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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) tkinter(("`Tkinter`")) -.-> tkinter/ThemedWidgetsGroup(["`Themed Widgets`"]) tkinter(("`Tkinter`")) -.-> tkinter/ClassicWidgetsGroup(["`Classic Widgets`"]) tkinter(("`Tkinter`")) -.-> tkinter/ImagesGroup(["`Images`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") tkinter/ThemedWidgetsGroup -.-> tkinter/button("`Clickable Button`") tkinter/ThemedWidgetsGroup -.-> tkinter/entry("`Text Field`") tkinter/ThemedWidgetsGroup -.-> tkinter/label("`Text Label`") tkinter/ClassicWidgetsGroup -.-> tkinter/canvas("`Drawing Area`") tkinter/ImagesGroup -.-> tkinter/photoimage("`Raster Image`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/FileHandlingGroup -.-> python/file_opening_closing("`Opening and Closing Files`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-298900{{"`QR Code Generator Using Python`"}} tkinter/button -.-> lab-298900{{"`QR Code Generator Using Python`"}} tkinter/entry -.-> lab-298900{{"`QR Code Generator Using Python`"}} tkinter/label -.-> lab-298900{{"`QR Code Generator Using Python`"}} tkinter/canvas -.-> lab-298900{{"`QR Code Generator Using Python`"}} tkinter/photoimage -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/booleans -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/conditional_statements -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/lists -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/tuples -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/function_definition -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/lambda_functions -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/importing_modules -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/using_packages -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/standard_libraries -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/file_opening_closing -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/os_system -.-> lab-298900{{"`QR Code Generator Using Python`"}} python/build_in_functions -.-> lab-298900{{"`QR Code Generator Using Python`"}} end

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

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

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.

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.

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.

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

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