如何通过在 PySide 中按下按钮来更改标签
How to change label by pushing a button in PySide
不知道哪里出了问题。只需要将标签文本从 'Default label' 更改为 'New label 01'。
来自 PySide.QtGui 导入 *
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)
不知道哪里出了问题。只需要将标签文本从 'Default label' 更改为 'New label 01'。 来自 PySide.QtGui 导入 *
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)