【问题标题】:File path for pyinstaller bundled images?pyinstaller 捆绑图像的文件路径?
【发布时间】:2017-02-16 22:28:06
【问题描述】:

我正在尝试使用 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)

From this page

这是我对每个图像文件的当前代码:

root.iconbitmap('C:\\Users\\username\\Downloads\\TripApp\\BennySM.ico')
filename = PhotoImage(file = 'C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif')

我知道这些不是最好的文件路径,但我不确定我需要添加什么,所以 python 文件知道在哪里查找。图像与 exe 捆绑在一起,如果我将 exe 添加到数据文件中,它会找到图像并运行。

谢谢!我之前尝试添加 resource_path,但我在顶部的定义部分中缺少文件路径。

再次感谢!

【问题讨论】:

    标签: python pyinstaller


    【解决方案1】:

    问题:如何在 pyinstaller 构建的程序中使用数据文件?

    我们首先假设 python 脚本在作为脚本运行时正在运行,并且脚本中包含以下行:

    filename = PhotoImage(file='C:\\Users\\username\\Downloads\\TripApp\\BgSM.gif')
    

    这一行表明脚本正在从固定目录中检索文件(可能不是最佳实践,但作为示例很好),并将该 .gif 文件转换为 PhotoImage() 对象实例。这将是我们的基线。

    当我们的脚本作为pyinstaller 构建程序运行时,需要完成三件事才能成功使用此文件。

    1.在 pyinstaller 构建期间,将文件移动到已知位置

    这一步是通过将datas 指令添加到“.spec”文件来完成的。有关如何执行此操作的更多信息,请参阅this post。但简而言之,这是需要的:

    datas=[
        ('C:\\Users\\test\\Downloads\\TripApp\\BgSM.gif', 'data'),
        ...
    ],
    

    请注意,元组中有两个元素。第一个元素是我们的.gif 文件的路径,因为它在我们将其打包成pyinstaller 可执行文件之前存在于工作python 脚本中。元组的第二个元素是运行可执行文件时文件所在的目录。

    2。在运行时,找到我们的.gif 文件

    这是问题示例中的函数,重铸以使用:

    1. 示例中的绝对路径,当脚本作为脚本运行时,或者,
    2. 脚本作为 pyinstaller 构建程序运行时在 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 构建程序中工作

    所以现在我们可以在作为脚本运行或作为 pyinstaller 构建程序运行时构建 .gif 文件的路径,我们的基线变为:

    filename = PhotoImage(file=resource_path('BgSM.gif'))
    

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 1970-01-01
      • 2016-07-09
      • 2011-12-02
      • 2014-07-25
      相关资源
      最近更新 更多