pyqt5 是写 python 图形化界面的,写完之后我们可以转化为 windows exe 文件运行
git pyqt 我的贪吃蛇(本示例用这个练习)
git clone https://github.com/wchpeng/pyqt5_test.git
cd pyqt5_test/我的贪吃蛇
打开 snake.py ,把里面的图片路径改成绝对路径(在你电脑上项目地址的图片绝对路径),如:
def restart_action(self):
restart_action = QAction(QIcon('D:\\my_projects\\git项目\\pyqt5_test\\我的贪吃蛇\\restart.jpg'), '&重新开始', self)
restart_action.setShortcut('Ctrl+R')
restart_action.triggered.connect(self.init_board)
return restart_action
def degree_of_difficulty_action(self):
degree = QAction(QIcon('D:\\my_projects\\git项目\\pyqt5_test\\我的贪吃蛇\\setting.jpg'), '&设置速度', self)
degree.setShortcut('Ctrl+Alt+S')
degree.triggered.connect(self.init_setting)
return degree
def pause_action(self):
pause = QAction(QIcon('D:\\my_projects\\git项目\\pyqt5_test\\我的贪吃蛇\\stop.jpg'), '&暂停', self)
pause.setShortcut('Ctrl+Alt+T')
pause.triggered.connect(self.board_paused)
return pause
新建虚拟环境并安装必要的库
mkvirtualenv pyqt --python=python3
pip install PyQt5==5.14
pip install cx-Freeze==6.1
生成 setup.py 文件
运行:cxfreeze-quickstart
(pyqt) D:\my_projects\git项目\pyqt5_test\我的贪吃蛇>cxfreeze-quickstart
Project name: snake
Version [1.0]: 1.0
Description: game
Python file to make executable from: snake.py
Executable file name [snake]: snake
(C)onsole application, (G)UI application, or (S)ervice [C]: G
Save setup script to [setup.py]:
Overwrite setup.py [n]? y
Setup script written to setup.py; run it as:
python setup.py build
Run this now [n]?
最后生成了 setup.py 文件
转化为 exe
python setup.py build
这时会生成 build 文件夹
点击进入找到 snake.exe 点击即可
this application failed … no Qt platform plugin could be initialized
# 这句话字面意思是没找到 Qt plugin platform 的路径
# 但是在 build 里的 PyQt5 下面是有 Qt 的,网上找了解决方法
# 参见 https://blog.csdn.net/ouening/article/details/81093697
# https://github.com/pyqt/python-qt5/issues/2
# 需要在 snake.py 前面加上
import os
qt_plugin_platform = os.path.join(os.path.dirname(os.path.abspath(PyQt5.__file__)), 'Qt', 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = qt_plugin_platform
# 重新 build 即可
使用 cxfreeze snake.py --target-dir ./ --base-name=Win32GUI 是会报错的