如何使用Python .get()将字符串转换为float?

时间:2014-08-15 10:51:28

标签: python python-3.x

所以这很简单,我确定我似乎无法弄明白。

使用Tk模块创建GUI,我有一个输入字段,需要浮点输入来进行数学运算。

目前我收到此错误

floatval1 = float(val1)
  

无法将字符串转换为float

代码部分如下所示:

val1 = entry1.get()
val2 = entry2.get()
floatval1 = float(val1)
floatval2 = float(val2)
formula12 = (((((((floatval1/100)*(floatval2)/100))*86.67)+bevel+44)*2.4)*1.1)
bevel = (((floatval1/100)*2)+((floatval2/100)*2))*3.5
glprice12 = formula12 + bevel

显然我已经尝试将输入字段,条目转换为浮点数,因此可以在此公式中使用。

我无法理解为什么不允许这样做,我们将非常感谢任何帮助。

亲切的问候,

3 个答案:

答案 0 :(得分:2)

您确定输入字段包含的字符串是有效数字吗?

也就是说,输入字段通常从空开始。如果您尝试将空字符串("")解析为数字,那么您将收到错误。 ""代表什么数字?

字段中的字符串可能不是有效数字,因此您应该正确编码以实现这种可能性。

例如

import tkMessageBox

...

# in your function
val1 = entry1.get()
val2 = entry2.get()
try:
    floatval1 = float(val1)
    floatval2 = float(val2)
except ValueError:
    message = "Either val1 ({!r}) or val2 ({!r}) is not a valid number".format(val1, 
        val2)
    print("Error!", message)
    tkMessageBox.showerror("Invalid Inputs", message)
    return # or reraise the error or something sensible
# continue rest of function as normal

答案 1 :(得分:1)

如果您的计算机上安装了PySide,则以下内容将创建一个符合您需要的对话框。

IMO,PySide比Tk更容易使用,你可以非常快速地创建这样的小应用程序,它们可以很好地工作。

enter image description here

from PySide import QtGui, QtCore
import sys

"""
This class just sets up the actual dialog widget, and puts everything in place. 
It was mostly just generated by Qt Designer & pyside-uic though, so there's 
no real need to understand it all.
"""
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(402, 182)
        self.gridLayout = QtGui.QGridLayout(Dialog)
        self.gridLayout.setObjectName("gridLayout")
        self.label_formula12 = QtGui.QLabel(Dialog)
        self.label_formula12.setObjectName("label_formula12")
        self.gridLayout.addWidget(self.label_formula12, 3, 0, 1, 2)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout.addWidget(self.buttonBox, 5, 0, 1, 2)
        self.label_v1 = QtGui.QLabel(Dialog)
        self.label_v1.setObjectName("label_v1")
        self.gridLayout.addWidget(self.label_v1, 0, 0, 1, 1)
        self.lineEdit_v1 = QtGui.QLineEdit(Dialog)
        self.lineEdit_v1.setObjectName("lineEdit_v1")
        self.gridLayout.addWidget(self.lineEdit_v1, 0, 1, 1, 1)
        self.label_v2 = QtGui.QLabel(Dialog)
        self.label_v2.setObjectName("label_v2")
        self.gridLayout.addWidget(self.label_v2, 1, 0, 1, 1)
        self.lineEdit_v2 = QtGui.QLineEdit(Dialog)
        self.lineEdit_v2.setObjectName("lineEdit_v2")
        self.gridLayout.addWidget(self.lineEdit_v2, 1, 1, 1, 1)
        self.label_bevel = QtGui.QLabel(Dialog)
        self.label_bevel.setObjectName("label_bevel")
        self.gridLayout.addWidget(self.label_bevel, 2, 0, 1, 2)
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 4, 0, 1, 2)
        self.label_v1.setBuddy(self.lineEdit_v1)
        self.label_v2.setBuddy(self.lineEdit_v2)

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle("Formula 12")
        self.label_formula12.setText("Formula 12")
        self.label_v1.setText("Value &1:")
        self.label_v2.setText("Vaule &2:")
        self.label_bevel.setText("Bevel")


"""
Here we add the actual functionality to the widgets in the dialog. The
functionality it simple, there are just a few differences from Tk, namely the
use of `signals` and `slots`. The 
"""
class MainWindow(QtGui.QDialog):
    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.ui.lineEdit_v1

        qDoubleValidator = QtGui.QDoubleValidator()

        self.ui.lineEdit_v1.setText("0.0")
        self.ui.lineEdit_v2.setText("0.0")

        """
        Here's the magic that forces the numbers in the `lineEdit`s to be 
        real numbers.
        """
        self.ui.lineEdit_v1.setValidator(qDoubleValidator)
        self.ui.lineEdit_v2.setValidator(qDoubleValidator)

        """
        Signals and Slots. The first set wait until editing is finished - i.e.
        when foucs leaves the box. The second set offer real time updating.        
        """
        #self.ui.lineEdit_v1.editingFinished.connect(self.updateValues)
        #self.ui.lineEdit_v2.editingFinished.connect(self.updateValues)

        self.ui.lineEdit_v1.textEdited.connect(self.updateValues)
        self.ui.lineEdit_v2.textEdited.connect(self.updateValues)

        self.updateValues()        

    def updateValues(self):
        try:
            self.value1 = float(self.ui.lineEdit_v1.text())
            self.value2 = float(self.ui.lineEdit_v2.text())

            self.bevel = self.calculateBevel()
            self.formula12 = self.calculateFormula12()

            self.ui.label_bevel.setText("Bevel = %10.5f" % self.bevel)
            self.ui.label_formula12.setText("Formula12 = %10.5f" % self.formula12)
        except ValueError:
            print "one of the values could not be cast to a float"

    def calculateBevel(self):
        return 3.5 * 2 * (self.value1 + self.value2) / 100

    def calculateFormula12(self):
        return 2.4 * 1.1 * (self.bevel + 44 + 86.67 * self.value1 * self.value2 / 10000)

def main():

    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()

    myapp.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

答案 2 :(得分:0)

最后出现错误的原因是因为浮点值是从创建时为空白的输入字段派生的。

浮点形式的空白字段不会转换为valueerror。

可以在Tkinter表单here

上创建验证规则

然而,在我的具体示例中,我将涉及浮点数的计算移动到按钮本身的代码块内,使得浮点值直到字段填充后才定义。

添加了另一个尝试除了块以处理输入的错误值。

谢谢所有帮助过的人,尤其是#34;"" Reza-S4" Dunes"和" barak manos"。