You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将QLineEdit输入转为float:汇率GUI程序报错求助

解决QLineEdit输入转float的ValueError问题

你遇到的核心问题很明确:你在界面初始化阶段就获取了QLineEdit的文本(此时是空字符串),并把这个固定值传给了点击事件的回调函数,而不是在按钮点击时实时读取用户的输入。同时,你传的货币选择值也是初始化时的固定值,用户切换下拉框后不会更新,这也会导致后续计算出错。

问题根源拆解

看这段代码:

# 在setupUi里执行,此时lineEdit是空的,currency1/currency2是初始选中值
currency1=self.comboBox.currentText()
currency2=self.comboBox_2.currentText()
input=self.lineEdit.text()
self.buton.clicked.connect(lambda: self.pressed(currency1, currency2,input))

这里的input、currency1、currency2都是初始化时的固定值,用户后续输入或切换下拉框都不会改变这些变量的值。点击按钮时用空字符串转float,自然触发ValueError。

修复方案

直接在pressed函数内部实时获取控件的当前状态,不要提前传固定值:

  1. 移除lambda里的参数传递
  2. 在pressed里直接读取lineEdit.text()、comboBox.currentText()和comboBox_2.currentText()
  3. 加上异常处理,防止用户输入非数字内容

修改后的完整代码

from PyQt5 import QtCore, QtGui, QtWidgets
import requests
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Exchange")
        Form.resize(850, 558)
        self.buton=QtWidgets.QPushButton("Calculate")
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(50, 60, 751, 351))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget_2)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout.addWidget(self.comboBox_2)
        self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget_2)
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout.addWidget(self.comboBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2.addWidget(self.buton)
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        self.verticalLayout_2.addStretch()
        self.label.setText("")
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)
        self.label.setText("Select currencies and enter the quantity")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        url = "http://data.fixer.io/api/latest?access_key=f79c72f7979f662b465bd28e40efa5cf&format=1"
        response = requests.get(url)
        self.json_data = response.json()
        kurlar=self.json_data["rates"].keys()
        for i in kurlar:
            self.comboBox.addItem(i)
            self.comboBox_2.addItem(i)
        index=self.comboBox.findText("TRY",QtCore.Qt.MatchFixedString)
        self.comboBox.setCurrentIndex(index)
        self.comboBox_2.setCurrentIndex(index)
        
        # 关键修改:不要提前传参数,直接连接到pressed函数
        self.buton.clicked.connect(self.pressed)

    def pressed(self):
        # 实时获取当前输入和选中的货币
        input_text = self.lineEdit.text()
        currency1 = self.comboBox.currentText()
        currency2 = self.comboBox_2.currentText()
        
        # 新增异常处理,防止非数字输入
        try:
            quantity = float(input_text)
            if currency1 == "EUR":
                converted = float(self.json_data["rates"][currency2]) * quantity
                self.label.setText(f"{quantity} EUR = {converted:.2f} {currency2}")
            else:
                rate = float(self.json_data["rates"][currency2]) / float(self.json_data["rates"][currency1])
                converted = quantity * rate
                self.label.setText(f"{quantity} {currency1} = {converted:.2f} {currency2}")
        except ValueError:
            self.label.setText("请输入有效的数字!")

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Currency Exchange Calculator"))
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

额外优化点

  • 用f-string代替format,代码更简洁
  • 给转换结果保留两位小数,显示更友好
  • 添加了输入非数字时的错误提示
  • 修改了窗口标题,更贴合功能

内容的提问来源于stack exchange,提问作者Berkay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 19:17:59