Below is a simple example of how to generate a QR code using Python with user input (URL) from a Tkinter GUI and display the generated QR code within the same GUI. This example uses the qrcode library for generating QR codes and PIL (Python Imaging Library) to display the QR code image in the Tkinter window.
Prerequisites:
Before running the code, ensure you have the necessary libraries installed. You can install them using pip:
bash
pip install qrcode pillow tkinter
QR Code Generation with Tkinter GUI Code:
python
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import qrcode
from io import BytesIO
# Function to generate the QR code based on the user's input URL
def generate_qr_code():
# Retrieve the URL from the input field
url = url_entry.get().strip()
# Validate the input
if not url:
messagebox.showerror("Error", "Please enter a valid URL")
return
try:
# Generate the QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(url)
qr.make(fit=True)
# Convert the QR code into an image
img = qr.make_image(fill_color="black", back_color="white")
# Create an in-memory bytes stream of the QR code image
bytes_io = BytesIO()
img.save(bytes_io, 'PNG')
bytes_io.seek(0)
# Display the QR code in the GUI
img_for_tk = ImageTk.PhotoImage(img)
qr_code_label.config(image=img_for_tk)
qr_code_label.image = img_for_tk # To prevent garbage collection
# Enable the save button after successful generation
save_button.config(state="normal")
except Exception as e:
messagebox.showerror("Error", f"Failed to generate QR code: {e}")
# Function to save the generated QR code to a file
def save_qr_code():
try:
# Open a file dialog for the user to choose a save location
filepath = filedialog.asksaveasfilename(defaultextension=".png", filetypes=(("PNG Image", "*.png"), ("All Files", "*.*")))
if filepath:
# Save the QR code image to the selected file path
img.save(filepath)
messagebox.showinfo("Success", "QR code saved successfully")
except Exception as e:
messagebox.showerror("Error", f"Failed to save QR code: {e}")
# Create the main window
root = tk.Tk()
root.title("QR Code Generator")
# Input Frame: Contains the URL entry field and the generate button
input_frame = tk.Frame(root)
input_frame.pack(padx=10, pady=10)
# Label and entry field for the URL
tk.Label(input_frame, text="Enter URL:").pack(side=tk.LEFT)
url_entry = tk.Entry(input_frame, width=50)
url_entry.pack(side=tk.LEFT, padx=5)
# Button to trigger QR code generation
generate_button = tk.Button(input_frame, text="Generate QR Code", command=generate_qr_code)
generate_button.pack(side=tk.LEFT, padx=5)
# QR Code Display Frame: Shows the generated QR code
qr_code_frame = tk.Frame(root)
qr_code_frame.pack(padx=10, pady=10)
# Label to display the QR code image
qr_code_label = tk.Label(qr_code_frame)
qr_code_label.pack()
# Save Button: Allows saving the QR code as an image file
save_button = tk.Button(root, text="Save QR Code", command=save_qr_code, state="disabled")
save_button.pack(pady=10)
root.mainloop()
How It Works:
User Input: The user enters a URL into the text field in the GUI.
Generate QR Code: Upon clicking the "Generate QR Code" button, the generate_qr_code function is called. This function retrieves the URL, generates a QR code using the qrcode library, and then displays the QR code in the GUI using PIL to convert the image for Tkinter.
Optional Save: After generating the QR code, the "Save QR Code" button becomes active. Clicking this button opens a file dialog where the user can choose a location to save the QR code as a PNG image.
Note:
Ensure you have the necessary permissions to save files when using the "Save QR Code" feature.
This example uses a basic configuration for QR code generation. Depending on your needs, you might want to explore more advanced options provided by the qrcode library, such as customizing the QR code's appearance or adjusting error correction levels.