1、安装pyinstaller
pip install pyinstaller
打开cmd,输入pyinstaller --version
若能正常显示pyinstaller版本号即表示安装成功。
2、将py文件转换为exe文件
在xxx.py文件所在目录下,按住shift+右击,选择“在此处打开powershell窗口”,输入
pyinstaller -F hello.py
3、pyinstaller生成.exe文件跳过命令行窗口,不弹出命令窗口
pyinstaller打包.py文件后,双击打开生成的.exe文件,会先跳出命令行窗口,回车之后才开始运行。可以通过增加选项的方式跳过命令行,直接打开exe:
-D, --onedir 创建一个目录,包含exe文件和依赖文件(默认)
-F, --onefile 创建一个exe文件,所有依赖文件都打包进这个exe文件
-c, --console, --nowindowed 有控制台,无界面 (默认)
-w, --windowed, --noconsole 有窗口,无控制台
只需将:pyinstaller -F xxx.py
改为: pyinstaller -w -F xxx.py
pyinstaller -F -w hello.py
4、给exe程序添加图标
需要准备一张.ico后缀名的图片(可自行网上下载或者用png图片在线生成ico图标)
然后使用命令(注意路径)
pyinstaller -F -w --icon=.\Src\tools.ico ThinkHome_Tools.py
- 最后需要注意的是,需要移动exe程序的位置,才可以显示图片
异常报错
发现执行后出现报错:
PS E:\01_政企产品线\04_个人成长\02_python> pyinstaller -F .\hello.py
65 INFO: PyInstaller: 3.5
65 INFO: Python: 3.8.0
66 INFO: Platform: Windows-10-10.0.17763-SP0
83 INFO: wrote E:\01_政企产品线\04_个人成长\02_python\hello.spec
85 INFO: UPX is not available.
96 INFO: Extending PYTHONPATH with paths
['E:\\01_政企产品线\\04_个人成长\\02_python', 'E:\\01_政企产品线\\04_个人成长\\02_python']
96 INFO: checking Analysis
97 INFO: Building Analysis because Analysis-00.toc is non existent
97 INFO: Initializing module dependency graph...
99 INFO: Initializing module graph hooks...
103 INFO: Analyzing base_library.zip ...
3304 INFO: running Analysis Analysis-00.toc
3308 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
required by c:\users\39558\appdata\local\programs\python\python38\python.exe
4061 INFO: Caching module hooks...
4105 INFO: Analyzing E:\01_政企产品线\04_个人成长\02_python\hello.py
4108 INFO: Loading module hooks...
4108 INFO: Loading module hook "hook-encodings.py"...
4174 INFO: Loading module hook "hook-pydoc.py"...
4176 INFO: Loading module hook "hook-xml.py"...
4352 INFO: Looking for ctypes DLLs
4354 INFO: Analyzing run-time hooks ...
4356 INFO: Including run-time hook 'pyi_rth_multiprocessing.py'
4363 INFO: Looking for dynamic libraries
6194 INFO: Looking for eggs
6194 INFO: Using Python library c:\users\39558\appdata\local\programs\python\python38\python38.dll
6194 INFO: Found binding redirects:
[]
6227 INFO: Warnings written to E:\01_政企产品线\04_个人成长\02_python\build\hello\warn-hello.txt
6264 INFO: Graph cross-reference written to E:\01_政企产品线\04_个人成长\02_python\build\hello\xref-hello.html
6273 INFO: checking PYZ
6273 INFO: Building PYZ because PYZ-00.toc is non existent
6273 INFO: Building PYZ (ZlibArchive) E:\01_政企产品线\04_个人成长\02_python\build\hello\PYZ-00.pyz
Traceb