欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Python制作二维码生成软件

程序员文章站 2022-05-28 22:21:44
...

使用Python制作二维码生成软件

需求背景:
在制造业工厂为了满足产品的追溯性要求,我们经常需要给零件做标记,内容包括:产品的料号,工单号,序号,原材料提供商等

传统的做法是制作固定格式的标签,使用手工标记。

传统的做法的缺点:字迹因人而异不易辨认,信息录入靠手工易出错浪费人力

使用本程序后可打印二维码标签,使用二维码扫码枪录入信息

软件基本功能:
使用本程序能生成并打印二维码标签,标签中嵌入tab键能够自动换行

软件需求:
win10 win8 win7 64位操作系统
python 3.6 以上
第三方库 win32print,win32ui,qrcode

硬件需求:

  标签打印机
  1.热敏便宜但是标签只能保存一年
  2.推荐全树脂碳带打印机
# -*- coding: utf-8 -*- 
import sys
import qrcode
import os
import tkinter.ttk
from tkinter import *
import datetime
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from PIL import ImageWin
import win32print         
import win32ui
from tkinter.messagebox import *


def changeline(file_name,draw,im1):
        str=file_name.encode('GB2312').decode('latin-1')
        total_width=0
        duanluo = ""
        for char in str:   
            width=draw.textsize(char)[0]
            total_width+=width
            if total_width>0.65*im1.size[0]:
                total_width= 0
                duanluo += "\n"
            duanluo += char
        return duanluo.encode('latin-1')



def qrcreate(content,file_name): #生成二维码
   
    #path=os.getcwd()+"\picture"      
    if not os.path.exists("picture"):
          os.makedirs("picture")
          
    qr = qrcode.QRCode(
        version=4,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=2,
        border=25
    )

   
    qr.add_data(content)
    qr.make(fit=True)
    img = qr.make_image()
    
   
    img_file = os.getcwd()+"\picture\%s.png"%file_name
    #fontcn = ImageFont.truetype("C:\\WINDOWS\\Fonts\\Arial.TTF", 13, encoding="utf-8")  #从win10中调用字体但不支持中文
    fontcn = ImageFont.truetype("simhei.ttf", 13, encoding="utf-8")
    img.save(img_file)  #保存二维码在picture文件夹中
    im1=Image.open(img_file)
    draw = ImageDraw.Draw(im1)
   
    
    position=(im1.size[0]-90-draw.textsize(changeline(file_name,draw,im1))[0]/2)
   
    
    draw.text((position,130),changeline(file_name,draw,im1).decode('GB2312'),000,font=fontcn)
    im1.save(img_file)



def printqrcode(content,file_name):  #打印函数
   

    HORZRES = 8
    VERTRES = 10
  
    LOGPIXELSX = 88
    LOGPIXELSY = 90
 
    PHYSICALWIDTH = 110
    PHYSICALHEIGHT = 111
  
    PHYSICALOFFSETX = 112
    PHYSICALOFFSETY = 113

    printer_name = win32print.GetDefaultPrinter ()
   
    file_name = os.getcwd()+"\picture\%s.png"%file_name


    hDC = win32ui.CreateDC ()
    hDC.CreatePrinterDC (printer_name)
    printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
    printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
    printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)

    bmp = Image.open (file_name)
    if bmp.size[0] > bmp.size[1]:
      bmp = bmp.rotate (0)

    ratios = [1.0 * printable_area[0] / bmp.size[0], 0.9 * printable_area[1] / bmp.size[1]]
    scale = min (ratios)


    hDC.StartDoc (file_name)
    hDC.StartPage ()

    dib = ImageWin.Dib (bmp)
    scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
    x1 = int ((printer_size[0] - scaled_width)/2)
    y1 = int ((printer_size[1] - scaled_height))
    x2 = x1 + scaled_width
    y2 = y1 + scaled_height
    dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))

    hDC.EndPage ()
    hDC.EndDoc ()
    hDC.DeleteDC ()



