Are you interested in building an application that can calculate Body Mass Index (BMI) using Python GUI? Look no further, as we will guide you through creating a BMI app with Python. BMI is essential for monitoring and maintaining a healthy lifestyle, making it a great project for beginners and intermediate-level Python programmers.
With the help of Python and the Delphi ecosystem, you can create an easy-to-use and interactive BMI app that anyone can use. In this post, we’ll provide a step-by-step guide to building a BMI app using Python GUI. So, let’s begin exploring the world of Python GUI programming!
Table of Contents
Why is a BMI Calculator App Important?
A BMI calculator app is useful because it allows people to monitor and track their body mass index, which is an important indicator of their overall health and well-being.
Such an app can be useful for individuals who want to maintain a healthy weight or for healthcare professionals who need to monitor their patients’ health. It can also detect potential health issues, such as obesity, leading to serious health problems like heart disease, diabetes, and stroke.
With the help of a BMI calculator app, users can easily track their BMI and get feedback on their progress toward achieving a healthy weight. Additionally, these apps often provide helpful tips on maintaining a healthy diet and lifestyle, making them an excellent tool for promoting healthy habits and overall wellness.
What Information do you Need to Calculate the BMI?
To calculate BMI (Body Mass Index), you need two pieces of information:
- Weight: The weight of the person in kilograms (kg) or pounds (lbs).
- Height: The height of the person in meters (m) or feet (ft) and inches (in).
Using these two pieces of information, you can calculate the BMI using the following formula:
BMI = Weight (kg) / Height² (m²)
Alternatively, you can use the following formula if you weigh pounds and height in inches:
BMI = (Weight (lbs) / Height² (in²)) x 703
Once you have calculated the BMI, you can use it to determine the weight status of the person based on the following categories:
- Underweight: BMI less than 18.5
- Normal weight: BMI between 18.5 and 24.9
- Overweight: BMI between 25 and 29.9
- Obese: BMI of 30 or higher
BMI is a useful tool for determining weight status but ignores things like muscle mass and body composition. Therefore, checking in with a healthcare professional for a more thorough health assessment is best.
What Kinds of Tools can be Useful in Building This App?
Delphi for Python is a powerful tool for developers who want to create cross-platform desktop applications using Python. With its comprehensive features, including powerful user interface (UI) design tools and cross-platform support, Delphi for Python can help developers create desktop applications that operate smoothly across multiple platforms.
The Delphi FMX framework enables developers to build visually appealing and efficient GUIs that work seamlessly on Windows, macOS, iOS, and Android devices. The Delphi Community Edition is a free, open-source version of the Delphi IDE, and the PythonFMXBuilder is also available for developers who prefer to work with open-source tools. With Delphi for Python, developers can reduce the time and effort required to develop cross-platform desktop applications, ensure consistent and reliable operation across all platforms, and create robust and feature-rich applications.
How Can You Create A BMI Calculator for Android Using These Tools?
What Are the Software Requirements to Complete this Task?
Before we dive into creating a BMI app with Delphi Ecosystem and Python, there are a few things you will need to have installed on your machine:
- Delphi IDE: You can download the community edition from the Embarcadero website for free.
- Delphi4PythonExporter tool: You can install this plugin by searching for it in the Delphi CE environment.
- Python: You can download the latest version of Python from the official website.
- Python4Delphi and PythonFMXBuilder: This library allows you to call Python functions from Delphi code. You can download it from the Python4Delphi Github repository.
- PyScripter or any other IDE that supports Python.
If you haven’t installed any of these tools, we recommend checking out the article “Powerful Python GUI Project Setup” to help you get started. In addition, you should have a basic understanding of Python and Delphi programming concepts to follow along with this tutorial.
Once you have all the required tools, you can proceed with the tutorial to create your BMI app using Delphi Ecosystem and Python.
You can grab the code for this tutorial from our GitHub repository using the following link:
https://github.com/Embarcadero/PythonBlogExamples/tree/main/BMI_Calculator_App
Let’s get started with creating our BMI Calculator App!
How to Create a Form in Delphi CE?
Let us start by opening Delphi CE and creating our first blank project. We will do this by clicking Create a new Project… under the Develop tab.
Next, select Multi-Device Application:
Finally, select Blank Application and click Ok.
For this tutorial, we have named our project as BMI_Calculator_App
.
Let’s start by giving our form a name. To do this, right-click on the form and select QuickEdit. Here, we will name our form MainForm
with the caption BMI Calculator
.
If you need to become more familiar with the various sections of the Delphi IDE, we recommend referring to our free eBook bundle, which covers the Delphi Python EcoSystem and all Python GUI offerings.
Next, we need to resize our form. To do this, head to the object inspector and search for ClientHeight
and ClientWidth
. Here, we will set them to 500
and 360
, respectively.
This form will serve as the main view of our application, where the user will be able to calculate their BMI. Therefore, let us add some components to this form to make it more functional.
First, let’s add a few labels to make it look more like an app. To do this, head on over to the Palette and search for the TLabel
Component. Then, drag and drop this component into the form.
Next, right-click on the label and go to QuickEdit. Here we will give the name Title
, and caption of BMI Calculator App
.
Now let’s modify the text style. Again, select the label and head to the Object Inspector
. Next, search for TextSettings
and click on the ...
right next to the Font property to modify the label’s font, size, and style based on your preferences.
Now, center the text using the HorzAlign
and VertAlign
properties in TextSettings
. So select the label component, and again, under the TextSettings
select the HorzAlign
and VertAlign
properties and adjust the properties to Center
.
Here is what our form looks like:
Similarly, let’s have a few more labels that will indicate the input fields for our app.
Note that we have also added another label Status
in the form that is not visible as it does not have any text. We will use this to display error messages to the user.
Now, we need to add a button that will help our user calculate their BMI and send them to the next form. For this, we will be using a TButton
component. So go to the Palette
and add a button using the TButton
component.
Next, we will modify this button to make it more appealing. But before that, we need to change the text on the Button. So right-click the button and, using QuickEdit, rename it to ResultsButton
with the caption Results
.
Next, select the button and head to TextSettings
. Here we will change the font size to Segoe UI with a font size of 16 and change the size of the button.
Our MainForm
is almost complete. Now, we just need to add two more components allowing the user to input their measurements. Head to the Palette
and search for the TEdit
Label. Again, we will use QuickEdit
to give these components intuitive names. Here we are adding 3 TEdit
components WeightEdit
, HeightFeetEdit
, and HeightInchEdit
, that, as the name implies, allow our users to input their weight and height, respectively.
Finally, we must allow users to add their weight in either imperial or metric units. To do this, we will use a radio button. So again, head to the Palette and search for the TRadioButton
component.
We will add two radio buttons to our form, giving them a name of PoundsRadio
, and KgRadio
. We will also modify their appearance using TextSettings.
Finally, let’s adjust the form’s background color by navigating to the Object Inspector and selecting the form’s fill
property.
This completes our MainForm
. Now let’s create a new form that will display our app. So right-click on BMI_Calculator_App.exe
and select Add New > Multi-Device Form
.
This will create a new form that will serve the result screen. Here we have named the form ResultsForm
and its corresponding source file Results.pas
. We also changed its dimension to match our MainForm
.
Next, similarly to our MainForm
let’s add color to our ResultsForm
and add a few labels and buttons. This form will only be used to display the results to our users. Here is what our form looks like:
Finally, we add a DetailsLabel
to display a custom message to our users based on their BMI.
How to Create a BMI App With Delphi Ecosystem And Python. App screen
Now that our forms are completed, we must ensure that the buttons remain functional when we export our application as a Python project. To do this, go to each form and double-click each button to add an OnClick
method to that button. The procedure will be created in the .pas
file corresponding to the .fmx
form.
Next, add at least one comment (//
) to each procedure. This will ensure the procedure is preserved when you export it as a Python file.
Can this Form be Easily Exported Into Python Code?
To export our project as Python scripts, we only need to select Tools > Export To Python > Export Current Entire Project
.
Next, we name our project BMI Calculator
, and select the main form as MainForm
. Finally, select the directory of your choosing and click Export:
This will generate 3 Python scripts and 2 .pyfmx
scripts in our specified directory. The BMI_Calculator_App.py
is used to launch our Delphi app, while Results.py
, and Main.py
Python files contain the classes for the individual forms. Along with the Python file for each form, Delphi also generates a .pyfmx
script of the same name as each form that contains the visual information of that form. Here are the contents of each file.
BMI_Calculator_App.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from delphifmx import * from Main import MainForm def main(): Application.Initialize() Application.Title = 'BMI Calculator' Application.MainForm = MainForm(Application) Application.MainForm.Show() Application.Run() Application.MainForm.Destroy() if __name__ == '__main__': main() |
Main.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import os from delphifmx import * class MainForm(Form): def __init__(self, owner): self.WeightEdit = None self.HeightFeetEdit = None self.ResultsButton = None self.HeightLabel = None self.WeightLabel = None self.Title = None self.PoundsRadio = None self.KgRadio = None self.FeetLabel = None self.HeightInchEdit = None self.InchLabel = None self.Status = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) def ResultsButtonClick(self, Sender): pass |
Results.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import os from delphifmx import * class ResultsForm(Form): def __init__(self, owner): self.BMIScore = None self.Label1 = None self.DetailsLabel = None self.CategoryLabel = None self.Title = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx")) |
How to Add Functionality to this Application?
Now that our Python scripts are ready let’s start adding functionality to our code. Start by opening our MainForm
in Main.py
and navigating to the __init__
function.
In our __init__
function, we will only initialize a new variable self.BMI
that will store the BMI of our individual. This will then be passed to the ResultsForm
, where it will be displayed. Here is what our __init__
function looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def __init__(self, owner): self.WeightEdit = None self.HeightFeetEdit = None self.ResultsButton = None self.HeightLabel = None self.WeightLabel = None self.Title = None self.PoundsRadio = None self.KgRadio = None self.FeetLabel = None self.HeightInchEdit = None self.InchLabel = None self.Status = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) self.BMI = 0 # Initialize BMI that would be calculated and sent to next form |
Next, let’s create a GetBMI
function that uses the height and weight of our individual to calculate the BMI of our user:
1 2 3 4 5 6 7 |
def GetBMI(self, weight, heightft, heightin): # For BMI Calculation, Weight should be in kg and Height in meters if self.PoundsRadio.IsChecked: weight = weight / 2.205 height = heightft * 0.3048 + heightin * 0.0254 # Conversion to meters return round(weight / (height**2), 2) # BMI = Weight/ (Height)^2 |
The BMI function checks whether the radio button for lbs is checked. If it is, it adds a conversion layer to convert the weight in pounds back into kilograms. It then uses the weight and height to generate a BMI based on our formula earlier and rounds it to 2 decimal places.
Now, let’s add functionality to our Results
button. Head to the ResultsButtonClick
function and start by checking whether the user has input in any fields. If the user does not have input in any fields, we use the Status
label to display an error.
1 2 3 4 5 |
def ResultsButtonClick(self, Sender): # Error Handling if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="": self.Status.Text = "Please fill in all fields" |
Next, we check whether the height input in inches is between 0 and 11:
1 2 3 |
elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11: self.Status.Text = "Give inches between 0 and 11" |
Finally, if there are no errors, we call the GetBMI
function and send the BMI to our results form. First, we import the ResultsForm
from the Results.py
file:
1 2 |
from Results import ResultsForm |
We call the GetBMI
function and store its result in a separate variable. Then, we create an instance of the ResultsForm
and use the .Show()
method to show the form. Here is what our final ResultsButtonClick
function looks like:
1 2 3 4 5 6 7 8 9 10 11 12 |
def ResultsButtonClick(self, Sender): # Error Handling if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="": self.Status.Text = "Please fill in all fields" elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11: self.Status.Text = "Give inches between 0 and 11" # If no errors else: self.BMI = self.GetBMI(float(self.WeightEdit.Text), int(self.HeightFeetEdit.Text), int(self.HeightInchEdit.Text)) self.results = ResultsForm(self, BMI=self.BMI) self.results.Show() |
Here is what our final Main.py
looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import os from delphifmx import * from Results import ResultsForm class MainForm(Form): def __init__(self, owner): self.WeightEdit = None self.HeightFeetEdit = None self.ResultsButton = None self.HeightLabel = None self.WeightLabel = None self.Title = None self.PoundsRadio = None self.KgRadio = None self.FeetLabel = None self.HeightInchEdit = None self.InchLabel = None self.Status = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Main.pyfmx")) self.BMI = 0 # Initialize BMI that would be calculated and sent to next form def ResultsButtonClick(self, Sender): # Error Handling if (self.PoundsRadio==False and self.KgRadio==False) or self.HeightFeetEdit.Text=="" or self.HeightInchEdit.Text=="" or self.WeightEdit.Text=="": self.Status.Text = "Please fill in all fields" elif int(self.HeightInchEdit.Text) < 0 or int(self.HeightInchEdit.Text) > 11: self.Status.Text = "Give inches between 0 and 11" # If no errors else: self.BMI = self.GetBMI(float(self.WeightEdit.Text), int(self.HeightFeetEdit.Text), int(self.HeightInchEdit.Text)) self.results = ResultsForm(self, BMI=self.BMI) self.results.Show() def GetBMI(self, weight, heightft, heightin): # For BMI Calculation, Weight should be in kg and Height in meters if self.PoundsRadio.IsChecked: weight = weight / 2.205 height = heightft * 0.3048 + heightin * 0.0254 # Conversion to meters return round(weight / (height**2), 2) # BMI = Weight/ (Height)^2 |
Next, let’s move onto the ResultsForm
. Open up Results.py
and head to the __init__
function. As you may see, when we initialized the ResultsForm
in the MainForm
we passed in a BMI value that cannot be passed onto the original form. To ensure that the ResultsForm
uses the value we passed, we will modify the __init__
function to take in this value:
1 2 |
def __init__(self, owner, BMI): |
Next, we store this BMI in a new variable self.BMI
and display this to our BMIScore
label using the .Text
property.
1 2 3 |
self.BMIScore.Text = str(BMI) self.BMI = BMI |
Now, we define a dictionary with our custom messages that will be displayed based on the user’s weight category:
1 2 3 4 5 6 7 |
self.Detail = { "Underweight": "Your BMI indicates that you are underweight, which may increase your risk of health problems. You should consult a doctor or a dietitian to develop a healthy eating plan that can help you gain weight in a safe and sustainable way.", "Healthy": "Your BMI indicates that you are in a healthy weight range, which is great for your overall health and well-being. Keep up the good work by staying physically active and eating a balanced diet.", "Overweight": "Your BMI indicates that you are overweight, which may increase your risk of health problems such as heart disease and diabetes. You should consider making lifestyle changes such as increasing your physical activity and reducing your calorie intake.", "Obese":"Your BMI indicates that you are obese, which significantly increases your risk of health problems such as heart disease, stroke, and cancer. You should consult a dietitian to develop a weight loss plan that can help you achieve a healthy weight and reduce your risk of these health problems.", } |
Finally, we check the user’s weight category based on their BMI and display a custom message to our DetailsLabel
. Our final Results.py
file looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import os from delphifmx import * class ResultsForm(Form): def __init__(self, owner, BMI): self.BMIScore = None self.Label1 = None self.DetailsLabel = None self.CategoryLabel = None self.Title = None self.Reset = None self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Results.pyfmx")) # More initializations self.BMIScore.Text = str(BMI) self.BMI = BMI self.Detail = { "Underweight": "Your BMI indicates that you are underweight, which may increase your risk of health problems. You should consult a doctor or a dietitian to develop a healthy eating plan that can help you gain weight in a safe and sustainable way.", "Healthy": "Your BMI indicates that you are in a healthy weight range, which is great for your overall health and well-being. Keep up the good work by staying physically active and eating a balanced diet.", "Overweight": "Your BMI indicates that you are overweight, which may increase your risk of health problems such as heart disease and diabetes. You should consider making lifestyle changes such as increasing your physical activity and reducing your calorie intake.", "Obese":"Your BMI indicates that you are obese, which significantly increases your risk of health problems such as heart disease, stroke, and cancer. You should consult a dietitian to develop a weight loss plan that can help you achieve a healthy weight and reduce your risk of these health problems.", } # Categorization according to BMI if BMI < 18.5: self.CategoryLabel.Text = "Underweight" elif 18.5 < BMI < 24.9: self.CategoryLabel.Text = "Healthy" elif 25.0 < BMI < 29.9: self.CategoryLabel.Text = "Overweight" elif BMI > 30: self.CategoryLabel.Text = "Obese" self.DetailsLabel.Text = self.Detail[self.CategoryLabel.Text] # Display details and suggestions according to the category |
Can this Code be Used to Create a Mobile Application?
Now that our app is ready, we can use FMXBuilder to convert this into an Android app.
But before we can create our app, we need to make important adjustments to our code to make it run on Android. Start by creating a new file named BMI_Calculator_App_Android.py
and paste the content of BMI_Calculator_App.py
. Now, open up this new file and start making the changes.
First, we need to remove the initialization. This is done because Delphi initializes Android applications automatically, so it is unnecessary to do it manually. In addition, we don’t need to launch or destroy our app form manually, as Delphi also does this. Here is what our BMI_Calculator_App_Android.py
looks like:
1 2 3 4 5 6 7 8 9 10 |
from delphifmx import * from Main import MainForm def main(): Application.MainForm = MainForm(Application) Application.MainForm.Show() if __name__ == '__main__': main() |
Now we can build our Android app. Start by opening up the FMXBuilder and create a new project by clicking on Project > New project
on the toolbar. Next, enter the name of this new project:
Add your Python and .pyfmx
files by right-clicking on the App and selecting Add file. We won’t add BMI_Calculator_App.py
but instead will be adding the BMI_Calculator_App_Android.py
.
Now, right-click on the BMI_Calculator_App_Android.py
file and set it to the main file.
Now that everything is ready, we must create the .apk
file for the app using the Build Project
button.
When the .apk
is fully generated, you will be prompted with a “Build process done
” message in the Messages box. You can then check out your generated file in the pathtoPythonFMXBuilderGUIexeFolderappsBMIbin
folder.
Now, you must copy the .apk
file into your phone’s storage. Next, install this file by accessing it on your Android device. Once your app is installed, you can use it like any other app on your phone.
Does the App Fulfill all Requirements?
Here is what our final app looks like:
If you press Results
without selecting any field, you get an error message:
Similarly, if you leave any field empty, you also get an error message:
Once you’ve filled in all the fields and press Results
, you will be navigated to the ResultsForm
.
Here you will be presented with your BMI along with a custom message:
You will also be given messages for being healthy, underweight, and overweight:
Are You Ready to Create More Such Apps?
Creating a BMI calculator app using Python and the Delphi ecosystem offers an excellent opportunity for Python developers to enhance their programming skills and produce useful tools that can benefit others. Furthermore, with the help of Delphi’s FireMonkey GUI framework, developers can easily create a user-friendly and aesthetically pleasing app that can be accessed on multiple platforms, including Android and iOS.
The Delphi ecosystem offers a wide range of development tools and libraries, making it an excellent choice for those who want to quickly build powerful and efficient apps. In addition, the cross-platform compatibility of DelphiFMX means that the app you create can be used by a wider audience, regardless of their device or operating system.
By utilizing the features and tools of the Delphi ecosystem, developers can significantly accelerate the app creation process, leading to quicker development and deployment times.
So, don’t wait any longer – start building your next app with the Delphi ecosystem today!
What Are Some FAQs Regarding This Topic?
What is the Delphi ecosystem?
The Delphi ecosystem is a collection of development tools, libraries, and frameworks used for building applications across multiple platforms, including Windows, Android, and iOS.
What is the FireMonkey GUI framework, and why is it useful for app development?
The FireMonkey GUI framework is a cross-platform UI toolkit for developing graphical user interfaces (GUIs) for applications. It’s useful for app development because it provides a rich set of UI controls, allows easy UI elements customization, and supports multiple platforms.
Can I use the BMI calculator app on my smartphone?
Yes, you can use the BMI calculator app on your smartphone. The app can be developed to support both Android and iOS platforms, making it accessible to a wider audience.
Can the BMI calculator app calculate BMI for children?
Yes, the BMI calculator app can calculate BMI for children and adults. However, the BMI calculation formula for children is different. Moreover, if you feel that your child may have certain health problems, it’s important to consult with a healthcare professional for a more accurate assessment of a child’s health.
Hi, thanks for the tutorial. I’m new to Python4Delphi, trying it out, and installed all the requirements. But I get these errors “Application is not defined” and “Form is not defined”. How can I resolve this? Thank you.