如何使计时器/时钟以秒为单位移动?

2024-09-29 00:12:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,当我运行它时,它不像时钟。它只返回一个字符串。但我想要的是以秒为单位的时间。谢谢你的帮助

def DateTime(self):
    dateandtime = QDialog()

    dateandtime.setWindowTitle("Date and Time")

    hbox = QHBoxLayout()

    datetime = QDateTime.currentDateTime()
    show = datetime.toString(Qt.DefaultLocaleLongDate)

    label = QLabel(show)
    label.setFont(QtGui.QFont("Arial", 10))
    hbox.addWidget(label)

    dateandtime.setLayout(hbox)

Tags: 字符串代码selfdatetimedefshow时间单位
1条回答
网友
1楼 · 发布于 2024-09-29 00:12:50

应该有一种更优雅的方式,但是可以找到一个计时器的例子:

from PyQt5.QtWidgets import QDialog, QHBoxLayout, QLabel, QApplication
from PyQt5.QtCore import QDateTime, Qt, QTimer
from PyQt5 import QtGui
import sys


class Dialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        datetime = QDateTime.currentDateTime()
        show = datetime.toString(Qt.DefaultLocaleLongDate)
        self.label = QLabel(show)
        self.DateTime()

    def DateTime(self):
        # dateandtime = QDialog()
        self.setWindowTitle("Date and Time")
        hbox = QHBoxLayout()
        self.label.setFont(QtGui.QFont("Arial", 10))
        hbox.addWidget(self.label)

        self.setLayout(hbox)

    def tick(self):
        datetime = QDateTime.currentDateTime().toString(Qt.DefaultLocaleLongDate)
        self.label.setText(datetime)


app = QApplication(sys.argv)
dialog = Dialog()
dialog.show()
timer = QTimer()
timer.timeout.connect(dialog.tick)
timer.start(1000)
app.exec_()

相关问题 更多 >