Python .py文件打包成.exe可执行程序,带托盘图标的可执行文件
安装pyinstalle
查看是否安装了pyinstaller
已安装
C:\Users\Administrator>pip show pyinstaller
Name: pyinstaller
Version: 6.12.0
Summary: PyInstaller bundles a Python application and all its dependencies into a single package.
Home-page: https://www.pyinstaller.org/
Author: Hartmut Goebel, Giovanni Bajo, David Vierra, David Cortesi, Martin Zibricky
Author-email:
License: GPLv2-or-later with a special exception which allows to use PyInstaller to build and distribute non-free programs (including commercial ones)
Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages
Requires: altgraph, packaging, pefile, pyinstaller-hooks-contrib, pywin32-ctypes, setuptools
Required-by:
未安装,则会收到类似于Could not find installation information for package 'pyinstaller’的提示信息
安装
打包
pip install pyinstaller
使用pyInstaller生成可执行文件,到需要生成文件的路径下,如果你的应用名为test.py,可执行下列命令:
pyinstaller --onefile test.py
#--onefile选项表示将所有依赖打包进一个单独的可执行文件中。
打包完成后,会在dist目录下生成一个可执行文件
如果不需要托盘图标,就可以用了
托盘图标设置
让程序在右下角显示托盘图标,需要在程序中添加相应的代码。以PyQt5介绍如何设置托盘图标
导入
import sys
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction
from PyQt5.QtGui import QIcon
创建托盘图标
app = QApplication(sys.argv)
icon = QSystemTrayIcon(QIcon('A1.png'), app)
icon.show()
menu = QMenu(app)
exit_action = QAction('Exit', app)
exit_action.triggered.connect(app.quit)
menu.addAction(exit_action)
icon.setContextMenu(menu)
sys.exit(app.exec_())
A1.png是你的托盘图标文件路径。这段代码会创建一个托盘图标,并添加一个退出菜单项。
在PyInstaller打包时添加托盘图标
重新运行pyinstaller A1.spec命令进行打包
常见问题解决方法
打包后的程序无法显示托盘图标
这可能是由于托盘图标文件没有正确打包进去导致的。请确保在spec文件中添加了正确的托盘图标文件路径。
打包后的程序在Windows 7下无法显示托盘图标
这可能是由于Windows 7系统对托盘图标的支持问题导致的。可以尝试使用其他托盘图标库,如pyqt5-trayicon