温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

pyinstaller打包程序exe踩过的坑

发布时间:2020-10-22 20:59:18 来源:脚本之家 阅读:284 作者:peace老师 栏目:开发技术

基础环境

  • 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

pyinstaller打包程序exe踩过的坑

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

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

pyinstaller打包程序exe踩过的坑

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

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

pyinstaller打包程序exe踩过的坑

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI