Site icon George的生活點滴

Flet – BMI Calculator

BMI 計算器是一個適合初學者練習的程式,UI 上需要兩個 textfield 讓使用者輸入身高和體重及一個送出鈕呼叫 function 計算結果,最後將結果放到一個 text 上就完成了

除了之外,我們用了 row 讓排版更為美觀,也運用了 radio 讓使用者選擇單位,但其實這一個部份應可以忽略,只是為了練習 radio 而加上的


# Flet - BMI Calculator BMI 計算機 
# # 2024-08-22 
# # https://github.com/lcc728/flet/blob/main/ex_bmi_calculator.py

import flet as ft

def main(page: ft.Page):
    page.title = "BMI 計算"

    def calculate_bmi(e):
        try:
            weight = float(weight_input.value)
            height = float(height_input.value)
            if height_unit.value == "英呎":
                height *= 30.48  
            if weight_unit.value == "磅":
                weight *= 0.454  

            bmi = weight / ((height / 100) ** 2)  
            color, report = determine_bmi_category(bmi)
            result_text.value = f" {bmi:.2f} - {report}"
            result_text.color = color

        except ValueError:
            result_text.value = "請輸入數字"
            result_text.color = "black"
        page.update()  

    def determine_bmi_category(bmi):
        if bmi <= 18.5:
            return "blue", "太輕"
        elif bmi < 24:
            return "green", "標準"
        else:
            return "red", "過胖"    
        
    weight_input = ft.TextField(label="體重", keyboard_type=ft.KeyboardType.NUMBER , width=100)
    weight_unit = ft.RadioGroup(
        value="公斤",
        content=ft.Row([
            ft.Radio(value="公斤", label="公斤"),
            ft.Radio(value="磅", label="磅")
        ]),
        
    )
    weight_row = ft.Row([
        weight_input,
        weight_unit 
    ])   

    height_input = ft.TextField(label="身高", keyboard_type=ft.KeyboardType.NUMBER, width=100)
    height_unit = ft.RadioGroup(
        value="公分",
        content=ft.Row([
            ft.Radio(value="公分", label="公分"),
            ft.Radio(value="英呎", label="英呎")
        ]),
        
    )
    height_row = ft.Row([
        height_input,
        height_unit 
    ])   
        
    calculate_button = ft.ElevatedButton("計算 BMI", on_click=calculate_bmi)
    result_text = ft.Text('', color='black')
    rows = ft.Row([
        ft.Text("您的 BMI 是:"),
        result_text 

    ])
  

    page.add(weight_row, height_row, calculate_button, rows)

ft.app(target=main)

程式碼說明:

執行結果:

Source Code: https://github.com/lcc728/flet/blob/main/ex_bmi_calculator.py

Exit mobile version