Python script that generates a QR code from user-provided text or a URL using the
qrcode library:
import qrcode
def generate_qr_code(data, filename):
# Create a QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add the data to the QR code
qr.add_data(data)
qr.make(fit=True)
# Generate the QR code image
img = qr.make_image(fill_color="black", back_color="white")
# Save the QR code image to a file
img.save(filename)
print(f"QR code saved as '{filename}'")
if __name__ == "__main__":
print("QR Code Generator")
data = input("Enter the text or URL to encode: ")
filename = input("Enter the filename (e.g., qrcode.png): ")
# Generate the QR code
generate_qr_code(data, filename)
Here's how the script works:
1. The
qrcode library is imported to generate QR codes.
2. The
generate_qr_code function takes two arguments:
data (the text or URL to encode) and
filename (the name of the file to save the QR code image).
3. Inside the function, a
QRCode instance is created with some configuration options, such as version, error correction level, box size, and border width.
4. The
add_data method is called to add the provided data to the QR code.
5. The
make method is called to generate the QR code image.
6. The
make_image method is used to create a PIL image object from the QR code, specifying the fill color (black) and background color (white).
7. The
save method is called on the image object to save the QR code image to the specified filename.
8. In the
if __name__ == "__main__": block, the script prompts the user to enter the text or URL to encode and the filename for the QR code image.
9. The
generate_qr_code function is called with the user-provided data and filename.
To run the script, save it to a file (e.g.,
qr_code_generator.py) and execute it using the Python interpreter. You'll be prompted to enter the text or URL to encode and the filename for the QR code image. After providing the necessary input, the script will generate the QR code image and save it to the specified filename.
Note that you need to have the
qrcode library installed. You can install it using pip:
pip install qrcode
Feel free to modify the script according to your needs, such as adding error handling, customizing the QR code appearance, or integrating it with a graphical user interface (GUI) framework like Tkinter or PyQt.