BMI Calculator using PyQt5

I’ve been meaning to make a GUI for the WiFi scanner program I made, so I have started learning how to make GUIs with PyQt5.

I chose PyQt5 for making GUIs since it is very modern looking. I tried Tkinter and disliked it since it looked very dated.

As a way of practicing what I learned from other tutorials, I decided to make my own app that calculates BMI. Here’s the code:

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
        QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit)
from PyQt5.QtGui import QPixmap


class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        # Adding widgets 
        self.output = QLabel('Enter Height in Inches and Weight in lbs')
        self.weight_label= QLabel('Weight (lbs): ')
        self.height_label = QLabel('Height (in): ')
        self.weight_input = QLineEdit()
        self.height_input = QLineEdit()
        self.return_button = QPushButton('Enter')
        self.legend = QLabel('Below 18.5 : Underweight\n' + \
                '18.5-24.9: Normal\n' + '25.0-29.9 : Overweight\n' + \
                '30.0 and Above: Obese')

        # Setting layout
        h_weight = QHBoxLayout()
        h_weight.addWidget(self.weight_label)
        h_weight.addWidget(self.weight_input)

        h_height = QHBoxLayout()
        h_height.addWidget(self.height_label)
        h_height.addWidget(self.height_input)

        v = QVBoxLayout()
        v.addWidget(self.output)
        v.addLayout(h_weight)
        v.addLayout(h_height)
        v.addWidget(self.return_button)
        v.addWidget(self.legend)

        h_total = QHBoxLayout()
        h_total.addStretch()
        h_total.addLayout(v)
        h_total.addStretch()

        self.setLayout(h_total)

        # Button clicked actions
        self.return_button.clicked.connect(self.calc_bmi)

        self.setWindowTitle('Calculate BMI')
        self.show()

    def calc_bmi(self):
        # Calculate bmi and change label
        metric_weight = float(self.weight_input.text()) * 0.45
        metric_height = float(self.height_input.text()) * 0.025
        bmi = metric_weight / (metric_height ** 2)
        self.output.setText('Your BMI is: {:.2f}'.format(bmi))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Window()
    sys.exit(app.exec_())

 

Leave a Reply

Your email address will not be published. Required fields are marked *