如何通过在PySide中按下按钮来更改标签

时间:2017-03-07 17:27:25

标签: python python-2.7 pyqt pyside qlabel

无法弄清楚出了什么问题。只需将标签文本从“默认标签”更改为“新标签01”即可。     来自PySide.QtGui import *

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

1 个答案:

答案 0 :(得分:0)

您必须通过在label1方法中添加myWidgetself__init__实例的属性:

    self.label1 = QLabel('Default label')
    layout.addWidget(self.label1)