Home » Create a digital clock using PyQt5

Create a digital clock using PyQt5

In this article, we create a digital clock using the PyQt5 libraries

Code

We start by importing the required libraries.
We then create a class called Window and initializes it with __init__() method.
Next, the code sets the geometry of the main window to 100×100 pixels and 800×400 pixels.
It then creates a vertical layout object which is used for arranging the required widgets vertically on the screen.
The next step is to create a font object using the QFont class
The next step is to create a label object using the QLabel class
The code adds a label to the layout before setting the font of the label.
Create a QTimer object.
Add an action to the QTimer object so that after every 1 second action the method gets called.
Inside the method we then get the current time and show that time in the label.

# importing required libraries
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__()
        # create the main window
        self.setGeometry(100, 100, 800, 400)
        # creating a vertical layout
        layout = QVBoxLayout()
        # creating font object
        font = QFont('Arial', 120, QFont.Bold)
        # crate the label
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(font)
        layout.addWidget(self.label)
        self.setLayout(layout)
        # create a timer object
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        # update the timer every second
        timer.start(1000)
 

    def showTime(self):
        # getting current time
        current_time = QTime.currentTime()
        # convert QTime object to string
        label_time = current_time.toString('hh:mm:ss')
        self.label.setText(label_time)
 
 
# create app
App = QApplication(sys.argv)
window = Window()
window.show()
 
# start the app
App.exit(App.exec_())

 

Link

https://github.com/programmershelp/maxpython/blob/main/PyQt5/pyqt5digitalclock.py

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More