定時器QTimer


 

 1 import sys
 2 from PyQt5.QtCore import QTimer, Qt
 3 from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
 4 
 5 class Demo(QWidget):
 6     def __init__(self):
 7         super(Demo, self).__init__()
 8         self.label = QLabel('0', self)
 9         self.label.setAlignment(Qt.AlignCenter)
10 
11         self.step = 0
12 
13         self.timer = QTimer(self) #實例化定時器
14         self.timer.timeout.connect(self.update_func) #設置定時執行的函數
15 
16         self.ss_button = QPushButton('Start', self)
17         self.ss_button.clicked.connect(self.start_stop_func)
18 
19         self.v_layout = QVBoxLayout()
20         self.v_layout.addWidget(self.label)
21         self.v_layout.addWidget(self.ss_button)
22 
23         self.setLayout(self.v_layout)
24 
25     def start_stop_func(self):
26         if not self.timer.isActive():
27             #self.timer.isActive() 返回定時器是否激活 Ture激活
28             self.ss_button.setText('Stop')
29             self.timer.start(100) #啟動定時器,時間間隔100毫秒
30         else:
31             self.ss_button.setText('Start')
32             self.timer.stop() #停止定時器
33 
34     def update_func(self):
35         self.step += 1
36         self.label.setText(str(self.step))
37 
38 
39 if __name__ == '__main__':
40     app = QApplication(sys.argv)
41     demo = Demo()
42     demo.show()
43     sys.exit(app.exec_())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM