pyinstaller打包程序exe踩过的坑

Thadea ·
更新时间:2024-09-20
· 782 次阅读

基础环境

python 2.7.17 pyinstaller 3.5

安装pyinstaller

pip install pyinstaller

坑,大坑,深坑

背景:用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后,就可以直接运行不会报错了

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

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

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

src-src

指定命令打包:pyinstaller -F 2048.spec

把2048.exe挪到另一个位置,跑一下看看cmd输出

src路径

生成的临时路径也叫src,且能找到我们的图片。

这时候还是不确定,我们换台机器跑下试试

也是正确的

您可能感兴趣的文章:python pyinstaller打包exe报错的解决方法详解pyinstaller selenium python3 chrome打包问题使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件Pyinstaller 打包exe教程及问题解决使用Pyinstaller转换.py文件为.exe可执行程序过程详解pyinstaller打包单个exe后无法执行错误的解决方法解决pyinstaller打包发布后的exe文件打开控制台闪退的问题pyinstaller还原python代码过程图解



需要 登录 后方可回复, 如果你还没有账号请 注册新账号