How to get value from entry(Tkinter), use it in formula and print the result it in label

2.3k views Asked by At
from Tkinter import *

top=Tk()

First Value A that user will input

A = Entry(top)
A.grid(row=1, column=1)

Second value B that user also inputs

B = Entry(top)
B.grid(row=1, column=2)

Calculation - Now I want to add those values (Preferably values with decimal points)

A1=float(A.get())
B1=float(B.get())
C1=A1+B1

Result - I want python to calculate result and show it to user when I input the first two values

C = Label(textvariable=C1)
C.grid(row=1, column=3)


top.mainloop()
1

There are 1 answers

4
Delioth On

First off, welcome to StackOverflow and nice job- your code does (mostly) everything you want it to do! The timing is just off- you create your objects and get the value, but the value hasn't been input by the user yet.

To solve that, you need to put your .get()'s in a function, and you should be using an actual text-variable that you set() after each one (if you just use C1=(float), you'll end up making new floats so the Label isn't pointing to the right one).

(setup... )
B.grid(...)
C1 = Tkinter.StringVar()
C = Label(textvariable=C1) # Using a StringVar will allow this to automagically update

def setC():
    A1=float(A.get())
    B1=float(B.get())
    C1.set(str(A1+B1))

Additionally, you need to set this function so it goes off more than just "immediately on running the program". The simple way to do this is to just have the function call itself .after() some time (in milliseconds).

def setC():
    # Body above
    top.after(1000, setC) # Call setC after 1 second, so it keeps getting called.

setC() # You have to call it manually once, and then it repeats.

The slightly more advanced and efficient way to update involves events and bindings (binding setC() to fire every time A1 or B1 is changed), but the writeup on that is long so I'll give you that tip and send you to some documentation on that. (Effbot is good tkinter documentation regardless)