pyinstaller打包程序exe踩过的坑

yipeiwu_com5年前Python基础

基础环境

  • 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设计】。

相关文章

python使用matplotlib绘制热图

python使用matplotlib绘制热图

python常用的绘图库就是matplotlib,今天在给公司绘图时,偶然间发现matplotlib可以绘制热图,并且十分简洁,拿出来跟大家分享一下。(由于涉及到公司数据问题,这里采用随...

Python黑帽编程 3.4 跨越VLAN详解

Python黑帽编程 3.4 跨越VLAN详解

VLAN(Virtual Local Area Network),是基于以太网交互技术构建的虚拟网络,既可以将同一物理网络划分成多个VALN,也可以跨越物理网络障碍,将不同子网中的用户划...

在python中只选取列表中某一纵列的方法

如下所示: >>> a=random.randint(1,6,(5,3)) >>> a array([[5, 3, 1], [5, 5,...

Python random模块(获取随机数)常用方法和使用例子

random.randomrandom.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 random.uniformrandom.uniform(...

对python函数签名的方法详解

函数签名对象,表示调用函数的方式,即定义了函数的输入和输出。 在Python中,可以使用标准库inspect的一些方法或类,来操作或创建函数签名。 获取函数签名及参数 使用标准库的sig...