Python: AttributeError: type object 'Ui_Form' has no attribute 'comboBox'
我有两个模块test.py和fill_combobox.py。 fill_combobox用于组合框中的默认值。 模块之间的通信仍然存在问题。
test.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from PyQt4 import QtCore, QtGui import fill_combobox 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(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.comboBox = QtGui.QComboBox(Form) self.comboBox.setGeometry(QtCore.QRect(160, 120, 51, 25)) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form","Form", None)) fill_combobox.fill() if __name__ =="__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_()) |
fill_combobox.py
1 2 3 4 | def fill(): import test for i in range(40): test.Ui_Form.comboBox.addItems(str(i)) |
在你的代码中:
1 | test.Ui_Form.comboBox.addItems(str(i)) |
正在访问类
1 2 3 4 | form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(form) form.show() |
您应该将该代码放在
如果您在许多地方这样做,最好将自定义小部件编写为:
1 2 3 4 | class MyWidget(QWidget, Ui_Form): def __init__(self, parent=None, ...): super(MyWidget, self).__init__(parent) self.setupUi(self) |
然后,您可以避免创建
1 2 | form = MyWidget() form.show() |