Python QR Code Generator using pyqrcode in Tkinter

In this Python Tkinter tutorial, we will learn how to create a QR code generator using the pyqrcode module. We’ll build a simple GUI application that allows users to enter text or a URL, generate a QR code, and display or save it instantly. This is a great beginner project to understand QR generation, event handling, and GUI layout in Tkinter.

Let’s get in.

Overview of the QR code

  • A QR code, also known as a Quick Response Code, was invented by a Japanese automotive company in 1994.
  • QR code is a type of Matrix barcode that is a machine-readable optical label that contains information about the item to which it is attached.
  • A QR code (Quick Response Code) consists of black squares arranged in a square grid on a white background, which can be read by an imaging device such as a camera.

Read Create Responsive Layouts with Python Tkinter’s Grid Geometry Manager

QR code Library in Python (pyqrcode)

Python provides a library, pyqrcode, which allows implementing QR codes in Python Tkinter.

  • pyqrcode can be installed using pip or pip3 on the system. Use the following code:
pip install pyqrcode

or

pip3 install pyqrcode
  • Once you have successfully installed the pyqrcode library, use the code below to test it.
import pyqrcode
url = pyqrcode.create('https://pythonguides.com/')
print(url.terminal(quiet_zone=1))
  • If you see the barcode generated in the terminal, then you are good to go.

Source code of QR Code Generator

In the below source code, the code at lines 12, 13 is responsible for generating the QR code.

from tkinter import *
from tkinter import messagebox
import pyqrcode

ws = Tk()
ws.title("PythonGuides")
ws.config(bg='#F25252')

def generate_QR():
    if len(user_input.get())!=0 :
        global qr,img
        qr = pyqrcode.create(user_input.get())
        img = BitmapImage(data = qr.xbm(scale=8))
    else:
        messagebox.showwarning('warning', 'All Fields are Required!')
    try:
        display_code()
    except:
        pass

def display_code():
    img_lbl.config(image = img)
    output.config(text="QR code of " + user_input.get())

lbl = Label(
    ws,
    text="Enter message or URL",
    bg='#F25252'
    )
lbl.pack()

user_input = StringVar()
entry = Entry(
    ws,
    textvariable = user_input
    )
entry.pack(padx=10)

button = Button(
    ws,
    text = "generate_QR",
    width=15,
    command = generate_QR
    )
button.pack(pady=10)

img_lbl = Label(
    ws,
    bg='#F25252')
img_lbl.pack()
output = Label(
    ws,
    text="",
    bg='#F25252'
    )
output.pack()
 
ws.mainloop()

Output of QR code Generator:

In this output, we have provided a URL, and a QR code is generated for that URL. This can be scanned using an imaging device like a camera.

python tkinter QR code

Read: How to Create a Snake Game in Python Tkinter

Python Tkinter QRcode save image

In this section, we will learn how to save the Generated QR code image file in our computer for later use.

  • In the above section, we have learned how to generate QR codes using Python Tkinter. In this section, we will cover how to save the generated QR code in Python Tkinter.
  • The library we are using here is qrcode. Use the following code to install qrcode on your machine.
pip install qrcode[pil]
  • using qrcode.make method in qrcode library, we can generate a QR code.
  • And, using qrcode.save method in qrcode library, we can save the generated QR code to the provided location.

Read Create Layouts with Python Tkinter Frame

Source code of Python Tkinter QRcode save image

In this code, we have created an interface in which the user can type a message or a URL. In the next entry field, the user needs to provide the file name. Once clicked on the generate button is clicked, an image of a QR code will be saved in the same directory.

import qrcode
from tkinter import *
from tkinter import messagebox

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x200')
ws.config(bg='#4a7a8c')


def generate():
    img = qrcode.make(msg.get())
    type(img) 
    img.save(f'{save_name.get()}.png')
    Label(ws, text='File Saved!', fg='green').pack()

frame = Frame(ws, bg='#4a7a8c')
frame.pack(expand=True)

Label(
    frame,
    text='URL',
    font = ('Times', 18),
    bg='#4a7a8c'
    ).grid(row=0, column=0, sticky='w')

msg = Entry(frame)
msg.grid(row=0, column=1)

Label(
    frame,
    text='Save as',
    font = ('Times', 18),
    bg='#4a7a8c',
).grid(row=1, column=0, sticky='w')

save_name = Entry(frame)
save_name.grid(row=1, column=1)

