# Python學習筆記
## tkinter+function應用
Tkinter 程式視窗設計的BMI計算程式
$$BMI=\frac{體重(kg)}{身高(m)^2}$$
```mermaid
graph TD;
輸入身高體重-->求出BMI;
求出BMI-->體重過輕;
求出BMI-->健康體位;
求出BMI-->體位異常;
```
:::success
$$BMI \lt18.5,體重過輕$$
:::

:::info
$$18.5 \le BMI\lt24,健康體位$$
:::

:::warning
$$24 \le BMI\lt27,過重$$
:::

:::success
$$27 \le BMI\lt30,輕度肥胖$$
:::

:::info
$$30 \le BMI\lt35,中度肥胖$$
:::

:::warning
$$35 \le BMI,重度肥胖$$
:::

```python=
import tkinter as tk
from tkinter.ttk import LabelFrame
from tkinter import messagebox
root = tk.Tk() # 建立 tkinter 視窗物件
root.title('BMI計算') # 設定標題
root.configure(background='#faa732')
width = 600
height = 400
x = 400
y = 350
root.geometry(f'{width}x{height}+{x}+{y}') # 定義視窗的尺寸和位置
root.minsize(150, 200) # 設定視窗最小為 200x200
root.maxsize(600, 800) # 設定視窗最大為 500x500
root.resizable(False, False) # 設定 x 方向和 y 方向都不能縮放
H=tk.StringVar()
W=tk.StringVar()
#BMI計算函式
def BMI():
h=eval(H.get())
w=eval(W.get())
bmi=w/(h/100)**2
if bmi>=35:
health="重度肥胖"
elif bmi>=30:
health="中度肥胖"
elif bmi>=27:
health="輕度肥胖"
elif bmi>=24:
health="過重"
elif bmi>=18.5:
health="標準體位"
else:
health="過輕"
print('BMI={:.4f} {}'.format(bmi,health))
messagebox.showinfo('你的BMI值為','BMI={:.4f} {}'.format(bmi,health))
#身高
heightlabel = tk.Label(root,
text='身高',
font=('',20,''),
fg='#c42100',
bg='#919e98',
relief='groove',
padx=10,pady=10) # 建立 label 標籤
heightlabel.place(x=20,y=20)
# 加入視窗中
weightlabel = tk.Label(root,
text='體重',
font=('',20,''),
fg='#c42100',
bg='#919e98',
relief='groove',
padx=10,pady=10) # 建立 label 標籤
weightlabel.place(x=20,y=120) # 加入視窗中
# tk.Label(root, text='hello world').pack() # 如果不使用變數,也可使用這種做法
btn = tk.Button(root,
text='BMI計算',
fg='#c42100',
bg='#919e98',
font=('',20,''),
command=BMI)
btn.place(x=200,y=220)
entryheight=tk.Entry(root,
fg='#c42100',
bg='#919e98',
font=('',20,''),
textvariable=H)
entryheight.place(x=150,y=20)
entryweight=tk.Entry(root,
fg='#c42100',
bg='#919e98',
font=('',20,''),
textvariable=W)
entryweight.place(x=150,y=120)
btn.place(x=200,y=220)
root.mainloop() # 放在主迴圈中
```
# 心得
透過這一次的練習,我深深體會到自己在程式設計方面的不足,幸虧有這次的練習,才能夠讓我學到更多稱是設計的新知識。