如何将.py转换为.exe时添加图像文件?

问题描述 投票:0回答:1

我创建了一个基于Tkinter的应用程序,该应用程序将图像用作按钮的图标。

现在我使用auto-py-to-exe(PyInstaller)将其转换为.exe。

但是输出文件无法运行,因为找不到所需的图像。如何将图像文件与.exe文件合并?

这里是应用代码:

import tkinter as tk
from tkinter import *


root = tk.Tk()
img = PhotoImage(file=r'E:\project\videos\icon\rec.png')
root.tk.call('wm', 'iconphoto', root._w, img)
root.title('Cam Recorder')
cam_icon = PhotoImage(file=r'E:\project\videos\icon\webcam0.png')
com_icon = PhotoImage(file=r'E:\project\videos\icon\webcam1.png')


def change_w():
    if webcam_btn.image == cam_icon:
        webcam_btn.config(image=com_icon)
        webcam_btn.image = com_icon
    else:
        webcam_btn.config(image=cam_icon)
        webcam_btn.image = cam_icon


frame = tk.Frame(root)
frame.pack()

webcam_btn = tk.Button(
    frame,
    image=cam_icon,
    width=70,
    height=80,
    relief=FLAT,
    command=change_w,
    )
webcam_btn.grid(row=0, column=2)
webcam_btn.image = cam_icon
root.mainloop()

这是auto-py-to-exe的屏幕截图:

eg

python tkinter exe pyinstaller
1个回答
-1
投票

您可以尝试使用临时文件,将其二进制文件嵌入到您的代码中作为byte,如下所示:1)使用print(open('path-to-img', 'rb').read())获取二进制。

2)添加

with open('your_temp_path.png', 'wb') as f:
    f.write(b'your_binary_data')

3)在代码末尾使用os.remove('your_temp_path.png')删除临时文件。

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.