生成条形码PyCharm 环境下可正常运行,利用Pyinstaller打包后系统报错OSError: cannot open resource,如何解决?(语言-python)

#报错信息
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter_init_.py", line 1921, in call
File "a1.py", line 29, in cz_cli
File "barcode\base.py", line 65, in save
File "barcode\codex.py", line 257, in render
File "barcode\base.py", line 105, in render
File "barcode\writer.py", line 227, in render
File "barcode\writer.py", line 372, in _paint_text
File "PIL\ImageFont.py", line 878, in truetype
File "PIL\ImageFont.py", line 875, in freetype
File "PIL\ImageFont.py", line 226, in init
OSError: cannot open resource
#报错代码
from pystrich.code128 import Code128Encoder
import openpyxl
import barcode
import os
from barcode.writer import ImageWriter
from openpyxl.drawing.image import Image
import tkinter
import winreg
#获取系统桌面路径
def get_desktop():
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
return winreg.QueryValueEx(key, "Desktop")[0]
Desktop_path=str(get_desktop())
wbb=openpyxl.Workbook()
wbb.create_sheet(title='打印',index=0)
wbb.save(Desktop_path+'/打印表.xlsx') # 保存
barcode.writer.FONT=os.path.join('AdobeGothicStd-Bold.otf')
def cz_cli():
#生成条形码保存为图片
bm='123456789'
tm = barcode.get_barcode_class('code128')
tmgs=tm(bm, writer=ImageWriter())
#条形码间距,文本与条码间距,文本尺寸,分辨率
tmgs.save(Desktop_path+'/code128',{'module_width':0.3,'text_distance':0.5,'font_size':20,'dpi':200})

#加载图片到EXCEL
wb = openpyxl.load_workbook(Desktop_path+'/打印表.xlsx')
ws = wb['打印']
img=Image(Desktop_path+'/code128.png')
ws.add_image(img,'B1')
wb.save(Desktop_path+'/打印表.xlsx')

dl_win = tkinter.Tk()
dl_win.title('登录窗口')
dl_win.geometry('%dx%d+%d+%d' % (300, 210, 100, 100))
cz_b = tkinter.Button(dl_win, text='生成', width=8, command=cz_cli)
cz_b.place(x=60, y=40)
dl_win.mainloop()

我估计问题出在barcode.writer.FONT=os.path.join('AdobeGothicStd-Bold.otf')这一行,因为报错提示信息是关于字体的,而你使用的这个字体并不是系统默认自带的字体,所以要不换一个字体试试,要不就把这个字体文件也一起打包到exe里边去,不然的话即使在你电脑上能运行,换个电脑依然会出问题

1、请排查所使用字体本机是否有安装,以及字体文件路径是否正确,注意大小写拼写及特殊字符
2、如果是字体问题的话,修改代码选为默认字体尝试是否正常,或者将字体文件放在代码里面,使用相对路径或者绝对路径 'test.ttf'调用

如:

  • 默认字体:
font = ImageFont.load_default()

draw = ImageDraw.Draw(pil_img)
draw.text(( 20, 32), "text_string", (255,0,0), font=font)
  • 使用字体:arial.ttf (注意大小写拼写)

下载链接:https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf

from PIL import Image, ImageDraw, ImageFont

im = Image.open("mak.png")
font_type = ImageFont.truetype("arial.ttf", 18)
draw = ImageDraw.Draw(im)
draw.text(xy=(120, 120), text= "download font you want to use", fill=(255,69,0), font=font_type)
im.show()

首先查看代码2、 4 、6行的路径拼接是否有问题,可以控制台输出一下,如果有问题可以先把中文名称换成英文的测试下,其次查看使用的字体是否安装成功
可以参考如下链接
https://www.cnblogs.com/wangyi0419/p/12956275.html
https://yunyaniu.blog.csdn.net/article/details/89814106