首页 文章

Tkinter条目小部件浮动

提问于
浏览
3

我一直在编写一个tkinter应用程序,它从多个条目小部件中获取浮点数,然后在计算中使用浮点数生成一个浮点数,然后可以在适当的标签中显示 .

当我运行应用程序时,我得到'ValueError:无法将字符串转换为float:'并且我不能在任何计算中使用浮点数 .

这是代码的一小部分:

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)

我怎么能让程序接受输入的数字是浮点数然后在计算中使用它?

如果答案显而易见,我很抱歉,我是编程和使用tkinter的新手 .

2 回答

  • 0

    “ValueError:”表示您输入的值未被理解 . 输入数字时,您知道它是一个数字,但计算机将其作为字符串输入 . 尝试:

    p1 = float(entry_p1.text())
    

    我犯了很多错误 . 继续编码 .

  • 0

    如果您问题中的代码是您的实际代码,则问题出现是因为您尝试在用户有机会输入任何数据之前转换条目小部件中的值 . 数据为空(空字符串),python不知道如何将空字符串转换为浮点数 .

相关问题