Pycharm中配置Pyinstaller工具 and 多文件打包

发布时间 2023-05-25 15:47:43作者: 写BUG的猪

一、Pycharm中配置Pyinstaller

首先,要下载个pyinstaller库,用pip install installer等待完成即可

(顺带记录下pip 配置国内镜像的方法:
国内源:

在 c:\users\你的用户名 目录下新建pip文件夹
在新建的pip目录下新建pip.ini (新建txt,把后缀改成ini)
用记事本打开写入

[global]
timeout=40
index-url=http://mirrors.aliyun.com/pypi/simple/
extra-index-url=
        https://pypi.tuna.tsinghua.edu.cn/simple/
        http://pypi.douban.com/simple/
        http://pypi.mirrors.ustc.edu.cn/simple/
[install]
trusted-host=
        pypi.tuna.tsinghua.edu.cn
        mirrors.aliyun.com
        pypi.douban.com
        pypi.mirrors.ustc.edu.cn

然后,添加环境变量:
此电脑->属性->设置->高级系统设置->环境变量->系统变量->path->新建
%HOME%\pip\pip.ini
在CMD中测试:
pip config list
image
)

二、Pycharm中添加Pyinstaller外部工具

文件——设置——外部工具——添加

程序:找到pyinstaller.exe的位置(我的pip安装后是在Python安装文件件下的Scripts文件夹中)
实参:--noconsole --onefile $FileName$
工作目录:$FileDir$

在需要打包的.py文件上右键—Extennal Tools-Pyinstaller

命令窗口出现:19629 INFO: Building EXE from EXE-00.toc completed successfully.

表示打包成功,在代码存放目录中的dist文件夹中就能找到.exe文件了。

多文件打包

如果程序中有些资源文件,比如图标、图片等,直接pyinstaller,并不会把这些一起打包进去。

这样的话,就只能用pyinstaller生成.spec文件,然后修改.spec文件,再通过spec文件来打包。同样,为了方便,我还是通过pycharm来配置两个工具,一个使用pyinstaller生成spec文件,一个通过spec文件打包。

配置pyinstaller_spec工具

文件-设置-外部工具-添加

程序:找到pyinstaller.exe的位置
实参:-F -w $FileNameWithoutExtension$.py (-w 小写)
工作目录:$FileDir$

配置pyinstaller_spec_exe 工具

程序:找到pyinstaller.exe的位置
实参:$FileNameWithoutExtension$.spec
工作目录:$FileDir$

入口程序代码中加入资源文件目录访问代码:

def resource_path(relative_path):

    if getattr(sys,'frozen',False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path,relative_path)


cd = resource_path('')
os.chdir(cd)

生成spec文件,修改资源文件

在入口程序.py文件上右击-Extennal Tools-Pyinstaller_spec,等待生成spec文件

之后打开spec文件
image

在前面加上文件地址变量
在pathex=[],中加入地址变量(地址中的'/' 需要多加个转义符'/')
datas中加入:

[(Setup_Dir + '\\res', 'res')],

'res'是资源文件夹名字

后面exe = EXE()
中的name='程序名称',可替换成.exe文件的名称

如果要替换exe图标,可加上:

icon='xxx.ico'
(注意,新添加这句代码,需要在上一行结尾加上',')

图标只能放在根文件目录中,不能放在res文件夹里。文件格式只能为.ico,否则会报错。

spec文件修改完成后,直接在spec文件上右键-Extennal Tools-Pyinstaller_spec_exe,等待生成结束后,在dist文件中查看。