文章背景:最近在使用PyQt5来创建一些带有UI界面的小工具。下面制作一个简单的界面来计算BMI指数。
系统: Win
代码编辑器:PyCharm Community Edition 2024.3.4
Python版本:Python37
操作步骤:先通过QT designer来设计界面,得到bmi_ui.ui文件,然后再通过pyuic转化为bmi_ui.py文件。然后再创建主程序,导入ui模型。
文件如下:
UI界面如下:
Python主程序如下:
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QMessageBox, QMainWindow, QApplication
from bmi_ui import Ui_MainWindow
import sys
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.onClick)
@pyqtSlot()
def onClick(self):
if self.ui.lineEdit_Length.text() == '' or self.ui.lineEdit_Weight.text() == '':
QMessageBox.about(self, "BMI", "Type something")
else:
height = float(self.ui.lineEdit_Length.text())
mass = float(self.ui.lineEdit_Weight.text())
bmi = mass / (height * height)
bmi = round(bmi, 2)
self.ui.Label_Output.setText(str(bmi))
# ======================
# main
# ======================
if __name__ == '__main__':
app = QApplication([])
win = Example()
win.show()
sys.exit(app.exec())
参考资料:
[1] [Create Desktop Apps with Python PyQt5](https://gumroad.com/d/68fd9e485e55e499552f04dff0996835)