QTimer、QThread
QTimer显示时间
QTimer
''' 动态显示当前时间 QTimer QThread 多线程:用于同时完成多个任务 ''' from PyQt5.QtWidgets import QWidget, QPushButton, QApplication, QListWidget, QGridLayout, QLabel from PyQt5.QtCore import QTimer, QDateTime import sys class ShowTime(QWidget): def __init__(self, parent=None): super(ShowTime, self).__init__(parent) self.setWindowTitle("动态显示当前时间") self.label = QLabel('显示当前时间') self.startBtn = QPushButton('开始') self.endBtn = QPushButton('结束') layout= QGridLayout() self.timer = QTimer() self.timer.timeout.connect(self.showTime) layout.addWidget(self.label,0,0,1,2) layout.addWidget(self.startBtn,1,0) layout.addWidget(self.endBtn,1,1) self.startBtn.clicked.connect(self.startTimer) self.endBtn.clicked.connect(self.endTimer) self.setLayout(layout) def showTime(self): time = QDateTime.currentDateTime() timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd") self.label.setText(timeDisplay) def startTimer(self): self.timer.start(1000) self.startBtn.setEnabled(False) self.endBtn.setEnabled(True) def endTimer(self): self.timer.stop() self.startBtn.setEnabled(True) self.endBtn.setEnabled(False) if __name__ == "__main__": app = QApplication(sys.argv) form = ShowTime() form.show() sys.exit(app.exec_())
QTimer让窗口定时关闭
''' 让程序定时关闭 QTimer.singleShot ''' import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * if __name__ == '__main__': app = QApplication(sys.argv) label = QLabel('<font color=red size=140><b>Hello World,窗口在5秒后自动关闭!</b></font>') label.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint) label.show() QTimer.singleShot(5000,app.quit) sys.exit(app.exec_())
使用线程类QThread编写计数器
''' 使用线程类(QThread)编写计数器 QThread def run(self): while True: self.sleep(1) if sec == 5: break; QLCDNumber WorkThread(QThread) 用到自定义信号 ''' import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * sec = 0 class WorkThread(QThread): timer = pyqtSignal() # 每隔1秒发送一次信号 end = pyqtSignal() # 计数完成后发送一次信号 def run(self): while True: self.sleep(1) # 休眠1秒 if sec == 5: self.end.emit() # 发送end信号 break self.timer.emit() # 发送timer信号 class Counter(QWidget): def __init__(self, parent=None): super(Counter, self).__init__(parent) self.setWindowTitle("使用线程类(QThread)编写计数器") self.resize(300, 120) layout = QVBoxLayout() self.lcdNumber = QLCDNumber() layout.addWidget(self.lcdNumber) button = QPushButton('开始计数') layout.addWidget(button) self.workThread = WorkThread() self.workThread.timer.connect(self.countTime) self.workThread.end.connect(self.end) button.clicked.connect(self.work) self.setLayout(layout) def countTime(self): global sec sec += 1 self.lcdNumber.display(sec) def end(self): QMessageBox.information(self,'消息','计数结束',QMessageBox.Ok) def work(self): self.workThread.start() if __name__ == "__main__": app = QApplication(sys.argv) form = Counter() form.show() sys.exit(app.exec_())
天道酬勤 循序渐进 技压群雄