我对 Python 和 tkinter 非常陌生,我使用 auto-py-to-exe 将我的 Python 脚本转换为 exe 文件。到目前为止我没有任何问题,但今天我很茫然。我编写了一个创建 QR 码的 python 脚本,其中 tkCalendar-DateEntry 用于日期字段。几天前我能够将脚本转换为 exe,但今天我再次尝试使用完全相同的代码,但我得到了一个巨大的错误。我提出 tkCalendar 的原因是当我注释掉 import 语句时,文件被转换了!
请帮忙!
这是我的代码:
from tkinter import *
from tkinter import ttk
import qrcode
import time
from PIL import Image, ImageTk,ImageWin
from tkcalendar import Calendar,DateEntry
from datetime import date
from datetime import datetime
from tkinter import messagebox
import os
import win32print,win32ui,win32gui,win32con,pywintypes
import sqlite3
import getpass
import win32api
from pathlib import Path
strForDB = os.getcwd() + '\DBINFO.txt'
print(strForDB)
openDBFile = open(strForDB, 'r')
currentDirForDB = openDBFile.read()
def printQRCode():
startPrint.config(state='disabled')
if len(txt_GS1.get())!=0 and len(txt_GS1.get())==7 and str(txt_GS1.get()).isdigit() and len(strainDropDown.get())!=0 and len(str(packedOnCalendar.get_date()))!=0 and len(txt_Qty.get())!=0 and len(sizeDropDown.get())!=0 and len(printQty.get())!=0 and len(printerSelect.get())!=0:
qtyVal=int(txt_Qty.get())
printedLabels=int(printQty.get())
if qtyVal<0 or printedLabels<0:
messagebox.showerror("Error","Negative values are not allowed. No labels printed!")
return
else:
if len(strain2DropDown.get())!=0:
qrString=str(txt_GS1.get())+"|S1:"+str(strainDropDown.get())+"|S2:"+str(strain2DropDown.get())+"|PkDt:"+str(packedOnCalendar.get_date())+"|Q:" + str(txt_Qty.get()) + "|S:"+str(sizeDropDown.get())
else:
qrString=str(txt_GS1.get())+"|S1:"+str(strainDropDown.get())+"|S2:N/A"+str(strain2DropDown.get())+"|PkDt:"+str(packedOnCalendar.get_date())+"|Q:" + str(txt_Qty.get()) + "|S:"+str(sizeDropDown.get())
#qrString="Lot-AV"+str(yearVal)+str(strainDropDown.get())+str(txt_Lot.get())+str(txt_Suffix.get())+"|Date:"+str(packedOnCalendar.get_date())+" |Qty:" + str(txt_Qty.get()) + "|Size:"+str(sizeDropDown.get())
i=0
for i in range(printedLabels):
if os.path.exists('QRCode.bmp'):
os.remove('QRCode.bmp')
time.sleep(1)
img = qrcode.make(qrString+'|'+getpass.getuser()+"|PDT:"+str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
newsize = (100,100)
img = img.resize(newsize)
img.save('QRCode.bmp')
filename=os.getcwd()+'\QRCode.bmp'
printer_name=printerSelect.get()
#####################################################################
#####################################################################
# printable area
horzrez = 8
vertres = 10
# DPI
logpixelsx = 203
logpixelsy = 203
# Total area
physicalwidth = 10
physicalheight = 10
# physical offset x/y--> left/top margin
physicaloffsetx = 600
physicaloffsety = 500
dc = win32ui.CreateDC()
dc.CreatePrinterDC(printer_name)
bmp = Image.open(filename)
# newsize = (10,10)
# bmp=bmp.resize(newsize)
# print(bmp)
printable_area = dc.GetDeviceCaps(horzrez), dc.GetDeviceCaps(vertres)
printer_size = dc.GetDeviceCaps(physicalwidth), dc.GetDeviceCaps(physicalheight)
printer_margins = dc.GetDeviceCaps(physicaloffsetx), dc.GetDeviceCaps(physicaloffsety)
ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
scale = min(ratios)
dc.StartDoc(filename)
dc.StartPage()
dib = ImageWin.Dib(bmp)
scaled_width, scaled_height = [int(scale * i) for i in bmp.size]
x1 = int((printer_size[0] - scaled_width) / 400)
y1 = int((printer_size[1] - scaled_height) / 400)
x2 = x1 + scaled_width
y2 = y1 + scaled_height
dib.draw(dc.GetHandleOutput(), (x1, y1, x2, y2))
dc.EndPage()
dc.EndDoc()
dc.DeleteDC()
txt_GS1.delete(0,END)
strainDropDown.set("")
strain2DropDown.config(state='readonly')
strain2DropDown.set("")
strain2DropDown.config(state='disable')
packedOnCalendar.set_date(datetime.now())
txt_Qty.delete(0,END)
sizeDropDown.set("")
printQty.delete(0,END)
printerSelect.set("")
startPrint.config(state='normal')
else:
messagebox.showerror("Error!","Invalid entries made, no labels printed!")
startPrint.config(state='normal')
return
dbPath = currentDirForDB
con = sqlite3.connect(dbPath)
cur = con.cursor()
allStrains=cur.execute("SELECT Strain FROM AllStrains").fetchall()
allSizes=cur.execute("SELECT SizeString FROM AllSizes").fetchall()
allStrainsList=[]
allSizesList=[]
for item in range(len(allStrains)):
allStrainsList.append(allStrains[item])
for item in range(len(allSizes)):
allSizesList.append(allSizes[item])
root =Tk()
root.title("QR Code Generator/Printer")
root.geometry('700x300+300+80')
lb_GS1=Label(root,text="GS1: ").grid(row=1,column=0)
lb_Strain=Label(root,text="Strain").grid(row=0,column=2,padx=10)
lb_Strain2 = Label(root,text="Strain II").grid(row=0,column=3,padx=10)
lb_YearInstruction=Label(root,text="(7 Digits)").grid(row=2,column=1)
txt_GS1 = Entry(root,width=10)
txt_GS1.grid(row=1,column=1)
strainDropDown = ttk.Combobox(root,values=allStrainsList,state='readonly',width=5)
strainDropDown.grid(row=1,column=2)
strain2DropDown = ttk.Combobox(root,state='disable',width=10)
strain2DropDown.grid(row=1,column=3)
yearList=[]
monthList=[]
dayList=[]
lb_YearPacked = Label(root,text="Packed on Date").grid(row=0,column=6)
packedOnCalendar=DateEntry(root,state='readonly')
packedOnCalendar.grid(row=1,column=6)
lb_Qty = Label(root,text="Quantity").grid(row=0,column=8)
txt_Qty = Entry(root,width=5)
txt_Qty.grid(row=1,column=8)
lb_QtyInstructions=Label(root,text="Integers\nOnly").grid(row=2,column=8)
lb_Size=Label(root,text="Size").grid(row=0,column=10)
sizeDropDown=ttk.Combobox(root,width=8,state='readonly',values=allSizes)
sizeDropDown.grid(row=1,column=10)
printQty= Entry(root,width=6)
printQty.grid(row=1,column=11)
lb_PrintQty=Label(root,text="Number of\nLabels")
lb_PrintQty.grid(row=0,column=11)
lb_Printer=Label(root,text="Select Printer")
lb_Printer.grid(row=0,column=12)
print(str(packedOnCalendar.get_date()))
textToEnter=datetime.now()
printers =win32print.EnumPrinters(7)
allPrintList=[]
finalPrintList=[]
for item in printers:
if item not in allPrintList:
allPrintList.append(item)
finalPrintList.append(item[2])
printerSelect=ttk.Combobox(root,state='readonly',values=finalPrintList)
printerSelect.grid(row=1,column=12)
startPrint=Button(root,text="Start Printing",command=printQRCode)
startPrint.grid(row=7,column=6,pady=10,padx=10,sticky=E)
print(type(win32print.GetDefaultPrinter()))
root.wm_iconbitmap(os.getcwd()+'\QRCodeIcon.ico')
def fillStrain2(eventObject):
if len(strainDropDown.get())!=0:
files=[]
for file in os.listdir(os.getcwd()):
if os.path.isfile(os.path.join(os.getcwd(),file)):
files.append(file)
if str(strainDropDown.get())+'.txt' in files:
strain2DropDown.config(state='readonly')
with open(str(strainDropDown.get())+'.txt','r') as allStrains:
secondaryStrain = [line.strip() for line in allStrains]
strain2DropDown.config(values=secondaryStrain)
strain2DropDown.current(0)
else:
strain2DropDown.set("")
strain2DropDown.config(state="disable")
else:
strain2DropDown.set("")
strain2DropDown.config(state="disable")
pass
strainDropDown.bind("<<ComboboxSelected>>",fillStrain2)
#################################################################################################
root.mainloop()
这是错误:
Running auto-py-to-exe v2.6.6
Building in the current instances temporary directory at C:\Users\USERNAME\AppData\Local\Temp\tmpjltqk5rg
To get a new temporary directory, restart this application
Recursion Limit is set to 5000
Executing: pyinstaller -y -w -i "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/QRCodeIcon.ico" --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/BLE.txt";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/COP.txt";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/DBINFO.txt";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/GEL.txt";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/QRCode.bmp";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/QRCodeCreatePrint2.py";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/QRCodeIcon.ico";"." --add-data "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/TestdatabaseBudToFG.db";"." "C:/Users/USERNAME/Desktop/Newest Versions of Apps/QRCodeCreatePrint2/QRCodeCreatePrint2.py"
1426181 INFO: PyInstaller: 4.0.dev0+8196c57ab
1426181 INFO: Python: 3.7.3 (conda)
1426182 INFO: Platform: Windows-10-10.0.17763-SP0
1426195 INFO: wrote C:\Users\USERNAME\AppData\Local\Temp\tmpjltqk5rg\QRCodeCreatePrint2.spec
1426199 INFO: UPX is not available.
1426204 INFO: Extending PYTHONPATH with paths
['C:\\Users\\USERNAME\\Desktop\\Newest Versions of Apps\\QRCodeCreatePrint2',
'C:\\Users\\USERNAME\\AppData\\Local\\Temp\\tmpjltqk5rg']
1426204 INFO: checking Analysis
1426205 INFO: Building Analysis because Analysis-02.toc is non existent
1426205 INFO: Reusing cached module dependency graph...
1426276 INFO: Caching module graph hooks...
1427088 INFO: running Analysis Analysis-02.toc
1427091 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\USERNAME\appdata\local\continuum\miniconda3\python.exe
1428280 INFO: Analyzing C:\Users\USERNAME\Desktop\Newest Versions of Apps\QRCodeCreatePrint2\QRCodeCreatePrint2.py
1428870 INFO: Processing pre-safe import module hook six.moves
1430474 INFO: Processing pre-find module path hook distutils
1430477 INFO: distutils: retargeting to non-venv dir 'c:\\users\\USERNAME\\appdata\\local\\continuum\\miniconda3\\lib'
1432867 INFO: Processing pre-find module path hook site
1432870 INFO: site: retargeting to fake-dir 'c:\\users\\USERNAME\\appdata\\local\\continuum\\miniconda3\\lib\\site-packages\\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\\PyInstaller\\fake-modules'
1434818 INFO: Processing pre-safe import module hook setuptools.extern.six.moves
1443890 INFO: Processing pre-safe import module hook urllib3.packages.six.moves
1459336 INFO: Processing module hooks...
1459337 INFO: Loading module hook "hook-babel.py"...
1459546 INFO: Loading module hook "hook-certifi.py"...
1459551 INFO: Loading module hook "hook-cryptography.py"...
1460706 INFO: Loading module hook "hook-distutils.py"...
1460710 INFO: Loading module hook "hook-encodings.py"...
1460951 INFO: Loading module hook "hook-gevent.py"...
1461637 WARNING: Unable to find package for requirement greenlet from package gevent.
1461637 INFO: Packages required by gevent:
['cffi']
1464333 INFO: Loading module hook "hook-lib2to3.py"...
1464348 INFO: Loading module hook "hook-lxml.etree.py"...
1464355 INFO: Loading module hook "hook-nltk.py"...
An error occurred, traceback follows:
Traceback (most recent call last):
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\auto_py_to_exe\__main__.py", line 269, in convert
pyi.run() # Execute PyInstaller
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\__main__.py", line 112, in run
run_build(pyi_config, spec_file, **vars(args))
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\__main__.py", line 63, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\build_main.py", line 732, in main
build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\build_main.py", line 679, in build
exec(code, spec_namespace)
File "C:\Users\USERNAME\AppData\Local\Temp\tmpjltqk5rg\QRCodeCreatePrint2.spec", line 17, in <module>
noarchive=False)
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\build_main.py", line 242, in __init__
self.__postinit__()
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\datastruct.py", line 158, in __postinit__
self.assemble()
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\build_main.py", line 420, in assemble
self.graph.process_post_graph_hooks()
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\depend\analysis.py", line 309, in process_post_graph_hooks
module_hook.post_graph()
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\depend\imphook.py", line 415, in post_graph
self._load_hook_module()
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\depend\imphook.py", line 396, in _load_hook_module
attr_value = sanitizer_func(attr_value)
File "c:\users\USERNAME\appdata\local\continuum\miniconda3\lib\site-packages\pyinstaller-4.0.dev0+8196c57ab-py3.7.egg\PyInstaller\building\utils.py", line 525, in format_binaries_and_datas
raise SystemExit(msg)
SystemExit: Unable to find "C:\Users\USERNAME\nltk_data" when adding binary and data files.
Project output will not be moved to output folder
Complete.