-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqrest2.py
More file actions
194 lines (164 loc) · 7.98 KB
/
Copy pathqrest2.py
File metadata and controls
194 lines (164 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers import RoundedModuleDrawer
from qrcode.image.styles.colormasks import RadialGradiantColorMask
from PIL import Image
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
import os
class QRCodeGenerator:
def __init__(self):
self.root = tk.Tk()
self.root.title("Advanced QR Code Generator")
self.root.geometry("500x400")
# Default values
self.data = ""
self.filename = "qrcode.png"
self.fill_color = "black"
self.back_color = "white"
self.size = 10
self.logo_path = ""
self.create_widgets()
def create_widgets(self):
# Main frame
main_frame = tk.Frame(self.root, padx=20, pady=20)
main_frame.pack(expand=True, fill=tk.BOTH)
# Data input
tk.Label(main_frame, text="Data to encode:").grid(row=0, column=0, sticky="w")
self.data_entry = tk.Entry(main_frame, width=40)
self.data_entry.grid(row=0, column=1, pady=5)
# Output file
tk.Label(main_frame, text="Output filename:").grid(row=1, column=0, sticky="w")
self.filename_entry = tk.Entry(main_frame, width=40)
self.filename_entry.insert(0, self.filename)
self.filename_entry.grid(row=1, column=1, pady=5)
# Color options
tk.Label(main_frame, text="QR Color:").grid(row=2, column=0, sticky="w")
self.fill_entry = tk.Entry(main_frame, width=15)
self.fill_entry.insert(0, self.fill_color)
self.fill_entry.grid(row=2, column=1, sticky="w", pady=5)
tk.Label(main_frame, text="Background Color:").grid(row=3, column=0, sticky="w")
self.back_entry = tk.Entry(main_frame, width=15)
self.back_entry.insert(0, self.back_color)
self.back_entry.grid(row=3, column=1, sticky="w", pady=5)
# Size option
tk.Label(main_frame, text="Size (1-40):").grid(row=4, column=0, sticky="w")
self.size_entry = tk.Entry(main_frame, width=5)
self.size_entry.insert(0, str(self.size))
self.size_entry.grid(row=4, column=1, sticky="w", pady=5)
# Logo option
self.logo_var = tk.StringVar()
self.logo_check = tk.Checkbutton(main_frame, text="Add Logo", variable=self.logo_var,
onvalue="yes", offvalue="no", command=self.toggle_logo)
self.logo_check.grid(row=5, column=0, sticky="w", pady=5)
self.logo_button = tk.Button(main_frame, text="Select Logo", state=tk.DISABLED, command=self.select_logo)
self.logo_button.grid(row=5, column=1, sticky="w", pady=5)
# Style options
tk.Label(main_frame, text="QR Style:").grid(row=6, column=0, sticky="w")
self.style_var = tk.StringVar(value="normal")
tk.Radiobutton(main_frame, text="Normal", variable=self.style_var, value="normal").grid(row=6, column=1, sticky="w")
tk.Radiobutton(main_frame, text="Rounded", variable=self.style_var, value="rounded").grid(row=7, column=1, sticky="w")
tk.Radiobutton(main_frame, text="Gradient", variable=self.style_var, value="gradient").grid(row=8, column=1, sticky="w")
# Generate button
generate_btn = tk.Button(main_frame, text="Generate QR Code", command=self.generate_qr)
generate_btn.grid(row=9, column=0, columnspan=2, pady=20)
# Preview label
self.preview_label = tk.Label(main_frame, text="")
self.preview_label.grid(row=10, column=0, columnspan=2)
def toggle_logo(self):
if self.logo_var.get() == "yes":
self.logo_button.config(state=tk.NORMAL)
else:
self.logo_button.config(state=tk.DISABLED)
self.logo_path = ""
def select_logo(self):
self.logo_path = filedialog.askopenfilename(
title="Select Logo Image",
filetypes=[("Image Files", "*.png *.jpg *.jpeg")]
)
if self.logo_path:
messagebox.showinfo("Logo Selected", f"Logo: {os.path.basename(self.logo_path)}")
def generate_qr(self):
try:
# Get input values
self.data = self.data_entry.get()
self.filename = self.filename_entry.get() or "qrcode.png"
self.fill_color = self.fill_entry.get() or "black"
self.back_color = self.back_entry.get() or "white"
self.size = int(self.size_entry.get() or 10)
if not self.data:
messagebox.showerror("Error", "Please enter data to encode")
return
# Create basic QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=self.size,
border=4,
)
qr.add_data(self.data)
qr.make(fit=True)
# Apply selected style
if self.style_var.get() == "rounded":
img = qr.make_image(
image_factory=StyledPilImage,
module_drawer=RoundedModuleDrawer(),
fill_color=self.fill_color,
back_color=self.back_color
)
elif self.style_var.get() == "gradient":
# Convert color names to RGB tuples
def color_to_rgb(color):
rgb = Image.new("RGB", (1, 1), color).getpixel((0, 0))
if isinstance(rgb, int) or rgb is None:
raise ValueError(f"Invalid color value: {color}")
if isinstance(rgb, tuple) and len(rgb) == 4:
rgb = rgb[:3]
return tuple(int(x) for x in rgb)
img = qr.make_image(
image_factory=StyledPilImage,
color_mask=RadialGradiantColorMask(
center_color=color_to_rgb(self.fill_color),
edge_color=color_to_rgb(self.back_color)
)
)
else: # normal
img = qr.make_image(
fill_color=self.fill_color,
back_color=self.back_color
)
# Add logo if selected
if self.logo_var.get() == "yes" and self.logo_path:
self.add_logo_to_qr(img, self.logo_path, self.filename)
else:
img.save(self.filename)
# Show success message
self.preview_label.config(text=f"QR code generated successfully!\nSaved as {self.filename}")
# Ask if user wants to see the QR code
if messagebox.askyesno("Success", "QR code generated successfully! Would you like to view it?"):
Image.open(self.filename).show()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
def add_logo_to_qr(self, qr_img, logo_path, output_filename):
"""Add a logo to the center of the QR code"""
try:
logo = Image.open(logo_path)
# Calculate logo size (20% of QR code size)
base_width = min(qr_img.size[0] // 5, logo.size[0])
wpercent = (base_width / float(logo.size[0]))
hsize = int((float(logo.size[1]) * float(wpercent)))
logo = logo.resize((base_width, hsize), Image.Resampling.LANCZOS)
# Calculate position to center the logo
pos = (
(qr_img.size[0] - logo.size[0]) // 2,
(qr_img.size[1] - logo.size[1]) // 2
)
qr_img.paste(logo, pos)
qr_img.save(output_filename)
except Exception as e:
raise Exception(f"Failed to add logo: {str(e)}")
def run(self):
self.root.mainloop()
if __name__ == "__main__":
app = QRCodeGenerator()
app.run()