2017-03-07 145 views
0

無法弄清楚什麼是錯的。只需要將標籤文本從「默認標籤」更改爲「新標籤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 

回答

0

你必須在__init__方法前面加上self使label1myWidget實例的屬性:

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

是的。完美的作品。謝謝。 – user1682929

相關問題