0

嗨,我很难让字符串变成花车。我试图让我的输入文本将输入转换为浮点数,以便我可以计算 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()
4

2 回答 2

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))
于 2012-10-29T01:00:48.823 回答
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)
于 2018-03-29T11:44:49.320 回答