QR Code Generator Python: Complete and Simple Guide
Introduction
In this guide, you will learn how to create a QR Code Generator in Python capable of generating QR codes compatible with various standard formats such as URL, vCard, Text, Email, SMS, WiFi, Bitcoin, and many more. The proposed solution uses a modular and scalable approach, with dedicated classes for each QR code type. By the end of this guide, you will be able to create personalized and maintainable QR codes.
Prerequisites and Environment Setup
Before starting, make sure Python is installed on your system. You can download the latest version from python.org.
Required Tools:
We will use the qrcode
and Pillow
packages to generate and manage QR codes and images. Install them by running the following command in the terminal:
pip install qrcode[pil]
Building the QR Code Generator in Python
The project structure is based on a main QRCodeGenerator
class that receives a payload object. Each QR code type has its own dedicated class that inherits from QRCodePayload
and defines the build_payload()
method to build the QR code content.
Here is the complete code:
import qrcode
from qrcode.constants import ERROR_CORRECT_L
from PIL import Image
from typing import Optional
# Base class for QR code payloads
class QRCodePayload:
def build_payload(self) -> str:
raise NotImplementedError("You must implement the build_payload method!")
# Specific classes for each payload type
class TextPayload(QRCodePayload):
def __init__(self, text: str):
self.text = text
def build_payload(self) -> str:
return self.text
class URLPayload(QRCodePayload):
def __init__(self, url: str):
self.url = url
def build_payload(self) -> str:
return self.url
class VCardPayload(QRCodePayload):
def __init__(self, name: str, org: str, phone: str, email: str):
self.name = name
self.org = org
self.phone = phone
self.email = email
def build_payload(self) -> str:
return f"BEGIN:VCARD\nVERSION:3.0\nFN:{self.name}\nORG:{self.org}\nTEL:{self.phone}\nEMAIL:{self.email}\nEND:VCARD"
class EmailPayload(QRCodePayload):
def __init__(self, email: str):
self.email = email
def build_payload(self) -> str:
return f"mailto:{self.email}"
class SMSPayload(QRCodePayload):
def __init__(self, phone_number: str, message: str):
self.phone_number = phone_number
self.message = message
def build_payload(self) -> str:
return f"sms:{self.phone_number}?body={self.message}"
class WiFiPayload(QRCodePayload):
def __init__(self, ssid: str, password: str, encryption: Optional[str] = "WPA"):
self.ssid = ssid
self.password = password
self.encryption = encryption
def build_payload(self) -> str:
return f"WIFI:S:{self.ssid};T:{self.encryption};P:{self.password};;"
class BitcoinPayload(QRCodePayload):
def __init__(self, address: str):
self.address = address
def build_payload(self) -> str:
return f"bitcoin:{self.address}"
# Main class for generating QR codes
class QRCodeGenerator:
def __init__(self, payload: QRCodePayload):
self.payload = payload
def generate_qr_code(self) -> Image:
"""Generates a QR code image using the specified payload."""
qr = qrcode.QRCode(
version=1,
error_correction=ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(self.payload.build_payload())
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
return img
Usage Examples
1. QR code with simple text
payload = TextPayload("Welcome to DevAccelerate!")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("text.png")
2. QR code for a URL
payload = URLPayload("https://www.devaccelerate.com")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("url.png")
3. QR code for a vCard
payload = VCardPayload("Mario Rossi", "Azienda SRL", "+39123456789", "mario.rossi@email.com")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("vcard.png")
4. QR code for Email
payload = EmailPayload("info@devaccelerate.com")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("email.png")
5. QR code for SMS
payload = SMSPayload("1234567890", "Test message")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("sms.png")
6. QR code for WiFi
payload = WiFiPayload("MyWiFi", "password1234", "WPA")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("wifi.png")
7. QR code for Bitcoin
payload = BitcoinPayload("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")
generator = QRCodeGenerator(payload)
img = generator.generate_qr_code()
img.show() # Display the QR code on the screen
# Or, if you want to save it as an image:
img.save("bitcoin.png")
Conclusion
In this guide, we created a QR Code Generator in Python using a modular and scalable structure. Each QR code format is handled by a dedicated class, making the code easy to extend and maintain. Adding new formats is simple: just create a new class inheriting from QRCodePayload
and implement the build_payload()
method.
In addition to displaying the QR code, you can also save it as an image using the save()
method.
If you want to add more features or further customize the project, you’re on the right track!