我正在通过一个基本的PyQt设计器示例来创建一个脚本来接受两个数字并添加它们。
我将calc_ui.py
文件创建为:
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_CalculatorUI(object):
def setupUi(self, CalculatorUI):
CalculatorUI.setObjectName(_fromUtf8("CalculatorUI"))
CalculatorUI.resize(219, 134)
self.gridLayout = QtGui.QGridLayout(CalculatorUI)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.labelX = QtGui.QLabel(CalculatorUI)
self.labelX.setObjectName(_fromUtf8("labelX"))
self.gridLayout.addWidget(self.labelX, 0, 0, 1, 1)
self.lineEditX = QtGui.QLineEdit(CalculatorUI)
self.lineEditX.setObjectName(_fromUtf8("lineEditX"))
self.gridLayout.addWidget(self.lineEditX, 0, 1, 1, 1)
self.labelY = QtGui.QLabel(CalculatorUI)
self.labelY.setObjectName(_fromUtf8("labelY"))
self.gridLayout.addWidget(self.labelY, 1, 0, 1, 1)
self.lineEditY = QtGui.QLineEdit(CalculatorUI)
self.lineEditY.setObjectName(_fromUtf8("lineEditY"))
self.gridLayout.addWidget(self.lineEditY, 1, 1, 1, 1)
self.labelZ = QtGui.QLabel(CalculatorUI)
self.labelZ.setObjectName(_fromUtf8("labelZ"))
self.gridLayout.addWidget(self.labelZ, 2, 0, 1, 1)
self.lineEditZ = QtGui.QLineEdit(CalculatorUI)
self.lineEditZ.setReadOnly(True)
self.lineEditZ.setObjectName(_fromUtf8("lineEditZ"))
self.gridLayout.addWidget(self.lineEditZ, 2, 1, 1, 1)
self.buttonCalc = QtGui.QPushButton(CalculatorUI)
self.buttonCalc.setObjectName(_fromUtf8("buttonCalc"))
self.gridLayout.addWidget(self.buttonCalc, 3, 0, 1, 2)
self.retranslateUi(CalculatorUI)
QtCore.QMetaObject.connectSlotsByName(CalculatorUI)
def retranslateUi(self, CalculatorUI):
CalculatorUI.setWindowTitle(_translate("CalculatorUI", "Calculator", None))
self.labelX.setText(_translate("CalculatorUI", "X:", None))
self.labelY.setText(_translate("CalculatorUI", "Y:", None))
self.labelZ.setText(_translate("CalculatorUI", "Z:", None))
self.buttonCalc.setText(_translate("CalculatorUI", "Calculate", None))
我的main.py
是:
from PyQt4 import QtGui, QtCore
import sys
from calc_ui import Ui_CalculatorUI
class Calculator(Ui_CalculatorUI):
def __init__(self):
Ui_CalculatorUI.__init__(self)
#self.setupUi(self)
self.buttonCalc.clicked.connect(self.handleCalculate)
def handleCalculate(self):
x = int(self.lineEditX.text())
y = int(self.lineEditY.text())
self.lineEditZ.setText(str(x + y))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Calculator()
window.show()
sys.exit(app.exec_())
但是,我的错误是:
AttributeError: 'Calculator' object has no attribute 'buttonCalc'
即使我可以看到'buttonCalc'
文件中已定义calc_ui.py
。
我尝试了不同的语法,但在这里遇到了问题。