python tkinter bmi计算器

时间:2012-10-29 00:46:36

标签: python tkinter

嗨,我有麻烦让字符串变成花车。我试图获取我的输入文本以将输入转换为浮点数,以便我可以计算bmi。

from Tkinter import *
import tkMessageBox

class MyApp(object):
    def __init__(self):
        self.root = Tk()
        self.root.wm_title("bmi!")
        self.label = Label(self.root, text="Enter your height in box one and weight in box two",
        font=('Helvetica', 20))
        self.label.pack(padx=20,pady=10)
        self.labeltext = StringVar()
        self.labeltext.set("Another nice label!")
        Label(self.root, textvariable=self.labeltext).pack()
        self.entrytext = StringVar()
        Entry(self.root, textvariable=self.entrytext).pack()
        self.entrytext.trace('w', self.entry_changed)
        self.entrytext2 = StringVar()
        Entry(self.root, textvariable=self.entrytext2).pack()
        self.entrytext2.trace('w', self.entry_changed)



        self.root.mainloop()

    def entry_changed(self, a, b, c):
        s = self.entrytext.get()
        b=self.entrytext2.get()
        a=getdouble(s)
        d=getdouble(b)
        c=(a/(d**2))*703
        self.labeltext.set(c)


MyApp()

2 个答案:

答案 0 :(得分:1)

我会尝试使用float()代替getdouble(),并使用str()将结果转换回字符串。

您还需要处理输入的文字不是数字时出现的ValueError例外情况。

def entry_changed(self, a, b, c):
    try:
        mass = float(self.entrytext.get())
        height = float(self.entrytext2.get())
    except ValueError:
        self.labeltext.set("--")
        return

    c = (mass/(height**2))*703
    self.labeltext.set(str(c))

答案 1 :(得分:0)

尝试

  bmiheight=self.heightcm.get()
  print(bmiheight)
  bmiweight=self.weightkg.get()
  bmi= float((bmiweight)/((bmiheight / 100)**2))
  self.bmi = bmi
  print(bmi)
  self.label1=Label(self.master,text='Your BMI is %.2f' % bmi).grid(row=5,column=0)

  if bmi <= 18.5:
       self.label2=Label(self.master,text='This places you in the underweight group.',fg='blue').grid(row=6,column=0)
       totalindex = 'underweight'
       self.totalindex = totalindex
  elif bmi >18.5 and bmi <25:
       self.label3=Label(self.master,text='This places you in the healthy weight group.',fg='green').grid(row=6,column=0)
       totalindex = 'healthy'
       self.totalindex = totalindex
  elif bmi >= 25 and bmi < 30:
       self.label4=Label(self.master,text='This places you in the overweight group.',fg='orange').grid(row=6,column=0)
       totalindex = 'overweight'
       self.totalindex = totalindex
  elif bmi >=30:
       self.label5=Label(self.master,text='This places you in the obese group.',fg='red').grid(row=6,column=0)
       totalindex = 'obese'
       self.totalindex = totalindex

  if bmi >0 and bmi <999999999999999999999:
       self.button6=Button(self.master,text="Store Data",fg='red',command=self.dynamic_data_entry).grid(row=8,column=0)