0

So I'm making a simple BMI calculator (really simple) and I'm trying to get the text boxes that have an input to change a label at the bottom that says the final answer. Problem is I can't get the label to display an actual answer.

I can get the program to print the answer in the command line but I can't update the value of the text in the label itself.

Below is my code. Thanks a bunch to whoever helps :^)

from tkinter import *
import tkinter

root = Tk()
root.title("BMI Calculator")
root.geometry("300x200")

name = StringVar()
height = DoubleVar()
weight = DoubleVar()
bmi2= DoubleVar()


name.set("Default")
weight.set(20)
height.set(2)
bmi2.set(0)

def calculate():
    global name
    global height
    global weight
    global bmi2
    bmi1= (weight.get() /height.get())
    bmi2= (bmi1/height.get())
    fnlname = print(name.get())
    fnlbmi = print(bmi2)


e= Entry(root, textvariable=height)
e.pack()
e2= Entry(root, textvariable=weight)
e2.pack()
e3= Entry(root, textvariable=name)
e3.pack()
b=Button(root, text="Calculate", command=calculate).pack()
l=Label(root, text=bmi2).pack()
root.mainloop()
Dhaval Asodariya
  • 558
  • 5
  • 19
Skyler
  • 33
  • 7

1 Answers1

0

You made 2 mistakes:

  1. You didn't assign the bmi2 variable to your label correctly:

    l=Label(root, text=bmi2).pack()
    

    This sets the label's text, but not the label's variable. The correct definition is

    l=Label(root, textvariable=bmi2).pack()
    
  2. You never update the bmi2 variable. You wrote

    bmi2= (bmi1/height.get())
    

    But that replaces the DoubleVar with a float number. You're rebinding bmi2 rather than mutating it. There are some posts that explain this in more detail, for example this one.

    The correct code is

    bmi2.set(bmi1/height.get())
    
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149