Question

I have a program that calculates a persons BMI after the user gives his height and weight.

I used variable.insert() to insert a value so the program doesn't have errors.

Is there any way to have the program start 'empty' without getting errors? Basically, I need it to not do anything until the calculate button is pressed.

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()
Was it helpful?

Solution

What you are doing right now is calling the output outright(& also by pressing the calculate button). What you need to do is call it only when the button is pressed

From init() remove self.calculate().

Now just remove all the insert statements. You don't need them anymore ;)

Edit:

As Joe suggested in his comment, you could also disable the button until all the fields are populated. You could do this by setting its state to disabled,like this:

self.calcBMI.config(state='disabled')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top