如何通过在PySide中按下按钮来更改标签
问题描述:
无法弄清楚什么是错的。只需要将标签文本从“默认标签”更改为“新标签01”即可。 从PySide.QtGui进口*如何通过在PySide中按下按钮来更改标签
class myWidget(QWidget):
def __init__(self):
super(myWidget, self).__init__()
layout = QVBoxLayout(self)
label1 = QLabel('Default label')
layout.addWidget(label1)
button = QPushButton('Change')
layout.addWidget(button)
button.clicked.connect(self.newlabel)
def newlabel(self):
print 'ACTION1'
self.label1.setText('New label 01')
print 'ACTION2'
app = QApplication([])
window = myWidget()
window.show()
app.exec_()
这是我在pycharm运行后得到
C:\Python27\python.exe D:/OneDrive/Projects/Personal/Tutorials/Python/CGScripting/PySide/simpleWidget.py
ACTION1
Traceback (most recent call last):
File "D:/OneDrive/Projects/Personal/Tutorials/Python/CGScripting/PySide/simpleWidget.py", line 32, in newlabel
self.label1.setText('New label 01')
AttributeError: 'myWidget' object has no attribute 'label1'
Process finished with exit code 0
答
你必须在__init__
方法前面加上self
使label1
您myWidget
实例的属性:
self.label1 = QLabel('Default label')
layout.addWidget(self.label1)
是的。完美的作品。谢谢。 – user1682929