我正在尝试使用pyinstaller构建一个文件exe,但我不确定图像的文件路径应该在主python文件中。
在我的主python文件的顶部,我使用了MEIPASS代码:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
这是我对每个图像文件的当前代码:
root.iconbitmap('C:\\Users\\username\\Downloads\\TripApp\\BennySM.ico')
filename = PhotoImage(file = 'C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif')
我知道这些不是最好的文件路径,但我不确定我需要添加什么,所以python文件知道在哪里查看。图像与exe捆绑在一起,如果我将exe添加到数据文件中,它会找到图像并运行。
谢谢!我之前尝试添加resource_path但是我在顶部的define部分中缺少文件路径。
再次感谢!
答案 0 :(得分:1)
问题:如何在pyinstaller构建的程序中使用数据文件?
让我们首先假设python脚本当作脚本运行时当前正在工作,并且脚本中包含以下行:
filename = PhotoImage(file='C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif')
此行表示脚本正在从固定目录中检索文件(可能不是最佳做法,但对于示例很好),并将该.gif
文件转换为PhotoImage()
对象实例。这将是我们的基准。
当我们的脚本作为pyinstaller
构建的程序运行时,需要完成三件事才能成功使用此文件。
<强> 1。在pyinstaller构建期间,将文件移动到已知位置
通过向`.spec'文件添加datas
指令来完成此步骤。有关如何执行此操作的详细信息,请参阅this post。但简而言之,这将是必要的:
datas=[
('C:\\Users\\test\\Downloads\\TripApp\\BgSM.gif', 'data'),
...
],
请注意元组中有两个元素。第一个元素是我们的.gif
文件的路径,因为它在我们将它打包成pyinstaller可执行文件之前存在于工作python脚本中。元组的第二个元素是运行可执行文件时文件所在的目录。
<强> 2。在运行时,找到我们的.gif
文件
以下是问题中示例中的函数,重新使用:
datas
元组中指定的路径。代码:
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS,
# and places our data files in a folder relative to that temp
# folder named as specified in the datas tuple in the spec file
base_path = os.path.join(sys._MEIPASS, 'data')
except Exception:
# sys._MEIPASS is not defined, so use the original path
base_path = 'C:\\Users\\test\\Downloads\\TripApp'
return os.path.join(base_path, relative_path)
第3。重新建立基线以在我们的pyinstaller构建的程序中工作
现在我们可以在作为脚本运行时构建。gif
文件的路径,或者作为pyinstaller构建的程序,我们的基线变为:
filename = PhotoImage(file=resource_path('BgSM.gif'))