首页 > 解决方案 > 如何访问 Tkinter exe 文件中的模型权重?

问题描述

我已经生成了一个 Tkinter GUI 并生成了一个复制模型权重的 exe 文件。

weights 文件夹与 myTKcode.py 文件位于同一文件夹中。

我生成我的模型并加载权重如下:

import tensorflow as tf
model = MyModel()
model.load_weights("weights/MyModelWeights")

现在,如果我使用 pyinstaller 生成一个 exe 文件,如下所示:

pyinstaller --onefile --add-data weights;weights myTKcode.py

根据myTKcode.exe文件的大小,我可以说在myTKcode.exe. 但是当我运行该myTKcode.exe文件时,它没有找到 weights 文件夹。但是,如果我将 weights 文件夹复制粘贴到所在的dist文件夹中myTKcode.exe,它就可以工作。

我的问题是如何访问存储在myTKcode.exe?

标签: pythonpyinstallerexe

解决方案


之前已经提出了类似的问题,并在此处找到了解决方案。

简而言之,对于每个文件夹/文件,必须将绝对路径添加到独立的 exe 文件中。

因为我有一个名为 weights 的文件夹;我只需将以下代码添加到我的代码中:

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

然后我加载了如下重量;

import tensorflow as tf
model = MyModel()
#model.load_weights("weights/MyModelWeights")
weightDir = resource_path("weights") # resource_path get the correct path for weights directory.
model.load_weights(weightDir+"/MyModelWeights")

然后简单地运行pyinstaller如下:

pyinstaller --onefile --add-data weights;weights myTKcode.py

推荐阅读