import sys
import time
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget
from PyQt5.QtCore import QTimer
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.resize(600, 300)
self.setWindowTitle('创建按钮和按钮点击事件的例子')
self.timer = QTimer() # 初始化定时器
self.timer.timeout.connect(self.time)
#定义时间任务是一次性任务,当是一次性任务的时候self.timer.start()不需要指定时间
#self.timer.setSingleShot(True)
self.timer.start(1000)
self.pushbutton_开 = QPushButton("开启线程",self)
self.pushbutton_开.setGeometry(10,10,200,200)
self.pushbutton_关 = QPushButton("关闭线程",self)
self.pushbutton_关.setGeometry(210, 10, 200, 200)
self.pushbutton_开.clicked.connect(self.startTimer)
self.pushbutton_关.clicked.connect(self.stopTimer)
def time(self):
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
def stopTimer(self):
self.timer.stop()
def startTimer(self):
self.timer.start(1000)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
pyqt5 python 定时器的实现
于 2022-09-21 11:14:18 首次发布