簡體   English   中英

使用Tkinter的Python BMI程序

[英]Python BMI program using Tkinter

我剛開始使用Tkinter,到目前為止還沒有太多問題。 我遇到的主要問題是,我應該在程序中使用tk__init __(self),它可以計算出一切。 但是,當我運行該程序時,我得到的是兩個彈出框,而不僅僅是1個。我還試圖拉伸主框,以使其完全顯示標題。 這是我的代碼:

from Tkinter import *

class App(Tk):
    def __init__(self):
        self.root = Tk()
        self.root.title("BMI Calculator")
        Tk.__init__(self)


        # Sets a label and entry field into the window for weight, height in
        # feet, and height in inches
        self.label = Label(self.root, text="Enter your weight in pounds.").pack()
        self.lbs = StringVar()
        Entry(self.root, textvariable=self.lbs).pack()

        self.label = Label(self.root, text="Enter your height in feet.").pack()
        self.feet = StringVar()
        Entry(self.root, textvariable=self.feet).pack()

        self.label = Label(self.root, text="Enter your height in inches.").pack()
        self.inches = StringVar()
        Entry(self.root, textvariable=self.inches).pack()

        # Sets a button and label to click and calculate BMI
        self.buttontext = StringVar()
        Button(self.root, textvariable=self.buttontext, command=self.calculate).pack()
        self.buttontext.set("Calculate")

        # Sets bmi_num to a StringVar so that when it is changed, the label will
        # update
        self.bmi_num = StringVar()
        Label(self.root, textvariable=self.bmi_num).pack()

        # Same thing here
        self.bmi_text = StringVar()
        Label(self.root, textvariable=self.bmi_text).pack()

        self.root.mainloop()

    def calculate(self):
        # Retrieves all necessary information to calculate BMI
        weight = float(self.lbs.get())
        feet = float(self.feet.get())
        inches = float(self.inches.get())
        height = (feet*12)+inches
        bmi = float((weight*703)/(height**2))
        # Updates the status label
        self.bmi_num.set("Your BMI is %.2f" % bmi)
        if bmi < 18.5:
            self.bmi_text.set("You are underweight")
        if 18.5 <= bmi < 25:
            self.bmi_text.set("You are normal")
        if 25 <= bmi < 30:
            self.bmi_text.set("You are overweight")
        if 30<= bmi > 30:
            self.bmi_text.set("You are obese")

App()

任何更好地編寫此建議或僅解決此問題的建議都將是不錯的。 謝謝。

似乎您在這里混淆了繼承和封裝。 您的App類是從Tk繼承的,這意味着它是Tk。 但是,您還將Tk對象封裝在App內,並將其分配給self.root。 因此,您有了App,它是Tk的子類,封裝了App.root,它也是Tk。

您實際上是在self.root Tk實例上構建GUI,但隨后還要調用Tk.__init__(self) ,這將初始化一個空白的Tk對象(因此是第二個窗口)。 您需要選擇一種方法或另一種方法。 (1)不要繼承Tk,不要調用Tk.__init__(self) ,而只使用self.root,或者(2)根本不要創建self.root對象,請調用Tk.__init__(self) ,並且只需在當前使用self.root任何地方使用self self.root

請注意,這似乎是我所教課程的一項家庭作業。 如果您想將此示例用作自己的示例,請注意兩點。

  • 代碼有一些問題,所以復制不是最好的東西
  • TA和我非常清楚,此代碼在線,因此您可能會破產

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM