【问题标题】:Bundle data for pyinstaller error (--onefile)pyinstaller 错误的捆绑数据(--onefile)
【发布时间】:2019-11-02 01:25:26
【问题描述】:

我想为我的 .exe 包含一个图像。我正在按照here 列出的指示进行操作。它说构建在终端中成功完成。当我运行 .exe 时,它​​标志着程序中的一个致命错误。

任何想法表示赞赏。

我的目录看起来像

/Box Tracking
--/res
----amazon_box.jpg
--main.py
--gui.py

来自gui.py的相关代码:

import tkinter as tk
import main
import traceback
import time
import random
# use these libs since base tkinter can only open gif and other obscure formats
# must install Pillow rather than PIL
from PIL import ImageTk, Image
from jokes import jokes
import sys, os # these will allow me to bundle the image in the distro

def resource_path(relative_path):
    '''
    See notes
    :param relative_path: path I will use | string | 'res/amazon-box.jpg'
    :return: string | path
    '''
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

root = tk.Tk()  # create GUI instance
root.geometry("1000x1000") # make GUI big so that users can see it
root.title('Box Tracking') # name GUI

# add a background so users can see it
bg_image = Image.open(resource_path('res/amazon-box.jpg'))
tk_bg_image = ImageTk.PhotoImage(bg_image)
bg = tk.Label(root,image=tk_bg_image)
bg.place(x=0,y=0,relwidth=1,relheight=1)

我用来构建 .exe 的片段: pyinstaller --onefile --windowed --add-data res/amazon-box.jpg;. --name "Box Tracking 3.1.5" gui.py

【问题讨论】:

    标签: python pyinstaller


    【解决方案1】:

    可能有更好的方法,但我是这样做的:

    \res\ 目录中,我有amazon_box.py 和一个空的__init__.py

    您可以使用以下小脚本将图像转换为 base64:

    import base64
    with open("amazon_box.jpg", "rb") as image:
        b = base64.b64encode(image.read())
    with open("amazon_box.py", "w") as write_file:
        write_file.write("def photo(): return (" + str(b) + ")"
    

    amazon_box.py 中会有(由上面的脚本自动创建):

    def photo(): return (image_as_base64)
    

    之后图像可以在主脚本中使用PhotoImage(data = ):

    import tkinter as tk
    from res import amazon_box
    
    root = tk.Tk()  # create GUI instance
    
    root.geometry("1000x1000") # make GUI big so that users can see it
    root.title('Box Tracking') # name GUI
    
    # add a background so users can see it
    tk_bg_image = tk.PhotoImage(data = amazon_box.photo())
    bg = tk.Label(root,image=tk_bg_image)
    bg.place(x=0,y=0,relwidth=1,relheight=1)
    

    显然我没有用你的图片测试过,但这是我过去将图片打包到一个文件中的方式,你可以在一个 .py 文件中拥有多个图片,所以它实际上可以是一个漂亮的干净的最终结果。

    编辑:

    由于此时它只是 PyInstaller 的另一个模块,所以我的构建命令是标准的:pyinstaller.exe --windowed --onefile "path\to\main\py\file"

    我通常只是从命令提示符运行 PyInstaller。

    【讨论】:

    • @ChristinaZhou 其实我很高兴我回顾了这个,我发现,如果编码正确,tempfile 是不需要的,tk.PhotoImage 可以直接加载大多数 base64 编码的图像。
    猜你喜欢
    • 2011-12-02
    • 2013-11-09
    • 2012-12-06
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多