btn = Button(
    ws, 
    text='Generate QR code',
    command=generate
    )
btn.pack()

ws.mainloop()

Output

In this output, the QR image is saved in the same directory where the main file is.

python tkinter qr code save image

Check out Create a Progress Bar in Python Tkinter

Python QR Code Generator with Logo

In this section, we will learn how to generate a QR code with a Logo in the center of it.

  • To generate a QR code with a Logo in Python Tkinter, we have to perform two tasks and then merge them into one.
  • First, we have to prepare the logo using the Pillow library, and then we have to add that logo to the code for generating the QR code.
  • We are using qrcode and Pillow modules to perform the task. These modules can be installed using pip. The below command will install both in one go.
pip install qrcode[pil]

Source code

Here is the source code to create a QR code with a logo in Python Tkinter.

import qrcode
import PIL.Image
from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#f25252')

logo = PIL.Image.open('logo.png')

def generate_qr():
    global logo
    basic = 100
    width_percentage = (basic/float(logo.size[0]))
    height_size = int((float(logo.size[1])*float(width_percentage)))
    logo = logo.resize((basic, height_size), PIL.Image.ANTIALIAS)
    qrc = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)

    qrc.add_data(msg.get())
    qrc.make()
    gen_img = qrc.make_image(
        fill_color='#4a7a8c', 
        bg_color="#fff"
        ).convert('RGBA')

    position = ((gen_img.size[0] - logo.size[0]) // 2, (gen_img.size[1] - logo.size[1]) // 2)

    gen_img.paste(logo, position)
    gen_img.save(save_name.get()+'.png')

    lbl.config(text='File saved with logo')

frame = Frame(ws, bg='#f25252')
frame.pack(expand=True)

Label(frame, text='Enter URL ', bg='#f25252').grid(row=0, column=0)
msg = Entry(frame)
msg.grid(row=0, column=1)

Label(frame, text='File Name', bg='#f25252').grid(row=1, column=0)
save_name = Entry(frame)
save_name.grid(row=1, column=1)

btn = Button(
    frame,
    text='Generate',
    command=generate_qr
)
btn.grid(row=2, columnspan=3, pady=10)

lbl = Label(ws, fg='green', bg='#f25252')
lbl.pack()

ws.mainloop()

Output

In this output, the application accepts a URL and a file name. When the button it generated, a QR code with the logo.

python tkinter qrcode with logo

Python QR Code Reader

In this section, we will learn how to create a QR code Reader in Python Tkinter.

  • Using the OpenCV library in Python, we will use our laptop’s camera to scan the QR code, and the result will be printed on the Python Tkinter window.
  • Other than OpenCV, we also require pyzbar to handle the QR code recognition. Both libraries can be installed using pip.
# pip install pyzbar
# pip install opencv_contrib_python
  • If you are a Ubuntu user, then you also need to install this package on the system
sudo apt-get install zbar-tools

Read Master the Python Tkinter Canvas

Source Code

  • vid = cv2.VideoCapture(0): This code is to start the camera on the laptop.
  • while i<2: the information of the QR code will be captured 2 times in a row,
  • decoded = pyzbar.decode(f): This code is to recognize and record the QR code.
  • The decoded variable will hold multiple information in a list format. Information like data, type, a rectangle property of the image, width, height, etc.
  • To fetch the data, a for loop is run, and the data will be displayed on the label.
from tkinter import *
import cv2
import pyzbar.pyzbar as pyzbar

def scanQR():
   i = 0
   vid = cv2.VideoCapture(0)
   while i<2:
       _,f = vid.read()
       decoded = pyzbar.decode(f)
       for obj in decoded:
           lbl.config(text=f'{obj.data}')
           i += 1
       cv2.imshow('QRCode',f)
       cv2.waitKey(5)
       cv2.destroyAllWindows

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')

Button(
    ws,
    text='Scan QRCode',
    command=scanQR
).pack(pady=10)

lbl = Label(ws, font=('times', 20))
lbl.pack()

ws.mainloop()

Output

In this output, the Python Tkinter window has a Scan QR Code button. When this button is clicked, a camera screen is opened. When showed QR code is shown on the camera, the information of the QR code is displayed on the Tkinter window.

python tkinter QR code reader

In this tutorial, we have learned about Python QR codes. Also, we have created a Python QR code generator using pyqrcode in Tkinter.

You may like the following Python Tkinter articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.