PyQt5 – 创建一个数字时钟

PyQt5 – 创建一个数字时钟

在这篇文章中,我们将看到如何使用PyQt5创建一个数字时钟,这个数字时钟基本上会以24小时的格式告诉人们当前时间。

为了创建一个数字时钟,我们必须做以下 工作。

  1. 创建一个垂直布局
  2. 创建显示当前时间的标签,把它放在布局中,并把它对准中心。
  3. 创建一个QTimer对象。
  4. 给QTimer对象添加动作,这样每隔1秒就会调用动作方法。
  5. 在动作方法中获取当前时间并在标签的帮助下显示该时间。

下面是实现方法。

# importing required librarie
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QVBoxLayout, QLabel
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QTimer, QTime, Qt
 
 
class Window(QWidget):
 
    def __init__(self):
        super().__init__()
 
        # setting geometry of main window
        self.setGeometry(100, 100, 800, 400)
 
        # creating a vertical layout
        layout = QVBoxLayout()
 
        # creating font object
        font = QFont('Arial', 120, QFont.Bold)
 
        # creating a label object
        self.label = QLabel()
 
        # setting center alignment to the label
        self.label.setAlignment(Qt.AlignCenter)
 
        # setting font to the label
        self.label.setFont(font)
 
        # adding label to the layout
        layout.addWidget(self.label)
 
        # setting the layout to main window
        self.setLayout(layout)
 
        # creating a timer object
        timer = QTimer(self)
 
        # adding action to timer
        timer.timeout.connect(self.showTime)
 
        # update the timer every second
        timer.start(1000)
 
    # method called by timer
    def showTime(self):
 
        # getting current time
        current_time = QTime.currentTime()
 
        # converting QTime object to string
        label_time = current_time.toString('hh:mm:ss')
 
        # showing it to the label
        self.label.setText(label_time)
 
 
# create pyqt5 app
App = QApplication(sys.argv)
 
# create the instance of our Window
window = Window()
 
# showing all the widgets
window.show()
 
# start the app
App.exit(App.exec_())

输出 : pyqt-create-digital-watch

代码解释

  1. 这段代码从导入所需的库开始。
  2. 然后,它创建了一个名为Window的类,并用init()方法将其初始化。
  3. 接下来,代码将主窗口的几何尺寸分别设置为100×100像素和800×400像素。
  4. 然后,它创建了一个垂直布局对象,用于在屏幕上按顺序垂直排列部件。
  5. 下一步是使用PyQt5库中的QFont类创建字体对象,然后使用 PyQt5 库中的QLabel类创建一个标签对象。
  6. 最后,代码将一个标签添加到布局中,并将其对齐方式设置为Qt的对齐中心选项,然后将标签的字体设置为Arial字体,大小为120点的粗体风格。
  7. 这段代码是一个简单的例子,说明如何创建一个窗口并显示它。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程