轉化 pyqt 爲 windows exe 文件
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
轉化成 exe 文件
-
生成 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 是會報錯的