QR Code Generator in Python.
About the project: This will allows you to convert text or a URL into a scannable QR code image.
This program will ask you for the data you want to encode (like a website address or a message), and then it will generate and save a QR code image file for you.
How to use this program:
Run the Python script.
When you run it, you will be prompted to enter the data you want to encode and a filename for the output image.
The program will then generate the QR code and save it in the same directory where your script is located.
To use this program, you will need to install the qrcode library. You can do this by running the following command in your terminal or command prompt:
pip install qrcode[pil] The [pil] part ensures that the necessary Pillow library (for image handling) is also installed.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# qr_code_generator.py
import qrcode
import os
def generate_qr_code(data, filename="qrcode.png"):
"""
Generates a QR code from the given data and saves it as an image file.
Args:
data (str): The text or URL to encode in the QR code.
filename (str): The name of the output image file (e.g., "my_qr_code.png").
Defaults to "qrcode.png".
Returns:
bool: True if the QR code was generated successfully, False otherwise.
"""
try:
# Create QR code instance
qr = qrcode.QRCode(
version=1, # Controls the size of the QR Code (1 to 40)
error_correction=qrcode.constants.ERROR_CORRECT_L, # Error correction level
box_size=10, # Size of each box (pixel) in the QR code
border=4, # Size of the border around the QR code
)
# Add data to the QR code
qr.add_data(data)
qr.make(fit=True) # Ensure the entire data fits into the QR code
# Create an image from the QR code instance
img = qr.make_image(fill_color="black", back_color="white")
# Ensure filename has a .png extension
if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
filename += ".png"
# Save the image file
img.save(filename)
print(f"\nSuccessfully generated QR code and saved as '{filename}'")
return True
except Exception as e:
print(f"Error generating QR code: {e}")
return False
def main():
"""
Main function to run the QR Code Generator.
"""
print("--- Python QR Code Generator ---")
print("This tool converts text or URLs into QR code images.")
while True:
data_to_encode = input("\nEnter the text or URL to encode (or 'q' to quit): ").strip()
if data_to_encode.lower() == 'q':
print("Exiting QR Code Generator. Goodbye!")
break
if not data_to_encode:
print("Input cannot be empty. Please enter some data.")
continue
output_filename = input("Enter the desired filename for the QR code image (e.g., my_website.png): ").strip()
if not output_filename:
output_filename = "qrcode_output.png" # Default if user doesn't provide one
generate_qr_code(data_to_encode, output_filename)
# Optional: Ask if they want to open the file (platform-dependent)
# if os.path.exists(output_filename):
# open_file = input("Do you want to open the generated QR code? (yes/no): ").strip().lower()
# if open_file == 'yes':
# try:
# os.startfile(output_filename) # For Windows
# except AttributeError:
# os.system(f"open {output_filename}") # For macOS
# except Exception as e:
# print(f"Could not open file automatically: {e}")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()