Python 使用sender()获取按钮文本始终返回错误—';非类型';对象没有属性';文本';

Python 使用sender()获取按钮文本始终返回错误—';非类型';对象没有属性';文本';,python,python-3.x,pyside2,Python,Python 3.x,Pyside2,使用Qt Designer创建了一个按钮,然后编码: #导入。。。 课堂测试: 定义初始化(自): qfile=qfile(“test.ui”) qfile.open(qfile.ReadOnly) qfile.close() self.ui=QUiLoader().load(qfile) self.ui.button.clicked.connect(self.buttonClicked) def按钮已锁定(自): 打印(self.ui.sender().text()) app=QApplica

使用Qt Designer创建了一个
按钮
,然后编码:

#导入。。。
课堂测试:
定义初始化(自):
qfile=qfile(“test.ui”)
qfile.open(qfile.ReadOnly)
qfile.close()
self.ui=QUiLoader().load(qfile)
self.ui.button.clicked.connect(self.buttonClicked)
def按钮已锁定(自):
打印(self.ui.sender().text())
app=QApplication([])
测试=测试()
test.ui.show()
app.exec()
单击按钮时,收到错误消息:

AttributeError: 'NoneType' object has no attribute 'text'
如何获取按钮文本?

如果调用的对象是异步调用的方法,那么sender()方法将返回发出信号的对象,并且只有该方法所属类的sender()才有效

考虑到上述情况,测试类必须是QObject,并且必须调用其sender()方法:

导入操作系统
从PySide2导入QtCore、QtWidgets、QtUiTools
当前目录=os.path.dirname(os.path.realpath(uu文件_uu))
类测试(QtCore.QObject):
定义初始化(自):
super()。\uuuu init\uuuuu()
filename=os.path.join(当前目录“test.ui”)
qfile=QtCore.qfile(文件名)
qfile.open(QtCore.qfile.ReadOnly)
qfile.close()
self.ui=qtutools.QUiLoader().load(qfile)
self.ui.button.clicked.connect(self.buttonClicked)
@QtCore.Slot()
def按钮已锁定(自):
打印(self.sender().text())
如果名称=“\uuuuu main\uuuuuuuu”:
app=QtWidgets.QApplication([])
测试=测试()
test.ui.show()
app.exec()