【问题标题】:Tkinter entry widget floatTkinter 条目小部件浮动
【发布时间】:2015-03-01 13:50:45
【问题描述】:

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

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

这是一小段代码:

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 还是很陌生。

【问题讨论】:

  • 忘了提到 p1、p2、t1 和 t2 有条目小部件和其他按钮,但我没有包括所有这些以使问题更简洁。以防万一不是很明显。

标签: python tkinter widget tkinter-entry


【解决方案1】:

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

p1 = float(entry_p1.text())

这是我犯过的很多错误。继续编码。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多