import tkinter as tk import tkinter as ttk from tkinter import messagebox class BIMView(tk.Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.body_weight = tk.DoubleVar() self.height = tk.DoubleVar() self.bmi = tk.StringVar() lbl_body_weight = ttk.Label(self, text="体重(kg):") entry_body_weight = ttk.Entry(self, textvariable=self.body_weight) lbl_height = ttk.Label(self, text="身高(m):") entry_body = ttk.Entry(self, textvariable=self.height) btn_claculate = ttk.Button(self, text="计算", command=self.on_calculate) lbl_bmi = ttk.Label(self, textvariable=self.bmi, font=("Microsoft Yahei", 64), wraplength=480) lbl_body_weight.grid(row=0, column=0, sticky=tk.W) entry_body_weight.grid(row=0, column=1, sticky=(tk.W + tk.E)) lbl_height.grid(row=0, column=2, sticky=(tk.W + tk.E)) entry_body.grid(row=0, column=3, sticky=(tk.W + tk.E)) btn_claculate.grid(row=0, column=4, sticky=tk.E) lbl_bmi.grid(row=1, column=0, columnspan=5) self.columnconfigure(1,weight=1) self.columnconfigure(3,weight=1) def on_calculate(self): try: bmi = self.body_weight.get() / (self.height.get() ** 2) print(bmi) self.bmi.set(f"{bmi:.1f}") except Exception as e: print(e) messagebox.showinfo(title="%s "%str(e),message=str(e)) class BMIApplication(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.title("BMI 计算器") self.geometry("640x180") self.resizable(width=False, height=False) BIMView(self).grid(sticky=(tk.E + tk.N + tk.W + tk.S)) self.columnconfigure(0,weight=1) if __name__ == "__main__": app = BMIApplication() app.mainloop()