AttributeError:“myWindow”对象没有属性“txtFirstName”

2024-09-30 22:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个简单的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_())

以下是我收到的错误消息:

Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\PyQTTests\src\pyqttests.py", line 36, in clicked self.txtFirstName.text(), self.txtLastName.text())) AttributeError: 'myWindow' object has no attribute 'txtFirstName'


Tags: totextselfappdefsysqtguiclicked
1条回答
网友
1楼 · 发布于 2024-09-30 22:23:48

问题出在__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)

相关问题 更多 >