This Python script uses the qrcode
library to convert user-provided text or URLs into a QR code image, which is saved as a PNG file. It offers a simple way to quickly generate and share QR codes directly from your terminal.
Click to view script…
#!/usr/bin/env python3
import qrcode
def generate_qr_code(data, filename="qr_code.png"):
"""
Generates a QR code from the provided data and saves it to a file.
Parameters:
data (str): The text or URL to encode.
filename (str): The name of the file to save the QR code image.
Returns:
str: The filename where the QR code is saved.
"""
# Create a QRCode object with desired settings.
qr = qrcode.QRCode(
version=1, # 1 means 21x21 matrix; increase for more data.
error_correction=qrcode.constants.ERROR_CORRECT_H, # High error correction.
box_size=10, # Size of each box in pixels.
border=4, # Border size in boxes.
)
# Add data to the QR code.
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code instance.
img = qr.make_image(fill_color="black", back_color="white")
img.save(filename)
return filename
def main():
print("=== QR Code Generator ===\n")
data = input("Enter the text or URL you want to encode in the QR code: ").strip()
if not data:
print("No data provided. Exiting.")
return
filename = generate_qr_code(data)
print(f"\nQR code generated and saved as '{filename}'.")
if __name__ == "__main__":
main()