Skip to main content
 首页 » 编程设计

python之属性错误 : 'Ui_Form' object has no attribute 'printHam_btn'

2024年11月01日30cyq1162

我开始使用 Qt 4.8.6 学习 QtDesigner (Python),我遵循这个教程:

https://www.youtube.com/watch?v=GLqrzLIIW2E

但它有时显示标题错误,有时显示 AttributeError:“Ui_Form”对象没有属性“printHam_btn”。有人可以告诉我我必须做什么或修复我的代码。

谢谢!

我知道这个问题已经发布在这个论坛上了,但我不知道我必须做什么。

代码:

from PyQt4 import QtCore, QtGui 
import sys 
 
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) 
 
    def setupUi(self, Form): 
        Form.setObjectName(_fromUtf8("Form")) 
        Form.resize(400, 300) 
        self.verticalLayout_2 = QtGui.QVBoxLayout(Form) 
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) 
        self.verticalLayout = QtGui.QVBoxLayout() 
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) 
        self.print_ham = QtGui.QPushButton(Form) 
        self.print_ham.setObjectName(_fromUtf8("print_ham")) 
        self.verticalLayout.addWidget(self.print_ham) 
        self.verticalLayout_2.addLayout(self.verticalLayout) 
 
        self.retranslateUi(Form) 
        QtCore.QMetaObject.connectSlotsByName(Form) 
 
    def retranslateUi(self, Form): 
        Form.setWindowTitle(_translate("Form", "Super ham", None)) 
        self.print_ham.setText(_translate("Form", "print ham", None)) 
        self.printHam_btn.clicked.connect(self.printHam) 
 
    def printHam(self): 
        print('Ham!') 
 
if __name__ == "__main__": 
    app = QtGui.QApplication(sys.argv) 
    main_window = Ui_Form() 
    main_window.show() 
    sys.exit(app.exec_()) 

请您参考如下方法:

问题在这里:

self.printHam_btn.clicked.connect(self.printHam) 

您以不同的方式调用您的 QPushButton 实例,因此您需要将此行更改为:

self.print_ham.clicked.connect(self.printHam)