if __name__ =="__main__":
      
      
      root=Tk() #创建运用程序窗口
      root.resizable(0,0)
      root.title("送料信息打印")
      width = 400
      height = 320
      screenwidth = root.winfo_screenwidth()
      screenheight = root.winfo_screenheight()
      alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
      root.geometry(alignstr)
      one = Label(root, text="Powered by Will  \n"+"2019-"+str(datetime.datetime.now().year), width=30, height=2, font=("Arial", 10))   #软件使用年随本机日期变动
      one.pack(side=BOTTOM)
      
      f1=LabelFrame(root,text="二维码QRcode",height=190,width=190,labelanchor="n")
      f1.pack(anchor="e",padx=10,pady=2)    #使用pack布局

      

      def loadpicture(pic):
          global photo         
          
          photo = PhotoImage(file=pic)  #图片
          for widget in f1.winfo_children():
                 widget.destroy()
          theLabel = Label(f1,
                 
                 justify=LEFT,
                 image=photo,
                 compound=CENTER,
                 
                 fg="white"
                 )
          theLabel.pack()
          root.update()
      

      def printcode():
             machine=comboCNC.get()
             
             cast=comboCAST.get()
             castlot=entry_CASTlot.get()
             mo=entry_MO.get()
             if len(mo)!=9:
                     showwarning('警告', "工单长度为9")
                     os._exit()
             mos=entry_MOS.get()
             pn=entry_PN.get()
             if len(pn)!=8:
                     showwarning('警告', "料号长度为8")
                     os._exit()
      
             text=machine+chr(9)+mo+chr(9)+mos+chr(9)+cast+chr(9)+castlot+chr(9)+chr(9)+pn   #二维码内容二维码中嵌入tab键chr(9),便于后续应用
           
             file=machine+mo+mos+cast+castlot+pn #文件名
             listbox.insert(0,"正在打印:"+file)
            
             print(file)
             pic = os.getcwd()+"\picture\%s.png"%file #文件名
             qrcreate(text,file)      #根据二维码内容生成二维码  
             loadpicture(pic)         #调用图片
             printqrcode(text,file)   #调用打印函数
            

      var_M=["M001","M002","M003","M004"]
      
      var_CAST=["A供应商","B供应商","C供应商"]
      
      var_CASTlot=tkinter.StringVar()
      var_MO=tkinter.StringVar()
      var_MOS=tkinter.StringVar()
      var_PN=tkinter.StringVar()

     
      
      
      comboCNC=tkinter.ttk.Combobox(root,value=tuple(var_M))
      comboCNC.place(x=100,y=10,width=100,height=20)
 
      comboCAST=tkinter.ttk.Combobox(root,value=tuple(var_CAST))
      comboCAST.place(x=100,y=70,width=100,height=20)   
       
      label_CNC=tkinter.Label(root,text="机器CNC:",justify=tkinter.RIGHT)
      label_CNC.place(x=0,y=10,width=100,height=20)
   
      label_CAST=tkinter.Label(root,text="铸件供应商:",justify=tkinter.RIGHT)
      label_CAST.place(x=0,y=70,width=100,height=20)
      label_CASTlot=tkinter.Label(root,text="铸造批次:",justify=tkinter.RIGHT)
      label_CASTlot.place(x=0,y=100,width=100,height=20)
      
      label_MO=tkinter.Label(root,text="工单号:",justify=tkinter.RIGHT)
      label_MO.place(x=0,y=130,width=100,height=20)
      label_MOS=tkinter.Label(root,text="工单号模号:",justify=tkinter.RIGHT)
      label_MOS.place(x=0,y=160,width=100,height=20)
      label_PN=tkinter.Label(root,text="料号:",justify=tkinter.RIGHT)
      label_PN.place(x=0,y=190,width=100,height=20)
      
     
      entry_CASTlot=tkinter.Entry(root,textvariable=var_CASTlot)
      entry_CASTlot.place(x=100,y=100,width=100,height=20)
      entry_MO=tkinter.Entry(root,textvariable=var_MO)
      entry_MO.place(x=100,y=130,width=100,height=20)
      entry_MOS=tkinter.Entry(root,textvariable=var_MOS)
      entry_MOS.place(x=100,y=160,width=100,height=20)
      entry_PN=tkinter.Entry(root,textvariable=var_PN)
      entry_PN.place(x=100,y=190,width=100,height=20)
      
      listbox=Listbox(root)
      listbox.place(x=110,y=230,width=280,height=40)
    
     
      
      buttonDelete=Button(root,text="打印",command=printcode)  #按下打印按钮启动打印函数"printcode"
      buttonDelete.place(x=0,y=230,width=100,height=20)
        
      
      root.mainloop()

图片效果

图片: 使用Python制作二维码生成软件

相关标签: tkinter