PyQt5: Updating Label?

后端 未结 2 1632
孤街浪徒
孤街浪徒 2021-01-13 14:45

I\'m currently having trouble updating labels continuously, I have tried my different ways but either nothing happens or the program stops working. I have attached below pa

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-13 15:30

    Here is a small working example that should help you. QTimer is used for periodical calling the update_labelTime function.

    import sys
    from PyQt5.QtCore import QTimer, QTime
    from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
    
    class MyApp(QMainWindow):
        def __init__(self):
            super(MyApp, self).__init__()
    
            self.labelTime = QLabel()
            self.update_labelTime()
            self.setCentralWidget(self.labelTime)
    
            self.timer = QTimer()
            self.timer.timeout.connect(self.update_labelTime)
            self.timer.start(1000) # repeat self.update_labelTime every 1 sec
    
        def update_labelTime(self):
    
            time_str = "Current time: {0}".format(QTime.currentTime().toString())
            self.labelTime.setText(time_str)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MyApp()
        window.show()
        sys.exit(app.exec_())
    

    P.S. Don't forget to change the updating period in timer.start call

提交回复
热议问题