pyinstaller 打包图片的问题

我正在试着用pyinstaller打包我的pygame程序,以下是我的pygame程序代码:

import sys
import pygame 
from pygame.locals import *

"""初始化游戏的静态设置"""
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("外星人入侵")
space = pygame.image.load('star123.png')
while True:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            sys.exit()
        screen.blit(space, (0,0))
        pygame.display.update()

在代码中,会使用到star123.png这个图片资源。那么我打包程序之后,就必须要把这个图片放到和exe一样的目录。那我要怎么做才能把exe和这个图片资源结合起来,并且在结合之后,代码怎么导用新增图片的路径?

coder Derek
Jason990420
最佳答案

SPEC 文件告诉 PyInstaller 如何处理脚本。
它对脚本名称和您提供给 pyinstaller 命令的大多数选项进行编码。SPEC 文件实际上是可执行的Python 代码。 PyInstaller 通过执行 SPEC 文件的内容来构建应用程序。

在四种情况下,修改规格文件很有用:

  • 当您要将数据文件与应用程序捆绑在一起时。
  • 当您想要包括运行时库(.dll或.so文件)时, PyInstaller不会从任何其他来源得知。
  • 当您要将Python运行时选项添加到可执行文件时。
  • 当您要创建具有合并通用模块的多程序包时。

使用规范文件

4年前 评论
Coolest (楼主) 4年前
讨论数量: 2
Jason990420

SPEC 文件告诉 PyInstaller 如何处理脚本。
它对脚本名称和您提供给 pyinstaller 命令的大多数选项进行编码。SPEC 文件实际上是可执行的Python 代码。 PyInstaller 通过执行 SPEC 文件的内容来构建应用程序。

在四种情况下,修改规格文件很有用:

  • 当您要将数据文件与应用程序捆绑在一起时。
  • 当您想要包括运行时库(.dll或.so文件)时, PyInstaller不会从任何其他来源得知。
  • 当您要将Python运行时选项添加到可执行文件时。
  • 当您要创建具有合并通用模块的多程序包时。

使用规范文件

4年前 评论
Coolest (楼主) 4年前
Jason990420

随手写的, 没试过喔...

import os
import sys

def resource_path(relative_path):

    if getattr(sys, 'frozen') and hasattr(sys, '_MEIPASS'):
        print('running in a PyInstaller bundle')
        base_path = sys._MEIPASS
    else:
        print('running in a normal Python process')
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!