当按下“OK”(确定)按钮时,如何更改以下代码,使其打印在line edit widget中写入的内容?当前版本返回“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_())
`
如果您希望在类的所有部分都可以访问变量,就像在您的情况下使用button\u 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