python - 无法从 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:
我不知道为什么我会收到这个错误。好像我所做的一切都很好。我感谢任何和所有的帮助!提前致谢!
解决方案
首先,您尝试将空字符串转换为浮点整数,因为当您 get() 输入框的内容时,它仅在创建后的几毫秒内没有给用户足够的时间来输入他们的偏好
您需要做的是创建它以及一个提交按钮,单击该按钮时,将获取输入框的值,您可以在其中使用以下代码进行进一步检查:
try:
float(entry1.get())
except ValueError:
#do something when failed
这应该有帮助
推荐阅读
- java - com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:无法创建到数据库服务器的连接
- css - 用于表单的 Bootstrap 4 d-print 类
- ember.js - 如何从模型中的函数访问模型实例?
- c++ - 当 SWIG 中包含命名空间时,如何 %include C++ 标头?
- haskell - Haskell foldl Monad 绑定
- linux - 如何在不打开 Linux 浏览器的情况下从命令行执行 URL
- c++ - 如何使用 GetFinalPathNameByHandle 来解析指向本地目录的符号链接?
- python - Python httplib2 - 无法获得成功响应
- python - 使用正则表达式获取匹配字符串的百分比
- hyperledger-fabric - 将新对等方加入频道时出现管理员身份错误