BMI Calculator in python

introduction

BMI Calculator in python is a widely used and simple tool to assess whether an individual has a healthy body weight relative to their height. It is a numerical value calculated using a person’s weight and height, and is used to categorize individuals into various health-related categories such as underweight, normal weight, overweight, and obese. These classifications help in early identification of potential health risks such as heart disease, diabetes, and hypertension.

In this project, we create a Graphical User Interface (GUI)-based BMI Calculator using the Tkinter library in Python, directly within a Jupyter Notebook environment.

The GUI provides an intuitive and user-friendly interface for entering input values and instantly calculating BMI with a corresponding health category.

This tool is ideal for educational purposes, fitness enthusiasts, and developers learning GUI development. It provides real-time feedback and uses basic error handling to ensure valid input.

The simplicity of the calculator makes it accessible to users of all ages, while the underlying logic reinforces core Python programming concepts like event handling, conditional statements, and function definitions.

 Key Features:

  • User input fields for weight (kg) and height (cm)

  • Instant BMI calculation with health category classification

  • Interactive GUI using Tkinter

  • Error handling for invalid inputs

  • Easy-to-understand layout and design

What This Project Demonstrates:

  • Creation of Tkinter-based GUI applications in Jupyter Notebook.

  • Real-world application of BMI calculation logic.

  • Use of input validation and error handling to prevent crashes.

  • Real-time output display and classification of BMI results.

  • Aesthetic design and layout creation using GUI widgets like Label, Entry, Button, and Messagebox.

Who Can Use This Project?

  • Beginners in Python learning GUI development.

  • Medical or fitness students creating personal tools or demonstrations.

  • Educators and instructors teaching health concepts or basic programming.

  • Anyone interested in health and wellness tracking tools.

Learning Outcomes:

  • Understanding the use of Tkinter for Python GUI development.

  • Developing logic for mathematical calculations and user classification.

  • Creating user-friendly applications in Jupyter Notebook.

  • Handling user errors gracefully using popup messages.

  • Making programs more interactive and visually engaging.

steps to create BMI calculator in python

Step 1: Open Jupyter Notebook

  • Launch Jupyter Notebook on your computer.

  • Create a new Python 3 Notebook (.ipynb).

Step 2: Import Required Libraries

import tkinter as tk
from tkinter import messagebox

tkinter is used for creating the GUI. messagebox is used to show error alerts.

Step 3: Define the BMI Calculation Function

def calculate_bmi():
    try:
        weight = float(entry_weight.get())
        height = float(entry_height.get()) / 100  # Convert cm to meters
        bmi = weight / (height ** 2)
        bmi = round(bmi, 2)

        if bmi < 18.5:
            category = "Underweight"
        elif 18.5 <= bmi < 24.9:
            category = "Normal weight"
        elif 25 <= bmi < 29.9:
            category = "Overweight"
        else:
            category = "Obese"

        result_label.config(text=f"BMI: {bmi} ({category})")
    except ValueError:
        messagebox.showerror("Invalid input", "Please enter valid numbers for weight and height.")

Step 4: Create the Main Window

root = tk.Tk()
root.title("BMI Calculator")
root.geometry("300x250")
root.config(bg="#f0f0f0")

This sets the title, size, and background color of the window.

Step 5: Add Labels and Entry Widgets

label_title = tk.Label(root, text="BMI Calculator", font=("Arial", 16, "bold"), bg="#f0f0f0")
label_title.pack(pady=10)

label_weight = tk.Label(root, text="Enter weight (kg):", bg="#f0f0f0")
label_weight.pack()
entry_weight = tk.Entry(root)
entry_weight.pack(pady=5)

label_height = tk.Label(root, text="Enter height (cm):", bg="#f0f0f0")
label_height.pack()
entry_height = tk.Entry(root)
entry_height.pack(pady=5)

Step 6: Add Button to Trigger Calculation

btn_calculate = tk.Button(root, text="Calculate BMI", command=calculate_bmi, bg="#4CAF50", fg="white")
btn_calculate.pack(pady=10)

Step 7: Display Result Label

result_label = tk.Label(root, text="", font=("Arial", 12), bg="#f0f0f0")
result_label.pack(pady=10)

Step 8: Run the App

root.mainloop()

This keeps the GUI running and responsive to user actions.

 Summary of Components:

ComponentPurpose
LabelDisplay static text
EntryAccept user input
ButtonTrigger BMI calculation
messageboxShow error pop-up
Label (result)Show BMI result and category

code explanation

1.import libraries

🔹 import tkinter as tk

  • Imports the tkinter library as tk, which is used to build GUI applications in Python.

🔹 from tkinter import messagebox

  • Imports the messagebox module to show error popups.

