Sunday, 21 December 2025

Python BMI Calculator

 


Code:

import tkinter as tk from tkinter import messagebox def calculate_bmi(): try: w = float(entry_weight.get()) h = float(entry_height.get()) / 100 # convert cm → meters bmi = w / (h*h) bmi = round(bmi, 2) # Category check if bmi < 18.5: status = "Underweight ๐Ÿ˜•" color = "blue" elif bmi < 25: status = "Normal ๐Ÿ˜Š" color = "green" elif bmi < 30: status = "Overweight ๐Ÿ˜" color = "orange" else: status = "Obese ๐Ÿ˜ง" color = "red" label_result.config(text=f"Your BMI: {bmi}\nStatus: {status}", fg=color) except: messagebox.showwarning("Input Error", "Please enter valid numbers!") # --- GUI Window --- root = tk.Tk() root.title("BMI Calculator") root.geometry("360x350") root.config(bg="#E8F6EF") root.resizable(False, False) # Title title = tk.Label(root, text="๐Ÿ’ช BMI Calculator ๐Ÿ’ช", font=("Arial", 18, "bold"), bg="#E8F6EF", fg="#2C3A47") title.pack(pady=15) # Frame Inputs frame = tk.Frame(root, bg="#E8F6EF") frame.pack(pady=10) tk.Label(frame, text="Weight (kg):", font=("Arial",12), bg="#E8F6EF").grid(row=0, column=0, padx=10, pady=5) entry_weight = tk.Entry(frame, width=12, font=("Arial",12)) entry_weight.grid(row=0, column=1) tk.Label(frame, text="Height (cm):", font=("Arial",12), bg="#E8F6EF").grid(row=1, column=0, padx=10, pady=5) entry_height = tk.Entry(frame, width=12, font=("Arial",12)) entry_height.grid(row=1, column=1) # Calculate Button btn_calc = tk.Button(root, text="Calculate BMI", font=("Arial", 12, "bold"), bg="#45CE30", fg="white", width=18, command=calculate_bmi) btn_calc.pack(pady=15) # Result Label label_result = tk.Label(root, text="", font=("Arial", 14, "bold"), bg="#E8F6EF") label_result.pack(pady=20) # Footer footer = tk.Label(root, text="Healthy BMI = 18.5 – 24.9", font=("Arial",10), bg="#E8F6EF", fg="#6D214F") footer.pack() root.mainloop()

Output:


Code Explanation:

Importing Required Libraries
import tkinter as tk
from tkinter import messagebox

What this means:

tkinter as tk — imports the Tkinter module and assigns it a short name tk to make widget creation easier.

messagebox — a Tkinter sub-module that allows pop-up alert dialogs.
You use it here to show an Input Error warning when invalid data is entered.

Defining the BMI Calculation Function
def calculate_bmi():

This function executes when the Calculate BMI button is clicked.

Inside the function, we wrap everything in a try / except block:
try:
    w = float(entry_weight.get())
    h = float(entry_height.get()) / 100


entry_weight.get() pulls the typed text from the weight input box.

float(...) converts text to a number.

entry_height.get() reads height in centimeters, so dividing by 100 converts it to meters, which is required for BMI formula.

If the conversion fails (text is empty or contains letters), the code jumps to the except block.

Applying the BMI Formula
bmi = w / (h*h)
bmi = round(bmi, 2)

Explanation:

BMI formula = weight (kg) / height(m)²

The result is rounded to 2 decimals for clarity.

Example:
70kg & 175cm → 70 / 1.75² = 22.86

Checking BMI Category

After calculating BMI, the code checks which WHO health range it belongs to:

if bmi < 18.5:
    status = "Underweight ๐Ÿ˜•"
    color = "blue"
elif bmi < 25:
    status = "Normal ๐Ÿ˜Š"
    color = "green"
elif bmi < 30:
    status = "Overweight ๐Ÿ˜"
    color = "orange"
