使用 PyQt5 创建一个数字时钟


在这篇博客中,我们将使用 PyQt5 创建一个简单的数字时钟。

效果

在这里插入图片描述

代码解析

定义时钟类

class ClockWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Digital Clock')
        self.setGeometry(100, 100, 400, 200)

        self.initUI()

初始化界面

def initUI(self):
    layout = QVBoxLayout()

    self.label = QLabel(self)
    self.label.setAlignment(Qt.AlignCenter)
    self.label.setStyleSheet("font-size: 48px;")

    layout.addWidget(self.label)

    container = QWidget()
    container.setLayout(layout)
    self.setCentralWidget(container)

    timer = QTimer(self)
    timer.timeout.connect(self.showTime)
    timer.start(1000)

    self.showTime()

  • 创建一个 QVBoxLayout 布局。
  • 创建一个 QLabel 控件用于显示时间。
  • 设置标签居中对齐。 使用 setStyleSheet 方法设置标签字体大小为 48 像素。
  • 将标签添加到布局中。
  • 创建一个容器 QWidget,将布局设置为该容器的布局,并将容器设置为主窗口的中央控件。
  • 创建一个 QTimer,每秒触发一次 timeout 事件,连接到 showTime 方法。 调用 showTime 方法显示当前时间。

显示时间

def showTime(self):
    current_time = QTime.currentTime().toString('hh:mm:ss')
    self.label.setText(current_time)

完整代码

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PyQt5.QtCore import QTimer, QTime, Qt

class ClockWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Digital Clock')
        self.setGeometry(100, 100, 400, 200)

        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        self.label = QLabel(self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("font-size: 48px;")

        layout.addWidget(self.label)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)

        self.showTime()

    def showTime(self):
        current_time = QTime.currentTime().toString('hh:mm:ss')
        self.label.setText(current_time)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ClockWindow()
    window.show()
    sys.exit(app.exec_())

  • 15
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

立秋6789

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值