当前环境:Win10 x64 + Python 3.8.10 + PyQt==5.15.2 + PyQt-tools==5.15.9.33
1 打开 designer.exe ,新建一个 Dialog without Buttons , 设计窗体。
C:\Python\Python38-32\Lib\site-packages\qt5_applications\Qt\bin\designer.exe
2 使用命令转换为 py
C:\Python\Python38-32\Scripts\pyuic5.exe -x dialog.ui -o dialog.py
说明: -x 会产生 __main__ 函数。
3 实现查询和调用。
dialog.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(675, 484)
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(50, 50, 471, 20))
self.lineEdit.setObjectName("lineEdit")
self.textEdit = QtWidgets.QTextEdit(Dialog)
self.textEdit.setGeometry(QtCore.QRect(40, 100, 601, 361))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(550, 50, 75, 23))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
self.pushButton.clicked.connect(Dialog.searchIP) # type: ignore
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "查询"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
mydialog.py
# -*- coding: utf-8 -*-
import sys
import dialog
from PyQt5.QtWidgets import QApplication, QDialog
import requests
class MainDialog(QDialog):
"""
def __init__(self):
super().__init__()
self.ui = dialog.Ui_Dialog()
self.ui.setupUi(self)
"""
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
self.ui = dialog.Ui_Dialog()
self.ui.setupUi(self)
def searchIP(self):
# 获取IP
query = self.getIP()
r = requests.get(f"http://ip-api.com/json/{query}")
text = r.text
self.ui.textEdit.setText(text)
def getIP(self):
ip = self.ui.lineEdit.text()
return ip
if __name__ == '__main__':
app = QApplication(sys.argv)
myDlg = MainDialog()
myDlg.show()
sys.exit(app.exec_())
4 运行 mydialog.py
参考:
https://github.com/zhiyiYo/PyQt-Fluent-Widgets/issues/786
https://www.cnblogs.com/lovesoo/p/12491361.html