Generating QR Codes in Python

QR Codes in Python can be generated using the qrcode library. Follow the steps below to generate a QR code:

Install the qrcode library

If you haven't already installed the qrcode library, you can install it using pip:

pip install qrcode[pil]

Generate QR Code

Here's a simple example that demonstrates how to generate a QR code for a given text:

import qrcode
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_M, ERROR_CORRECT_Q, ERROR_CORRECT_H

def generate_qr_code(text, filename, version=1, error_correction=ERROR_CORRECT_L, box_size=10, border=4):
    # Create QR code instance
    qr = qrcode.QRCode(
        version=version,
        error_correction=error_correction,
        box_size=box_size,
        border=border,
    )
    qr.add_data(text)
    qr.make(fit=True)

    # Generate QR code image
    img = qr.make_image(fill='black', back_color='white')

    # Save the QR code image
    img.save(filename)

if __name__ == "__main__":
    text_to_encode = "Hello, QR Code Buddy!"
    output_filename = "qrcode.png"
    
    # Available error correction levels:
    # ERROR_CORRECT_L: About 7% or fewer errors can be corrected.
    # ERROR_CORRECT_M: About 15% or fewer errors can be corrected.
    # ERROR_CORRECT_Q: About 25% or fewer errors can be corrected.
    # ERROR_CORRECT_H: About 30% or fewer errors can be corrected.
    error_correction_level = ERROR_CORRECT_L
    
    generate_qr_code(text_to_encode, output_filename, version=2, error_correction=error_correction_level, box_size=14, border=2)
    print(f"QR Code generated and saved as {output_filename}")

Execute the Python script. After running, you should find a qrcode.png file in your current directory containing the generated QR code. You can customize the QR code's version (size), error correction level, box size, and border by passing the desired values to the generate_qr_code function. Adjust the parameters as needed for your specific requirements.