定时器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