Imagine there are chickens and rabbits in a cage. You know the total number of heads and the total number of legs. How many chickens and rabbits are there?
雞免同籠 : https://www.george.tw/2022/04/14/python-%E9%9B%9E%E5%85%94%E5%90%8C%E7%B1%A0/
# Flet - Chicken and Rabbit in a Cage 雞免同籠
# 2024-08-27
# https://github.com/lcc728/flet/blob/main/ex_chicken_rabbit.py
import flet as ft
def main(page: ft.Page):
page.title = "雞兔同籠"
def calculate(e):
try:
H = int(H_input.value)
F = int(F_input.value)
C = int((4 * H - F )/2)
R = H - C
result.value = f"雞有 {C} 隻,兔子有 {R} 隻"
except ValueError:
result.value = "請輸入數字"
page.update()
H_input = ft.TextField(label="雞兔同籠共幾隻", icon=ft.icons.CRUELTY_FREE)
F_input = ft.TextField(label="一共有幾隻腳", icon=ft.icons.QUESTION_MARK)
calculate_button = ft.ElevatedButton(text="計算", on_click=calculate)
result = ft.Text()
page.add(
H_input,
F_input,
calculate_button,
result
)
ft.app(target=main)
整個程式很簡單,只用到:
- 2 個 textfield : H_input 使用者在這個地方輸入雞和兔的總和。,F_input 輸入腳的總數
- 1 個 button : 按下按鈕時,呼叫 calculate 開始計算雞和兔分別的數量,執行後返回結果給 result
- 1 個 text : result 透 calculate 中的 page.update() 負責顯示結果
執行結果:
SourceCode: https://github.com/lcc728/flet/blob/main/ex_chicken_rabbit.py