1 說明
因爲個人測試,需要在Python中引入一個GUI的界面環境,本人熟悉Qt,所以理所當然地使用了PyQt5這個環境,特此將整個過程整理總結一下,以便更好地讓Python和Qt爲大家服務。
本文先在Win10上從0開始搭建Python3的環境,然後在這個環境上搭建PyQt5的開發運行環境,最後創建了一個包含了用qt designer設計的窗口的例程。
2 安裝Python3
本文使用Python3.8.2
進入https://www.python.org/getit/
點擊如下圖所示的鏈接
在打開的頁面中翻到最底部,點擊如下圖所示的鏈接,下載Windows 64位的安裝包
雙擊下載的安裝包,按照下面的步驟和選擇安裝Python,考慮到部分羣衆對Python和Qt的瞭解有限,請先嚴格按照截圖中的配置和步驟來操作,以後熟悉了再隨意發揮
我們這裏把Python3.8.2成功安裝到了E:/Python382這個路徑下
3 安裝PyQt5和PyQt5-tools
打開Windows的CMD(什麼是CMD?????!!!!!!!!!!!!),分別輸入下面的命令安裝PyQt5和PyQt5-tools
注:網上的資料都是使用pip install PyQt5直接安裝,但我的測試結果是這樣直接安裝總會報錯,使用 -i https://xxxxxxxx到國內鏡像上下載安裝測試順利且成功
PyQt5
E:/Python382/Scripts/pip.exe install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple
PyQt5-tools
E:/Python382/Scripts/pip.exe install pyqt5-tools -i https://pypi.tuna.tsinghua.edu.cn/simple
pip list查看一下,可知PyQt5和PyQt5-tools已經成功安裝
4 使用PyQt5-tools中的designer創建一個簡單的窗口並保存爲ui文件
在CMD中使用命令行打開designer
編輯如下所示的一個簡單的窗口,窗口包含了一個按鈕和一個標籤控件
編輯完成後將這個窗口保存爲mywidget.ui文件,本文中我將這個文件保存到了G:/GWorkSpace/20200404/文件夾中
5 使用PyQt5-tools中的pyuic5工具將mywidget.ui文件翻譯爲mywidget_ui.py文件
CMD切換到G:/GWorkSpace/20200404/文件夾下,使用pyuic5工具翻譯ui文件爲py文件
翻譯後生成的mywidget_ui.py文件內容爲
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mywidget.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MyWidget(object):
def setupUi(self, MyWidget):
MyWidget.setObjectName("MyWidget")
MyWidget.resize(271, 227)
self.buttonTest = QtWidgets.QPushButton(MyWidget)
self.buttonTest.setGeometry(QtCore.QRect(70, 150, 111, 41))
self.buttonTest.setObjectName("buttonTest")
self.labelTest = QtWidgets.QLabel(MyWidget)
self.labelTest.setGeometry(QtCore.QRect(60, 60, 151, 51))
self.labelTest.setObjectName("labelTest")
self.retranslateUi(MyWidget)
QtCore.QMetaObject.connectSlotsByName(MyWidget)
def retranslateUi(self, MyWidget):
_translate = QtCore.QCoreApplication.translate
MyWidget.setWindowTitle(_translate("MyWidget", "Form"))
self.buttonTest.setText(_translate("MyWidget", "Test"))
self.labelTest.setText(_translate("MyWidget", "Test"))
6 創建main.py, mywidget.py等測試文件
mywidget.py
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QWidget, QPushButton, QLabel
import mywidget_ui
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.ui = mywidget_ui.Ui_MyWidget()
self.ui.setupUi(self)
self.initEvent()
def initEvent(self):
self.ui.buttonTest.clicked.connect(self.changeText)
def changeText(self):
print("buttonTest clicked!")
self.ui.labelTest.setText("Hello, PyQt5!")
main.py
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QWidget, QApplication
from mywidget import MyWidget
app = QApplication(sys.argv)
myWidget = MyWidget()
myWidget.setWindowTitle("PyQt5 Test")
myWidget.show()
sys.exit(app.exec())
7 運行測試程序
CMD中運行
運行效果(點擊按鈕前)
運行效果(點擊按鈕後)
(--------------------完----------------------)