简体   繁体   English

如何在pyQt4 python中将QTextedit的输入转换为int

[英]How to convert QTextedit's input to int in pyQt4 python

I am fairly new to pyqt as i transitioned from tkinter.当我从 tkinter 过渡时,我对 pyqt 相当陌生。 i want to simply ask for two numbers then click the button "SUM" to add both numbers and present the output on the gui but i keep getting errors like "cant convert str to int" or sometimes it outputs nothing at all.我只想询问两个数字,然后单击“SUM”按钮将两个数字相加并在 gui 上显示输出,但我不断收到诸如“无法将 str 转换为 int”之类的错误,或者有时它根本不输出任何内容。 i feel i have to convert the input gotten from QTextedit to int or float but I've tried every possible way i know.我觉得我必须将从 QTextedit 获得的输入转换为 int 或 float 但我已经尝试了我知道的所有可能的方法。 what am i missing?我错过了什么?

code is below代码如下

import sys
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(400, 300)
        self.sum_button = QtGui.QPushButton(Form)
        self.sum_button.setGeometry(QtCore.QRect(10, 20, 75, 23))
        self.sum_button.setObjectName(_fromUtf8("sum_button"))
        self.sum_button.clicked.connect(self.action)

        self.text1 = QtGui.QTextEdit(Form)
        self.text1.setGeometry(QtCore.QRect(110, 10, 104, 71))
        self.text1.setObjectName(_fromUtf8("text1"))
        self.texxt1 = self.text1.toPlainText()

        self.text2 = QtGui.QTextEdit(Form)
        self.text2.setGeometry(QtCore.QRect(110, 140, 104, 71))
        self.text2.setObjectName(_fromUtf8("text2"))
        self.texxt2 = self.text2.toPlainText()

        self.clear = QtGui.QPushButton(Form)
        self.clear.setGeometry(QtCore.QRect(20, 140, 75, 23))
        self.clear.setObjectName(_fromUtf8("clear"))

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.clear, QtCore.SIGNAL(_fromUtf8("clicked()")), self.text2.clear)
        QtCore.QObject.connect(self.clear, QtCore.SIGNAL(_fromUtf8("clicked()")), self.text1.clear)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def action(self):
        self.tex = self.texxt1
        self.ij = self.texxt2
        self.l = self.tex + self.ij
        QtGui.QLabel(self.l,self)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.sum_button.setText(_translate("Form", "sum", None))
        self.clear.setText(_translate("Form", "clear", None))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_Form()
    ex.show()
    sys.exit(app.exec_())

You have this:你有这个:

self.texxt1 = self.text1.toPlainText()
# ...
self.texxt2 = self.text2.toPlainText()

And then, in your action handler, you have this:然后,在你的动作处理程序中,你有这个:

def action(self):
    self.tex = self.texxt1
    self.ij =  self.texxt2
    self.l = self.tex + self.ij
    QtGui.QLabel(self.l,self)

First, instead of trying to add the strings together, you need to convert the values to integers.首先,不是尝试将字符串相加,而是需要将值转换为整数。 Eg:例如:

total = int(self.texxt1) + int(self.texxt2)

You should check for exceptions, in case the inputs are not numeric.您应该检查异常,以防输入不是数字。

Then, you have this line in your handler:然后,您的处理程序中有这一行:

QtGui.QLabel(self.l,self)

This line creates a new label.此行创建一个新标签。 Instead of creating a new label, just take a pre-existing label in your GUI, and use it's setText method to show the result.无需创建新标签,只需在您的 GUI 中获取一个预先存在的标签,并使用它的setText方法来显示结果。 Eg:例如:

self.result_lbl.setText('{:,}'.format(total))

would display the result if you have a QLabel widget named result_lbl .如果您有一个名为result_lblQLabel小部件,则会显示结果。


Update更新

it still isn't outputting any result它仍然没有输出任何结果

The source of your problem is in these lines:您的问题的根源在于以下几行:

self.texxt1 = self.text1.toPlainText()
# ...
self.texxt2 = self.text2.toPlainText()

Notice that you're trying to get the contents of the QTextEdit s widgets during the UI's initialization, which is before the user has had a chance to enter anything.请注意,您试图在 UI 初始化期间获取QTextEdit小部件的内容,这是用户有机会输入任何内容之前。 You then try to compute using empty strings, which will never work.然后您尝试使用空字符串进行计算,这将永远无法工作。 (BTW, I think there're better widget choices, like QLineEdit ) (顺便说一句,我认为有更好的小部件选择,例如QLineEdit

Instead, you need to wait until the user has pressed the "Sum" button to do the work.相反,您需要等到用户按下“求和”按钮才能完成工作。 It's only at this point that it's reasonable to expect that the user would've entered something.只有在这一点上,可以合理地预期用户会输入某些内容。

For example, assuming you've added the result label result_lbl as I suggested, you'd be looking at something like:例如,假设您已按照我的建议添加了结果标签result_lbl ,您会看到如下内容:

def action(self):
    val1 = int(self.text1.toPlainText())
    val2 = int(self.text2.toPlainText())
    self.result_lbl.setText(_fromUtf8("<b>Result:</b> {:,}".format(val1 + val2)))

To add the QLabel , add this code snippet to your setupUi method:要添加QLabel ,请将此代码片段添加到您的setupUi方法中:

self.result_lbl = QtGui.QLabel(Form)
self.result_lbl.setGeometry(QtCore.QRect(20, 250, 75, 23))
self.result_lbl.setObjectName(_fromUtf8("result_lbl"))
self.result_lbl.setText(_fromUtf8("<b>Result:</b>"))

This was tested (using Python3) as a modification to the code you originally posted and it works.这已经过测试(使用 Python3)作为对您最初发布的代码的修改,并且可以正常工作。 If it doesn't work for you, you'll need to re-check your code.如果它不适合你,你需要重新检查你的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM