定時器的操作方法有兩種:
方法一:利用每個對象包含的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_())
天子驕龍