AttributeError:'myWindow'对象没有属性'txtFirstName'

时间:2010-11-11 14:45:15

标签: python pyqt

我试图创建一个简单的PyQT4应用程序,让我在一个消息框中显示来自两个文本框的文本。它很直接,所以我确定我错过了一些非常小的东西。

感谢您的帮助。

import sys
from PyQt4 import QtGui, QtCore

class myWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        #The setGeometry method is used to position the control.
        #Order: X, Y position - Width, Height of control.
        self.resize(500,350)
        self.center()
        self.setWindowTitle("Sergio's QT Application.")
        self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png'))

        self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!')
        QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12))

        txtFirstName = QtGui.QLineEdit('', self)
        txtFirstName.setGeometry(35, 35, 150, 20)

        txtLastName = QtGui.QLineEdit('', self)
        txtLastName.setGeometry(35, 60, 150, 20)

        btnSubmit = QtGui.QPushButton('Say hello.', self)
        btnSubmit.setGeometry(340, 250, 150, 35)
        self.connect(btnSubmit, QtCore.SIGNAL("clicked()"), self.clicked)

        btnQuit = QtGui.QPushButton('Exit Application', self)
        btnQuit.setGeometry(340, 300, 150, 35)

        self.connect(btnQuit, QtCore.SIGNAL('clicked()'),
                    QtGui.qApp, QtCore.SLOT('quit()'))

    def clicked(self):
        QtGui.QMessageBox.about(self, "Just dropped by to say hi!", "Welcome to this tutorial %s %s!" % (
            self.txtFirstName.text(), self.txtLastName.text()))

    def center(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size =  self.geometry()
        self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)

app = QtGui.QApplication(sys.argv)
mainForm = myWindow()
mainForm.show()
sys.exit(app.exec_())

这是我收到的错误消息:

  

追踪(最近的呼叫最后):
  文件   &#34; C:\用户\ Sergio.Tapia \文件\的NetBeansProjects \ PyQTTests \ SRC \ pyqttests.py&#34 ;,   第36行,点击       self.txtFirstName.text(),self.txtLastName.text()))   AttributeError:&#39; myWindow&#39;对象有   没有属性&#39; txtFirstName&#39;

1 个答案:

答案 0 :(得分:3)

问题出在__init__,其中txtLastName已创建。它不是作为类成员创建的,而是作为__init__方法中的局部变量创建的。要使其成为类成员,您稍后可以参考,使用self.

    self.txtFirstName = QtGui.QLineEdit('', self)
    self.txtFirstName.setGeometry(35, 35, 150, 20)

    self.txtLastName = QtGui.QLineEdit('', self)
    self.txtLastName.setGeometry(35, 60, 150, 20)