在按下按钮时打印LineEdit文本

问题描述 投票:1回答:1

如何更改以下代码,以使其在按“确定”按钮时打印在行编辑小部件中编写的内容?当前版本返回“'Example'对象没有属性'textbox'”错误。

import sys
from PyQt5.QtWidgets import QApplication, QWidget,QPushButton,QLineEdit, QHBoxLayout, QLabel, QVBoxLayout
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        label = QLabel('Keyword') 
        button = QPushButton('OK')
        textbox = QLineEdit()
        hbox = QHBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(textbox)
        hbox.addWidget(button)

        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        button.clicked.connect(self.button_clicked)

        self.setLayout(vbox)   

        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png')) 
        self.show()

    def button_clicked(self):
        print(self.textbox.text())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

`

python pyqt pyqt5 qlineedit qpushbutton
1个回答
1
投票

如果您希望在类的所有部分都可以访问变量,因为您的情况是button_clicked方法,则必须使其成为类的成员,因为在创建时必须使用self。

class Example(QWidget):
    [...]

    def initUI(self):    
        label = QLabel('Keyword') 
        button = QPushButton('OK')
        self.textbox = QLineEdit() # change this line
        hbox = QHBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(self.textbox) # change this line
© www.soinside.com 2019 - 2024. All rights reserved.