点击上方右侧蓝字 ● 关注捷创源科技
一、定时器基本使用
周期性的进行某种操作,PyQt5就提供了一个定时器QTimer来实现这种操作
from PyQt5.QtCore import QTimer
首先需要引入QTimer模块
self.timer = QTimer(self) #初始化一个定时器self.timer.timeout.connect(self.operate) #计时结束调用operate()方法self.timer.start(1000) #设置计时间隔并启动,1秒
然后实例化一个QTimer对象,将timeout信号连接到operate()信号槽,start(1000)表示设定时间间隔为1秒,并且启动
这里注意:connect中operate方法千万不要加括号,否则会出错
def operate(self):#具体操作
将想要实现的操作写在方法中即可。
self.timer.stop() #停止计时器
停止计时器
二、实例:
1.按照教程PyCharm PyQt5创建主窗口详细教程,先创建PyQt5主对话框
2.在主界面添加一个lable控件和三个pushButton按钮,三个按钮添加消息槽函数。

3.main.py主代码:
"""python主文件"""# -*- coding: utf-8 -*-import sysfrom PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidgetfrom PyQt5.QtCore import QTimerimport MyQTMainForm # 导入MyQTMainForm.py文件class MyPyQTMainForm(QMainWindow, MyQTMainForm.Ui_MainWindow):"""主界面"""def __init__(self):"""初始化"""super(MyPyQTMainForm, self).__init__()self.setupUi(self)self.num = 0 # 初始化self.timer = QTimer(self) # 初始化一个定时器self.timer.timeout.connect(self.operate) # 计时结束调用operate()方法def center(self):"""定义一个函数使得窗口居中显示"""# 获取屏幕坐标系screen = QDesktopWidget().screenGeometry()# 获取窗口坐标系size = self.geometry()newLeft = (screen.width() - size.width()) 2newTop = (screen.height() - size.height()) 2self.move(int(newLeft), int(newTop))def operate(self):"""定时器定时时间到,操作处理"""self.num += 1strTime = str(self.num)self.label.setText(strTime)def start(self):"""计时开始"""self.timer.start(1000) # 设置计时间隔并启动def reset(self):"""复位"""self.num = 0self.label.setText(str(self.num))def stop(self):"""计时停止"""self.timer.stop() # 计时停止"""=====================================主函数====================================="""if __name__ == '__main__':app = QApplication(sys.argv)# 创建主窗口对象myPyMainForm = MyPyQTMainForm()# 主窗口显示在屏幕中间myPyMainForm.center()# 禁止最大化按钮# myPyMainForm.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)# 禁止拉伸窗口大小# myPyMainForm.setFixedSize(myPyMainForm.width(), myPyMainForm.height())# 显示主界面myPyMainForm.show()sys.exit(app.exec_())
4.编译运行

关注上面微信公众号“捷创源科技”,每天获取技术干货,让我们一起成长!
文章转载自捷创源科技,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




