Learn how to easily convert any text into a QR code using Python. This guide walks you through the process step-by-step, using the qrcode library to generate scannable QR codes that can store URLs, messages, or any custom text. Perfect for beginners and developers looking to add QR code functionality to their projects.
TEXT TO QR CODE IN PYTHON
Step 1: Install the Required Library
Think of this step as getting the tool you need.
- Open your terminal (or command prompt) and type:
pip install qrcode[pil]
This installs the qrcode library, which helps create QR codes, and Pillow, which helps handle images.
Step 2: Write the Python Code
Now, let’s write a small Python script to do the magic
import qrcode # Function to turn text into a QR code def text_to_qr(text, filename='qrcode.png'): # Create a QR code qr = qrcode.QRCode( version=1, # QR size (1 is small, higher numbers are bigger) error_correction=qrcode.constants.ERROR_CORRECT_H, # Allows QR code to work even if a bit damaged box_size=10, # Size of each square in the QR code border=4 # Border around the QR code ) qr.add_data(text) # Add your text to the QR code qr.make(fit=True) # Adjust size based on text length # Create and save the QR code image img = qr.make_image(fill_color="black", back_color="white") img.save(filename) print(f"QR code saved as {filename}") # Example: Convert this text into a QR code text = "Hello, this is a QR code generated in Python!" text_to_qr(text)
Step 3: Run the Code
- Save this code in a file, like qr_code_generator.py.
- Open your terminal, go to the folder where the file is saved, and run:
python qr_code_generator.py
3. Boom! You’ll find an image named qrcode.png in the same folder. That’s your QR code!
How It Works (In Simple Terms):
- You give it some text.
- The code converts it into a bunch of black-and-white squares (that’s the QR code).
- You get an image file that anyone can scan with their phone
Bonus: Make It Colorful!
Want a fancy QR code with colors? Just tweak this part:
img = qr.make_image(fill_color="blue", back_color="yellow") img.save("colorful_qr.png")
Now your QR code will be blue and yellow instead of plain black and white!