我刚开始使用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()
任何关于更好地写这个或只是解决这个问题的建议都会很棒。感谢。
答案 0 :(得分:3)
看起来你在这里混淆了继承和封装。您的App类继承自Tk,这意味着它是一个Tk。但是,您还要在App中封装Tk对象并将其分配给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
对象,调用{{1只需在当前使用Tk.__init__(self)
的任何地方使用self
。
答案 1 :(得分:0)
请注意,这似乎是我教授课程的家庭作业。如果您想将此示例用作自己的示例,请注意两件事。