Search code examples
pythonpyqtpyqt5qlineeditqpushbutton

Print LineEdit text on a button press


How do I alter the following code to make it print whatever is written in line edit widget when 'OK' button is pressed? The current version returns "'Example' object has no attribute 'textbox'" error.

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_())

`


Solution

  • if you want that a variable can be accessed in all parts of the class as in your case is the button_clicked method you must make it a member of the class for it you must use self when you create it.

    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