else:
    status = "Obese ๐Ÿ˜ง"
    color = "red"

What it does:

Uses if − elif − else to compare BMI against ranges.

Assigns:

status text describing health category

emoji for emotion

color for text display

Categories logic:
BMI Range Category Color
< 18.5 Underweight Blue
18.5–24.9 Normal Green
25–29.9 Overweight Orange
≥ 30 Obese Red

This makes the output visual, emotional, and health-interpretable.

Displaying the Result on the Label
label_result.config(text=f"Your BMI: {bmi}\nStatus: {status}", fg=color)


This dynamically updates an existing Label widget by:

putting BMI value + category text

coloring the letters based on status (fg=color)

adding \n for line break

So the interface changes instantly without creating a new widget.

Error Handling
except:
    messagebox.showwarning("Input Error", "Please enter valid numbers!")


This runs only if:

inputs are blank

non-numeric characters are entered

showwarning() opens a yellow warning popup window.

Creating the GUI Window
root = tk.Tk()
root.title("BMI Calculator")
root.geometry("360x350")
root.config(bg="#E8F6EF")
root.resizable(False, False)

Explanation:

tk.Tk() creates the main application window

title() sets the window title bar text

geometry() sets pixel size (width × height)

config(bg=...) changes background color

resizable(False, False) prevents resizing horizontally & vertically

This results in a fixed-size clean window.

Creating the App Title Label
title = tk.Label(root, text="๐Ÿ’ช BMI Calculator ๐Ÿ’ช", font=("Arial", 18, "bold"), bg="#E8F6EF", fg="#2C3A47")
title.pack(pady=15)


A Label widget displays text on screen

Font size 18 bold makes it prominent

Emojis add personality

.pack(pady=15) spaces it vertically

Creating an Input Frame
frame = tk.Frame(root, bg="#E8F6EF")
frame.pack(pady=10)

A Frame groups widgets together, making layout easier.

Weight Input Row
tk.Label(frame, text="Weight (kg):", font=("Arial",12), bg="#E8F6EF").grid(row=0, column=0, padx=10, pady=5)
entry_weight = tk.Entry(frame, width=12, font=("Arial",12))
entry_weight.grid(row=0, column=1)

Here:

A Label displays "Weight (kg):"

An Entry box allows user input

We use .grid(row,column) for neat placement inside the frame

Padding adds space around elements

Height Input Row
tk.Label(frame, text="Height (cm):", font=("Arial",12), bg="#E8F6EF").grid(row=1, column=0, padx=10, pady=5)
entry_height = tk.Entry(frame, width=12, font=("Arial",12))
entry_height.grid(row=1, column=1)

Similar to weight input but for Height in centimeters.

The Calculate Button
btn_calc = tk.Button(root, text="Calculate BMI", font=("Arial", 12, "bold"),
                     bg="#45CE30", fg="white", width=18, command=calculate_bmi)
btn_calc.pack(pady=15)

Explanation:

Creates a Button widget

Green button with white text

Width 18 makes it visually wide

Most important part:

command=calculate_bmi

— means this function is called when clicked.

Output Result Label
label_result = tk.Label(root, text="", font=("Arial", 14, "bold"),
                        bg="#E8F6EF")
label_result.pack(pady=20)


This blank label will later display:

BMI value

Category

Emoji

Color

Initially empty.

Footer Text
footer = tk.Label(root, text="Healthy BMI = 18.5 – 24.9", font=("Arial",10),
                  bg="#E8F6EF", fg="#6D214F")
footer.pack()

Simply shows helpful advice to guide users.

Event Loop (Runs the App Forever)
root.mainloop()

This line:

Starts Tkinter GUI event system

Keeps window open

Listens for button clicks, input typing, etc.

Without mainloop(), the window would close immediately.






0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (166) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (230) Data Strucures (14) Deep Learning (81) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (18) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (50) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (204) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1229) Python Coding Challenge (915) Python Mistakes (1) Python Quiz (357) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)