简体   繁体   中英

Tkinter entry widget float

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.

"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.

If the code in your question is your actual code, the problem comes because you are trying to convert the values in the entry widgets before the user has a chance to enter any data. The data is blank (an empty string), and python doesn't know how to convert an empty string to a floating point number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM