开发一个界面少不了要用到定时器的功能,下面简单描述一个PyQt5的定时器Qtimer使用步骤:
下面在第一个程序的基础上添加定时器的内容:
(1) 导入依赖库
import sys
import time
from demo import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import QTimer
其中 Qtimer 即为 PyQt5 的定时器模块。
(2) 主函数
class Window(QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
super(Window,self).__init__(parent)
self.setupUi(self)
self.timer = QTimer() # 初始化定时器
self.timer.timeout.connect(self.time)
self.pushButton.clicked.connect(self.start)
def start(self):
self.timer.start(2 * 1000)
def time(self):
self.label.setText('{} s'.format(time.time()))
其中界面部分不再赘述,这里按钮(pushButton)所连接的函数为启动定时器的函数 (start),该定时器的单位为毫秒。
(3) 运行
if __name__ == "__main__":
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
运行结果如下