我有一个程序可以在用户给出身高和体重后计算人体BMI。
我使用variable.insert()
插入一个值,因此程序没有错误。
有没有办法让程序开始“空”'没有错误?基本上,我需要它在按下计算按钮之前不做任何事情。
from Tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.height()
self.weigh()
self.output()
self.calculate()
def height(self):
Label(self, text = "Enter Height, feet").grid()
self.feet = Entry(self)
self.feet.grid(row = 0, column = 1)
self.feet.insert(0, "1")
Label(self, text = "Enter Height, inches").grid(row = 1, column = 0)
self.inches = Entry(self)
self.inches.grid(row = 1, column = 1)
self.inches.insert(0, "1")
def weigh(self):
Label(self, text = "Enter Weight").grid(row =2, column = 0)
self.weight = Entry(self)
self.weight.grid(row = 2, column = 1)
self.weight.insert(0, "1")
def output(self):
self.calcBMI = Button(self, text = "Calculate BMI")
self.calcBMI.grid(row = 6, columnspan = 2)
self.calcBMI["command"] = self.calculate
Label(self, text = "Body Mass Index").grid(row = 4, column = 0)
self.lblbmi = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblbmi.grid(row = 4, column = 1, sticky = "we")
Label(self, text = "Status").grid(row = 5, column = 0)
self.lblstat = Label(self, bg = "#fff", anchor = "w", relief = "groove")
self.lblstat.grid(row = 5, column = 1, sticky = "we")
def calculate(self):
ft = int(self.feet.get())
inch = int(self.inches.get())
ht = ft * 12 + inch
wt = int(self.weight.get())
bmi = (wt * 703) / (ht ** 2)
self.lblbmi["text"] = "%.2f" % bmi
if bmi > 30:
self.lblstat["text"] = "Obese"
elif bmi > 25:
self.lblstat["text"] = "Overweight"
elif bmi > 18.5:
self.lblstat["text"] = "Normal"
else:
self.lblstat["text"] = "Underweight"
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
答案 0 :(得分:0)
您现在正在做的是直接调用输出(也可以通过按下计算按钮)。您需要做的是仅在按下按钮时调用它
从init()
移除self.calculate()
。
现在只需删除所有insert
语句。你不再需要它们了;)
正如Joe在评论中建议的那样,你也可以禁用按钮,直到所有字段都被填充。您可以通过将state
设置为disabled
来完成此操作,如下所示:
self.calcBMI.config(state='disabled')