Skip to content

Instantly share code, notes, and snippets.

@fastfingertips
Created March 12, 2024 14:13
Show Gist options
  • Save fastfingertips/264fb54e10026cbdf72f2123ac77c1fb to your computer and use it in GitHub Desktop.
Save fastfingertips/264fb54e10026cbdf72f2123ac77c1fb to your computer and use it in GitHub Desktop.
This application is a BMI (Body Mass Index) calculator. It calculates BMI based on the weight and height inputs provided by the user, and then categorizes the BMI value into different weight categories such as underweight, normal weight, overweight, and various levels of obesity.
from tkinter import Tk, Label, Entry, Button
def calculate_bmi():
"""
Calculate the BMI based on the provided weight and height inputs.
"""
weight = get_weight()
height = get_height()
# Check if both weight and height are provided
if weight == "" or height == "":
result_label.config(text="Enter both weight and height!")
else:
try:
# Calculate BMI
bmi = calculate_bmi_value(float(weight), float(height))
# Write result to result_label
result_label.config(text=write_result(bmi))
except ValueError:
# Handle invalid input
result_label.config(text="Enter a valid number!")
def get_weight():
"""
Retrieve the weight input from the weight_entry.
"""
return weight_entry.get()
def get_height():
"""
Retrieve the height input from the height_entry.
"""
return height_entry.get()
def calculate_bmi_value(weight, height):
"""
Calculate BMI value using weight (in kg) and height (in cm).
"""
return weight / ((height / 100) ** 2)
def write_result(bmi):
"""
Generate a string describing the BMI category based on its value.
"""
result_string = f"Your BMI is {round(bmi, 2)}. You are "
if bmi <= 16:
result_string += "severely thin!"
elif 16 < bmi <= 17:
result_string += "moderately thin!"
elif 17 < bmi <= 18.5:
result_string += "mild thin!"
elif 18.5 < bmi <= 25:
result_string += "normal weight"
elif 25 < bmi <= 30:
result_string += "overweight"
elif 30 < bmi <= 35:
result_string += "obese class 1"
elif 35 < bmi <= 40:
result_string += "obese class 2"
else:
result_string += "obese class 3"
return result_string
# Create tkinter window
window = Tk()
window.title("BMI Calculator")
window.config(padx=30, pady=30)
# Create weight input label and entry
weight_input_label = Label(text="Enter Your Weight (kg)")
weight_input_label.pack()
weight_entry = Entry(width=10)
weight_entry.pack()
# Create height input label and entry
height_input_label = Label(text="Enter Your Height (cm)")
height_input_label.pack()
height_entry = Entry(width=10)
height_entry.pack()
# Create calculate button
calculate_button = Button(text="Calculate", command=calculate_bmi)
calculate_button.pack()
# Create result label
result_label = Label()
result_label.pack()
# Start the GUI event loop
window.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment