今天來用之前介紹的PyQt來製作一個對話框,結合前一篇介紹的爬蟲程式來做一個小小的應用
首先,要用python製作對話框需要先準備好下列幾樣東西:
如果你是用Anaconda的話,開啟cmd或Anaconda Prompt,直接在你想要的環境中輸入conda install pyqt5
如果你使用原生python則可以輸入pip指令安裝pip install pyqt5
先下載Qt的Qt Designer製作工具,有許多現成的元件可以圖像化製作,在軟體中拉一拉元件,規劃你要的介面,就可以直接輸出.ui檔
可以將.ui檔轉換為.py檔供python使用,為安裝PyQt5後附加的工具,於cmd中切換到當前環境目錄(例:...\Anaconda3\Scripts\pyuic5.exe),輸入語法為pyuic ui_file_from_QtDesigner.ui -o ui_file_for_python.py
Where is pyside-uic.exe? https://stackoverflow.com/questions/6684180/where-is-pyside-uic
下列附上ui介面完整程式碼:
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(600, 800)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setSpacing(10)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setObjectName("comboBox")
self.gridLayout.addWidget(self.comboBox, 1, 0, 1, 2)
self.pushButton = QtWidgets.QPushButton(Form)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 1, 2, 1, 1)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1)
self.comboBox_2 = QtWidgets.QComboBox(Form)
self.comboBox_2.setObjectName("comboBox_2")
self.gridLayout.addWidget(self.comboBox_2, 3, 0, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 3, 1, 1, 2)
self.listWidget = QtWidgets.QListWidget(Form)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 4, 0, 1, 3)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "爬蟲工具"))
self.label.setText(_translate("Form", "看板"))
self.pushButton.setText(_translate("Form", "+"))
self.label_2.setText(_translate("Form", "關鍵字搜尋"))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QDialog()
ui = Ui_Form()
ui.setupUi(window)
window.show()
sys.exit(app.exec_())
Using Qt Designer
https://www.riverbankcomputing.com/static/Docs/PyQt5/designer.html