首页 > 解决方案 > 无法从 tkinter 条目将字符串转换为浮点数

问题描述

我基本上是在制作一个程序,用户可以输入不同的数字来获得特定形状的面积和周长答案。现在,我将 Tkinter 模块用于 GUI,出于某种原因,我什至没有输入字符串。我的代码如下(用于输入数字):

def perTriangle():
    tk.Label(window, text = "Enter in the Numbers: ", background = "white").place(x = 1115, y = 100)
    tk.Label(window, text = "Side 1: ", background = "white").place(x = 1115, y = 130)
    entry1 = tk.Entry(window)
    entry1.place(x = 1155, y = 130)
    tk.Label(window, text = "Side 2: ", background = "white").place(x = 1115, y = 160)
    entry2 = tk.Entry(window)
    entry2.place(x = 1155, y = 160)
    tk.Label(window, text = "Side 3: ", background = "white").place(x = 1115, y = 190)
    entry3 = tk.Entry(window)
    entry3.place(x = 1155, y = 190)
    btnA = tk.Button(mainFrame, text = "Enter", fg = "black", command = btnACommand).place(x = 1115, y = 220)
    num1 = float(entry1.get())
    num2 = float(entry2.get())
    num3 = float(entry3.get())

现在我无法在字符串和浮点数之间进行转换,因为我什至没有字符串(我认为是这种情况,但我可能错了)。我得到的错误信息是:

num1 = float(entry1.get())
ValueError: could not convert string to float: 

我不知道为什么我会收到这个错误。好像我所做的一切都很好。我感谢任何和所有的帮助!提前致谢!

标签: pythonpython-3.xuser-interfacetkintertkinter-entry

解决方案


首先,您尝试将空字符串转换为浮点整数,因为当您 get() 输入框的内容时,它仅在创建后的几毫秒内没有给用户足够的时间来输入他们的偏好

您需要做的是创建它以及一个提交按钮,单击该按钮时,将获取输入框的值,您可以在其中使用以下代码进行进一步检查:

try:
    float(entry1.get())
except ValueError:
    #do something when failed

这应该有帮助


推荐阅读