pyinstaller踩过的坑

pyinstaller踩过的坑

  • 1 基础环境
  • 2 坑,大坑,深坑
  • 3 上边解决了可能是巧合,因为每个人电脑上都有这个字体

1 基础环境

python 2.7.17
pyinstaller 3.5
安装pyinstaller

pip install pyinstaller

2 坑,大坑,深坑

背景:用pygame写了个贪吃蛇游戏,要打包成exe
用到了字体文件 C:\Windows\Fonts\simsun.ttc (宋体)

打包过程中没有报错
打包过程中的警告可以忽略,这个警告: WARNING: Hidden import “pygame._view” not found!

运行exe的时候报NotImplementedError: Can’t perform this operation for unregistered loader type
真的是百思不得其姐,为什么会报这个错????
最终确定,是找不到引用的字体文件,需要指定下,添加如下代码:

def rp(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)

并且每个文件都要使用该函数转换下地址

BASICFONT = pygame.font.Font(rp('C:\Windows\Fonts\simsun.ttc'), 18)
titleFont = pygame.font.Font(rp('C:\Windows\Fonts\simsun.ttc'), 100)
gameOverFont = pygame.font.Font(rp('freesansbold.ttf'), 100)

再次pyinstaller -F xxx.py生成单个exe后,就可以直接运行不会报错了

3 上边解决了可能是巧合,因为每个人电脑上都有这个字体

再来个图片的,其他电脑上就没有了
首先,还是那个函数需要加到代码里

def rp(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)

再者,把src目录下的background.jpg用上方的函数转换下地址,同时打印下地址以观后效

bgimg = rp(os.path.join('src','background.jpg'))
print(bgimg)

三,使用 pyi-makespec -F 2048.py命令生成spec文件,修改文件内容如下:
指定src目录打包到exe中,运行时生成的临时路径也叫src
pyinstaller踩过的坑_第1张图片
指定命令打包:pyinstaller -F 2048.spec
把2048.exe挪到另一个位置,跑一下看看cmd输出
pyinstaller踩过的坑_第2张图片
生成的临时路径也叫src,且能找到我们的图片。
这时候还是不确定,我们换台机器跑下试试
pyinstaller踩过的坑_第3张图片
撒花吧!!!!

你可能感兴趣的:(python)