修改代码实现点击OK按钮打印LineEdit内容,解决属性不存在报错
解决点击OK按钮打印LineEdit内容的属性错误问题
嘿,这个错误我太熟啦!问题出在LineEdit部件的作用域上——你大概率是在类的__init__方法里把它定义成了局部变量,没有用self.前缀,导致点击按钮时的回调方法找不到这个textbox属性。
错误原因拆解
当你在initUI里直接写textbox = QLineEdit(self)时,这个textbox只是该方法内的局部变量,方法执行完就会被销毁,类的其他方法(比如按钮的回调函数)根本访问不到它,所以才会抛出'Example' object has no attribute 'textbox'的错误。
修改后的完整代码
import sys from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QPushButton, QVBoxLayout class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # 关键:用self.textbox将LineEdit转为实例属性 self.textbox = QLineEdit(self) ok_btn = QPushButton("OK", self) ok_btn.clicked.connect(self.on_ok_click) layout = QVBoxLayout() layout.addWidget(self.textbox) layout.addWidget(ok_btn) self.setLayout(layout) self.show() def on_ok_click(self): # 现在可以正常获取输入内容并打印 input_content = self.textbox.text() print("你输入的内容是:", input_content) if __name__ == "__main__": app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
核心修改点
- 给LineEdit部件加上
self.前缀:把textbox变成类的实例属性,这样类内所有方法都能通过self访问到它。 - 在按钮回调方法中,通过
self.textbox.text()获取输入的文本内容,再执行打印操作。
这样修改后,点击OK按钮就能正常打印你在LineEdit里输入的内容啦!
内容的提问来源于stack exchange,提问作者barciewicz
相关产品推荐
相关产品推荐

