pyqt5-定时器

 

定时器的操作方法有两种:

方法一:利用每个对象包含的timerEvent函数

方法二:利用定时器模块    需要  from PyQt5.QtCore import QTimer

 

 

方法一:利用每个对象包含的timerEvent函数

 

from PyQt5.QtWidgets import QApplication, QWidget,QLabel,QPushButton
from PyQt5.QtCore import *
import sys

class myobject(QObject):
    def timerEvent(self, evt):   #重写对象的定时器函数
        print(evt,'1')

class win(QWidget): #创建一个类,为了集成控件
    def __init__(self):
        super(win, self).__init__()
        self.setWindowTitle('定时器的使用')
        self.resize(200,200)
        self.setup_ui()

    def setup_ui(self):
        #label = QLabel('标签控件', self)
        button = QPushButton('按钮', self)
        #label.move(10, 10)
        button.move(70, 150)
        button.pressed.connect(self.a)

        self.obj=myobject(self)
        self.id=self.obj.startTimer(1000)  #启动对象定时器函数
        #可以创建多个,每个返回的id不同
        #每个一定的时间,就会自动执行对象中的timerEvent函数
        #参数1 间隔时间,单位毫秒

    def a(self):
        print('按钮被点击了')
        self.obj.killTimer(self.id)  #释放对象的定时器函数

if __name__=='__main__':
    app=QApplication(sys.argv)  #创建应用
    window=win()
    window.show()
    sys.exit(app.exec_())

 

 

 

 

例子:在标签控件中显示从10到0的倒计时,显示0时停止

 


from PyQt5.QtWidgets import QApplication, QWidget,QLabel,QPushButton
from PyQt5.QtCore import *
import sys

class Label(QLabel):
def __init__(self,par):
super().__init__(par)
self.setText('10')
self.d=par

def timerEvent(self, evt) :
a=int(self.text())-1
if a == 0:
self.killTimer(self.d.id)
self.setText(str(a))

class win(QWidget): #创建一个类,为了集成控件
def __init__(self):
super(win, self).__init__()
self.setWindowTitle('定时器的使用')
self.resize(200,200)
self.setup_ui()

def setup_ui(self):
label = Label(self)
label.move(70, 20)
self.id=label.startTimer(1000)

if __name__=='__main__':
app=QApplication(sys.argv) #创建应用
window=win()
window.show()
sys.exit(app.exec_())

 

 

说明:label = Label(self)    在建立对象时,把self参数传给par

 

 

 方法二:利用定时器模块

 需要  from PyQt5.QtCore import QTimer  

 

from PyQt5.QtWidgets import QApplication, QWidget,QLabel,QPushButton
#from PyQt5.QtCore import *
from PyQt5.QtCore import QTimer
import sys

class win(QWidget): #创建一个类,为了集成控件
    def __init__(self):
        super(win, self).__init__()
        self.setWindowTitle('定时器的使用')
        self.resize(200,200)
        self.setup_ui()
        self.num=0

    def setup_ui(self):
        self.timer = QTimer(self)  # 初始化一个定时器
        self.timer.timeout.connect(self.operate)  # 每次计时到时间时发出信号
        self.timer.start(1000)  # 设置计时间隔并启动;单位毫秒

    def operate(self):
        self.num=self.num+1
        print(self.num)

if __name__=='__main__':
    app=QApplication(sys.argv)  #创建应用
    window=win()
    window.show()
    sys.exit(app.exec_())

 

 

 

 

 

 

 

 

天子骄龙

 

posted @ 2019-04-07 06:00  天子骄龙  阅读(5375)  评论(0编辑  收藏  举报