Tkinter entry widget float

user3925339 picture user3925339 · Mar 1, 2015 · Viewed 12.4k times · Source

I have been writing a tkinter application that takes floats from multiple entry widgets and then uses the floats in a calculation to produce a float that can then be displayed in an appropriate label.

When I run the application I get 'ValueError: could not convert string to float:' and I can't use the floats in any calculations.

This is a small chunk of the code:

def click_p1():
    p1 = entry_p1.get()

    try:
        p1 = float(p1)
        print (p1)

    except:
        print('Bad Input')


button_p1 = Button(text = 'ENTER', command = click_p1).grid(row = 2, column = 1, stick = 'nsew')
entry_p1 = Entry()
entry_p1.grid(row = 2, column = 0, stick = 'nsew')

p1 = float(entry_p1.get())
p2 = float(entry_p2.get())
t1 = float(entry_t1.get())
t2 = float(entry_t2.get())
a1 = math.log(p1) - math.log(p2)
b1 = t2 - t1
k1 = a1/b1
e2hours = -k1*(120 + t1)
p2hours += p1*math.exp(e2hours)
print(p2hours)

How could I get the program to accept the number entered is a float and then use it in the calculation?

I'm sorry if the answer is obvious, I'm quite new to programming and using tkinter.

Answer

Theodhori Dhiamanti picture Theodhori Dhiamanti · Mar 1, 2015

"ValueError:" means that the value you entering is not understood. When you enter a number you know it is a number but the computer takes it in as string. try:

p1 = float(entry_p1.text())

It is a mistake I have made a lot. Keep coding.