闲来无事想自己在pc端实现自定义文本生成二维码功能,因为离线工具怕藏门,在线工具离线时候用不了。在网上找了一些现成代码,做了一些功能优化(默认颜色,取消图标,生成图片显示自适应缩放)
import qrcode
import tkinter as tk
from PIL import Image
def create_code():
global photo
content = Entry_input_url.get('1.0', 'end')
fill_color = Entry_input_fill_color.get()
back_color = Entry_input_back_color.get()
qr = qrcode.QRCode(
version=1, # 二维码的边长
# ERROR_CORRECT_H: 30%的字码可被容错,因为插入了图片,所以增加容错率
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=8,
border=1,
)
qr.make(fit=True)
qr.add_data(content)
img = qr.make_image(fill_color=fill_color, back_color=back_color)
# 保存二维码
img.save("qr.png")
photo = tk.PhotoImage(file="qr.png")
photo_height = photo.height()
xnum = 1
while (photo_height > window.winfo_height()):
photo_height = round(photo_height/(xnum+1))
xnum = xnum+1
photo = photo.subsample(xnum)
Label_img = tk.Label(window, image=photo)
Label_img.place(x=400, y=0)
window.update()
if __name__ == '__main__':
window = tk.Tk()
window.title('二维码生成器')
window.geometry('900x400')
label_url = tk.Label(window, text="输入文本:")
label_url.place(x=50, y=40)
Entry_input_url = tk.Text()
Entry_input_url.place(x=120, y=40, width=200, height=100)
label_fill_color = tk.Label(window, text="填充颜色:")
label_fill_color.place(x=50, y=160)
Entry_input_fill_color = tk.Entry()
Entry_input_fill_color.insert(0, 'black')
Entry_input_fill_color.place(x=120, y=160)
label_fill_color = tk.Label(window, text="背景颜色:")
label_fill_color.place(x=50, y=190)
Entry_input_back_color = tk.Entry()
Entry_input_back_color.insert(0, 'white')
Entry_input_back_color.place(x=120, y=190)
button = tk.Button(window, text='开始生成', command=create_code)
button.place(x=140, y=220)
window.mainloop()