我的代码中有一个非常奇怪的错误.我正在写一个Python程序,可以生成条形码并将它们组合成图像.当我执行. Exec文件时,它会给我一个错误.然而,这很奇怪,因为当我从VS Code中运行它时没有任何问题,代码可以正常工作.但当我将其转换为. excel文件时,它会给我一个错误.

代码如下:

def generate_and_save_image(self, filename, dpi=600):
        # Create new image
        image = Image.new("RGB", (1024, 768), "white")
        draw = ImageDraw.Draw(image)

        # Font
        font_path = "C:/Users/RaulV/Desktop/sbar/ARIAL.ttf"
        large_font = ImageFont.load_default()
        
        print("Font Path:", font_path)
        print("Large Font Loaded:", large_font)

        # Generate and add the origin barcode
        barcode_origin = Code128(self.current_origin, writer=ImageWriter())
        barcode_origin.save("barcode_origin")
        barcode_origin_img = Image.open("barcode_origin.png")
        barcode_origin_img = barcode_origin_img.resize((barcode_origin_img.width, barcode_origin_img.height))
        image.paste(barcode_origin_img, (10, 40))
        
        draw.text((20, 10), "ORIGEN", fill="black", font=large_font)

        # Generate and add the destination barcode
        barcode_destination = Code128(self.current_destination, writer=ImageWriter())
        barcode_destination.save("barcode_destination")
        barcode_destination_img = Image.open("barcode_destination.png")
        barcode_destination_img = barcode_destination_img.resize((barcode_destination_img.width, barcode_destination_img.height)) 
        image.paste(barcode_destination_img, (image.width - barcode_destination_img.width - 10, 40))
        draw.text((image.width - barcode_destination_img.width - 10, 10), "DESTINO", fill="black", font=large_font)
        
        # Generate and add the scanned barcode
        barcode_scanned = Code128(self.codigo_barras, writer=ImageWriter())
        barcode_scanned.save(f"barcode")
        barcode_scanned_img = Image.open(f"barcode.png")
        
        # Calculate the coordinates to place the barcode in the center of the image
        x = (image.width - barcode_scanned_img.width) // 2
        y = (image.height - barcode_scanned_img.height) // 2 + 50
        
        image.paste(barcode_scanned_img, (x, y))

        # Generate and add the quantity barcode in the bottom right corner
        barcode_quantity = Code128(str(self.cantidad), writer=ImageWriter())
        barcode_quantity.save("barcode_quantity")
        barcode_quantity_img = Image.open("barcode_quantity.png")
        barcode_quantity_img = barcode_quantity_img.resize((barcode_quantity_img.width, barcode_quantity_img.height))
        image.paste(barcode_quantity_img, (image.width - barcode_quantity_img.width - 10, image.height - barcode_quantity_img.height - 10))
        
        # Text with the quantity
        draw.text((image.width - barcode_quantity_img.width - 10, image.height - barcode_quantity_img.height - 30), "CANTIDAD", fill="black", font=large_font)

        query = ""
        self.cursor.execute(query, (self.codigo_barras))
        result = self.cursor.fetchone()
        if result:
            article_code, description = result
            draw.text((10, image.height-90), f"REF: {article_code}", fill="black", font=large_font)
            draw.text((10, image.height-30), f"{description}", fill="black", font=large_font) 
                
        query = ""
        self.cursor.execute(query, (self.current_origin))
        result = self.cursor.fetchone()
        if result:
            cantidadAnterior = result[0]
            draw.text((10, image.height-60), f"Unidades en la ubicacion de origen: {cantidadAnterior}", fill="black", font=large_font)  
        
        # Save image
        image.save(filename, dpi=(dpi, dpi))

错误如下:

Font Path: C:/Users/RaulV/Desktop/sbar/ARIAL.ttf
Large Font Loaded: <PIL.ImageFont.FreeTypeFont object at 0x0000022DA8EB6ED0>
Exception in Tkinter callback
Traceback (most recent call last):
  File "tkinter\__init__.py", line 1967, in __call__
  File "combinedApp.py", line 759, in close_selected_boxes
  File "combinedApp.py", line 842, in generate_and_save_image
  File "barcode\base.py", line 64, in save
  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 807, in truetype
  File "PIL\ImageFont.py", line 804, in freetype
  File "PIL\ImageFont.py", line 244, in __init__
OSError: cannot open resource

759号线: self.generate_and_save_image(filename) 842号线: barcode_origin.save("barcode_origin")

我也try 过使用默认字体:large_font = ImageFont.load_default(),但得到同样的错误.

当我使用pyinstaller将.py转换为. Exec时,我try 在Exec中添加字体,但也得到了同样的错误. 这是转换的命令:

pyinstaller --noconfirm --onefile --console --add-data "C:/Users/RaulV/Desktop/Barcodes/arial.ttf;."  "C:/Users/RaulV/Desktop/Barcodes/combinedApp.py"

现在我正在try 使用一个简单的代码,但我得到了同样的错误:

    def generate_barcode(code, filename):
        code128 = barcode.get_barcode_class('code128')
        barcode_instance = code128(code, writer=ImageWriter())
        barcode_instance.save(filename)

    generate_barcode('123456789', 'barcode.png')

推荐答案

我找到了解决方案.

我必须在Code 128初始化之前创建一个Image Writer对象,如下所示:

font_path = 'your_path'
writer = ImageWriter()
writer.font_path = font_path 
writer.format = 'png'
barcode_origin = Code128(self.current_origin, writer=writer)

Python相关问答推荐

在Python中,如何初始化集合列表脚本的输出

如果在第一行之前不存在其他条件,如何获得满足口罩条件的第一行?

取相框中一列的第二位数字

Pandas 群内滚动总和

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

Tkinter -控制调色板的位置

"如果发生特定错误,返回值

是pandas.DataFrame使用方法查询后仍然排序吗?

使用Keras的线性回归参数估计

具有多个选项的计数_匹配

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

try 在树叶 map 上应用覆盖磁贴

Python中的嵌套Ruby哈希

如何在WSL2中更新Python到最新版本(3.12.2)?

在np数组上实现无重叠的二维滑动窗口

使用groupby方法移除公共子字符串

Django RawSQL注释字段

使用BeautifulSoup抓取所有链接

使用Python从rotowire中抓取MLB每日阵容

导入错误:无法导入名称';操作';