Python запускает команду int (x.get ()) / float (x.get ()), прежде чем пользователь сможет ввести что-либо в запись [Python 3.6, Tkinter] - PullRequest
0 голосов
/ 23 января 2020

Название в значительной степени говорит само за себя, выполняя проект для школы, есть поле ввода, которое позволяет пользователю вводить два значения, но кажется, что он запускает команду float, прежде чем он может что-либо ввести, и выдает ошибку. Я попытался использовать int () вместо этого и дает ошибку 10 базы вместо. Я даже пытался переместить математическую секцию в другую функцию, думая, что она пытается превратить ее в int при создании окна. Полный код ошибки:

  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:

Мой код:

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()

1 Ответ

2 голосов
/ 23 января 2020

Вы вызываете self.height_and_weight() (который затем выполняет weight = float(weightEntry.get())) в Application.__init__, поэтому он выполняется здесь:

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

Так что это выполняется перед любым кодом Tkinter. У вас должна быть кнопка, которая запускает вашу функцию при нажатии.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...