在 PyInstaller 可执行文件中使用条形码库生成条形码时出错

问题描述 投票:0回答:1

我有一个 Python 应用程序,它使用

barcode
库生成条形码并将其保存为 PNG 图像。从 Python 解释器运行时,该应用程序运行得很好,但当我使用 PyInstaller 创建可执行文件并尝试运行它时,我遇到了错误。

我遇到的错误如下:

File "tkinter/__init__.py", line 1948, in __call__
File "Bachmaier.py", line 668, in save_selection
File "Barcode_generator.py", line 13, in generate_barcodes
  barcode_image = code128.render(writer_options={"font_size": 1, "text_distance": 1})
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "barcode/codex.py", line 255, in render
File "barcode/base.py", line 100, in render
File "barcode/writer.py", line 269, in render
File "barcode/writer.py", line 440, in _paint_text
File "PIL/ImageFont.py", line 791, in truetype
File "PIL/ImageFont.py", line 788, in freetype
File "PIL/ImageFont.py", line 226, in __init__
OSError: cannot open resource

这是发生错误的相关代码片段:

import os
from barcode import Code128
from barcode.writer import ImageWriter

def generate_barcodes(stl_names, path):
    barcodes = []  # To store the barcode image paths
    
    for name in stl_names:
        barcode_name = f"{name}"
        code128 = Code128(barcode_name, writer=ImageWriter())

        # Generate the barcode as a PIL image
        barcode_image = code128.render(writer_options={"font_size": 1, "text_distance": 1})

        # Save the barcode image as a PNG file
        barcode_file_path = os.path.join(path, f"{barcode_name}.png")
        barcode_image.save(barcode_file_path, "PNG")

        barcodes.append(barcode_file_path)
    return barcodes

该错误似乎与访问资源有关,但我没有在代码中明确使用任何字体。仅当我运行 PyInstaller 生成的可执行文件时才会出现此问题;直接在 Python 解释器中运行脚本可以正常工作。

我尝试在 PyInstaller 中包含

--add-data
标志以确保资源被打包,但问题仍然存在。可能是什么原因导致此错误以及如何解决它?在 PyInstaller 可执行文件中使用
barcode
库时,我需要考虑什么具体事项吗?

任何有关解决此问题的见解或指导将不胜感激。预先感谢您的帮助!

python pyinstaller barcode
1个回答
0
投票

barcode.writer
来自
python-barcode
模块。您的系统中没有安装该软件,因此会出现错误。

所以,做

pip install python-barcode
,你就可以开始了。

© www.soinside.com 2019 - 2024. All rights reserved.