calculate_bmi() Function

🔹 weight = float(entry_weight.get())

  • Gets the weight input from the entry box and converts it to a float.

🔹 height = float(entry_height.get()) / 100

  • Gets the height in cm, converts it to float, and divides by 100 to convert to meters.

🔹 bmi = weight / (height ** 2)

  • Applies the BMI formula:

    BMI=weight (kg)(height (m))2\text{BMI} = \frac{\text{weight (kg)}}{(\text{height (m)})^2}

🔹 bmi = round(bmi, 2)

  • Rounds the BMI value to 2 decimal places.

🔹 BMI Category Conditions:

if bmi < 18.5:
    category = "Underweight"
elif 18.5 <= bmi < 24.9:
    category = "Normal weight"
elif 25 <= bmi < 29.9:
    category = "Overweight"
else:
    category = "Obese"
  • Classifies the user based on their BMI range.

🔹 result_label.config(...)

  • Updates the result label text to show the BMI and category.

🔹 except ValueError

  • If user inputs invalid data (e.g., letters instead of numbers), shows a popup error.

 GUI Layout Components

🔹 root = tk.Tk()

  • Initializes the main window.

🔹 root.title("BMI Calculator")

  • Sets the window title.

🔹 root.geometry("300x250")

  • Sets the window size (width x height).

🔹 root.config(bg="#f0f0f0")

  • Sets background color of the window.

🔹 Label Widgets:

label_title = tk.Label(root, text="BMI Calculator", font=("Arial", 16, "bold"), bg="#f0f0f0")
label_title.pack(pady=10)
  • Displays the title at the top with padding.

🔹 Entry Widgets:

entry_weight = tk.Entry(root)
entry_height = tk.Entry(root)
  • Input fields for weight and height.

🔹 Button Widget:

btn_calculate = tk.Button(root, text="Calculate BMI", command=calculate_bmi, bg="#4CAF50", fg="white")
  • When clicked, this button triggers the calculate_bmi() function.

🔹 result_label

result_label = tk.Label(root, text="", font=("Arial", 12), bg="#f0f0f0")
  • Displays the final BMI and health category.

🔹 root.mainloop()

  • Starts the GUI event loop — keeps the window open and responsive.

 Summary

ElementPurpose
tk.Tk()Creates main window
EntryTakes user input
LabelDisplays text/output
ButtonCalls BMI function
messageboxAlerts on invalid input
mainloop()Keeps GUI window open

 

source code

				
					import tkinter as tk
from tkinter import messagebox
def calculate_bmi():
    try:
        weight = float(entry_weight.get())
        height = float(entry_height.get()) / 100  # Convert cm to meters
        bmi = weight / (height ** 2)
        bmi = round(bmi, 2)

        if bmi &lt; 18.5:
            category = &quot;Underweight&quot;
        elif 18.5 &lt;= bmi &lt; 24.9:
            category = &quot;Normal weight&quot;
        elif 25 &lt;= bmi &lt; 29.9:
            category = &quot;Overweight&quot;
        else:
            category = &quot;Obese&quot;

        result_label.config(text=f&quot;BMI: {bmi} ({category})&quot;)
    except ValueError:
        messagebox.showerror(&quot;Invalid input&quot;, &quot;Please enter valid numbers for weight and height.&quot;)
root = tk.Tk()
root.title(&quot;BMI Calculator&quot;)
root.geometry(&quot;300x250&quot;)
root.config(bg=&quot;#f0f0f0&quot;)
label_title = tk.Label(root, text=&quot;BMI Calculator&quot;, font=(&quot;Arial&quot;, 16, &quot;bold&quot;), bg=&quot;#f0f0f0&quot;)
label_title.pack(pady=10)

label_weight = tk.Label(root, text=&quot;Enter weight (kg):&quot;, bg=&quot;#f0f0f0&quot;)
label_weight.pack()
entry_weight = tk.Entry(root)
entry_weight.pack(pady=5)

label_height = tk.Label(root, text=&quot;Enter height (cm):&quot;, bg=&quot;#f0f0f0&quot;)
label_height.pack()
entry_height = tk.Entry(root)
entry_height.pack(pady=5)

btn_calculate = tk.Button(root, text=&quot;Calculate BMI&quot;, command=calculate_bmi, bg=&quot;#4CAF50&quot;, fg=&quot;white&quot;)
btn_calculate.pack(pady=10)

result_label = tk.Label(root, text=&quot;&quot;, font=(&quot;Arial&quot;, 12), bg=&quot;#f0f0f0&quot;)
result_label.pack(pady=10)
root.mainloop()

				
			

output

More java Pojects
Get Huge Discounts
				
					console.log( 'Code is Poetry' );
				
			

output