PyQt5基礎學習-QTimer(時間計時器) 1.QDateTime.currentDateTime(顯示當前時間) 2.QTimer().start(設置時間的間隔) 3.QTimer().stop(停止時間計時器)


動態顯示時間, 點擊按鈕開始時間計時器, 每隔一秒顯示一次時間

 showTime.py

"""
動態顯示當前時間

QTimer
QThread

多線程: 用於同時完成多個任務
"""
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QTimer, QDateTime

class ShowTime(QWidget):

    def __init__(self):
        super(ShowTime, self).__init__()
        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)
    main = ShowTime()
    main.show()

    sys.exit(app.exec_())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM