简体   繁体   中英

Python runs an int(x.get())/float(x.get()) command before the user can input anything into an entry [Python 3.6, Tkinter]

Title pretty much says it all, doing a project for school, there's an entry field that allows the user to input two values but it seems to run the float command before they can enter anything and gives an error. I have tried using int() instead and gives a base 10 error instead. I even tried moving the math section to another function thinking that it was trying to turn it into an int while creating the window. Full error code:

  File "main.py", line 111, in <module>
    app = Application(root)
  File "main.py", line 9, in __init__
    self.height_and_weight()
  File "main.py", line 29, in height_and_weight
    weight = float(weightEntry.get())
ValueError: could not convert string to float:

My code:

from tkinter import *

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.height_and_weight()


    def clear_window(self, option):
        for widget in self.winfo_children():
            if option == 1:
                widget.grid_forget()
            else:
                widget.destroy()


    def height_and_weight(self):
        Label(self, text = "Enter your height in inches").grid(column = 0, sticky = W)
        heightEntry = Entry(self)
        heightEntry.grid(column = 0, sticky = W)

        Label(self, text = "Enter your weight in pounds").grid(column = 0, sticky = W)
        weightEntry = Entry(self)
        weightEntry.grid(column = 0, sticky = W)

        weight = float(weightEntry.get())
        height = float(heightEntry.get())

        weight *= .45
        height *= .025
        height **= 2
        self.BMI = 10
        self.BMI = weight / height
        Button(self, text = "Continue", command = self.health_assessment).grid(column = 0, sticky = W)


    def health_assessment(self):
        self.clear_window(1)
        if self.BMI < 18.5: # Underweight
            Label(self, text = "You are underweight").grid(column = 0, sticky = W)
            Label(self, text = "It is recommended that you gain some healthy weight.").grid(column = 0, sticky = W)
            Label(self, text = "Would you like information on:").grid(column = 0, sticky = W)

            choice = IntVar()
            Radiobutton(self, text = "Building muscle mass", variable = choice, value = 1).grid(column = 0, sticky = W)

            Radiobutton(self, text = "Increasing good calories in your diet", variable = choice, value = 2).grid(column = 0, sticky = W)

            Radiobutton(self, text = "No thanks", variable = choice, value = 3).grid(column = 0, sticky = W)

            if choice == 1:
                link = "http://virtualfitnesstrainer.com/muscle-building/bodybuilding/how-to-gain-weight-and-muscle-%E2%80%93-even-if-you-are-under-weight/"
            elif choice == 2:
                link = "https://www.everydayhealth.com/weight/how-to-gain-healthy-weight.aspx"
            else:
              link = ""

            Label(self, text = link).grid(column = 0, sticky = W)
            Button(self, text = "EXIT").grid(column = 0, sticky = W)

        elif self.BMI >= 18.5 and self.BMI < 25: # Normal weight
            Label(self, text = "You are a normal weight.").grid(column = 0, sticky = W)
            Label(self, text = "Great job staying healthy!").grid(column = 0, sticky = W)
            Button(self, text = "EXIT", command = root.destroy()).grid(column = 0, sticky = W)

        elif self.BMI >= 25 and self.BMI > 30: # Overweight
            Label(self, text = "You are overweight.").grid(column = 0, sticky = W)

            Label(self, text = "It is recommended that you shed a few pounds.").grid(column = 0, sticky = W)

            Label(self, text = "Would you like information on:").grid(column = 0, sticky = W)

            link = ""
            if option:
                link = "https://www.runtastic.com/blog/en/burn-more-calories-during-workout/"
            else:
                link = "https://www.healthline.com/nutrition/35-ways-to-cut-calories"

            Label(self, text = link).grid(column = 0, sticky = W)
            Button(self, text = "EXIT",command = root.destroy()).grid(column = 0, sticky = W)

        else: # Obese
            Label(self, text = "You are obese.").grid(column = 0, sticky = W)

            Label(self, text = "You are at an unhealthy weight that increases your chances of health problems.").grid(column = 0, sticky = W)

            Label(self, text = "Please select one of the following:").grid(column = 0, sticky = W)

            link = ""
            if option:
                link = "https://www.runtastic.com/blog/en/burn-more-calories-during-workout/"
            else:
                link = "https://www.healthline.com/nutrition/35-ways-to-cut-calories"

            Label(self, text = link).grid(column = 0, sticky = W)
            if option or not option:
                Button(self, text = "EXIT",command = root.destroy()).grid(column = 0, sticky = W)  

root = Tk()
root.title("Health Assessment Program")
w = 500
h = 500
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
app = Application(root)
root.mainloop()

You're calling self.height_and_weight() (which then executes weight = float(weightEntry.get()) ) in Application.__init__ , so it's executed here:

root.geometry('%dx%d+%d+%d' % (w, h, x, y))
app = Application(root)  # RIGHT HERE (and the error message tells you that)
root.mainloop()

So this is run before any Tkinter code. You should have a button that runs your function when pressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM