1.准备
(1) PyCharm安装QtDesigner、PyUIC、Pyrcc5。可参考:https://blog.csdn.net/weixin_43115411/article/details/125872862
(2) PyCharm直接安装pyqt5。
(3) PyCharm直接安装pyinstaller。
2.pyqt5简单界面设计
(1) 打开”工具“菜单栏,”External Tools”,打开QtDesigner。
(2) 创建Main Window,,为了测试添加了一个按钮(直接从左侧拖动即可)。点击保存,保存为*.ui文件。
(3) 右击*.ui文件,点击PyUIC,将ui文件转为*.py文件,方便python调用。最终会生成一个与*.ui同名的*.py文件。
(4) 放弃使用qtMainWindows.py文件里的主函数,注释掉:
(4) 为了使UI代码和事件代码分离,需要新建一个*.py文件,文件名:myWindows.py。复制如下代码到myWindows.py。
from qtMainWindows import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow
class MainWindow(QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.setupUi(self)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
解释:
<1> from qtMainWindows import Ui_MainWindow: qtMainWindows表示通过*.ui文件生成的文件,Ui_MainWindow为qtMainWindows.py文件里的UI类。
(5) 添加按钮事件。
from qtMainWindows import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow,QMessageBox
class MainWindow(QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.b1)#连接槽函数
def b1(self):#槽函数
QMessageBox.information(self, '提示', '按钮')
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
(6) 运行结果:
3.Pyinstaller打包发布
(1) 我的项目目录:G:\program\Py_qt5,进入目录:G:\program\Py_qt5\venv\Scripts。
(2) 打开cmd,直接输入cmd可打开。
(3) 激活环境:输入activate。
(4) 进入主函数目录,输入cd /d G:\program\Py_qt5,主函数在myWindows.py文件中,myWindows.py文件在Py_qt5文件夹中。
(5)输入pyinstaller myWindows.py --noconsole
(6) 打包后的exe存放在:G:\program\Py_qt5\dist\myWindows