Modern Clock using PyQt
Below is an example of a modern clock using PyQt. This clock has a simple and intuitive design, and it also includes a feature to display the current date.
Code
python Copy code
import sys
from PyQt5.QtCore import QTimer, QTime, Qt
from PyQt5.QtGui import QFont, QColor
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout
class Clock(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setStyleSheet("background-color: #2b2b2b;")
self.time_label = QLabel()
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setStyleSheet("color: #ffffff;")
self.time_label.setFont(QFont('Arial', 64))
self.date_label = QLabel()
self.date_label.setAlignment(Qt.AlignCenter)
self.date_label.setStyleSheet("color: #ffffff;")
self.date_label.setFont(QFont('Arial', 24))
self.layout = QVBoxLayout()
self.layout.addStretch()
self.layout.addWidget(self.time_label)
self.layout.addWidget(self.date_label)
self.layout.addStretch()
self.container = QWidget()
self.container.setLayout(self.layout)
self.main_layout = QHBoxLayout()
self.main_layout.addStretch()
self.main_layout.addWidget(self.container)
self.main_layout.addStretch()
self.setLayout(self.main_layout)
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_time)
self.timer.start(1000)
self.update_time()
self.show()
def update_time(self):
current_time = QTime.currentTime().toString('hh:mm:ss')
self.time_label.setText(current_time)
from datetime import date
today = date.today().strftime("%A, %d %B %Y")
self.date_label.setText(today)
def main():
app = QApplication(sys.argv)
clock = Clock()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
How it Works
The Clock class inherits from QWidget and initializes the UI components.
The initUI method sets up the geometry, stylesheet, and layout of the clock.
Two QLabel widgets are used to display the time and date.
A QTimer is used to update the time every second.
The update_time method retrieves the current time and date, and updates the corresponding labels.
Features
Displays the current time in hours, minutes, and seconds.
Displays the current date in the format "Day, Date Month Year".
Has a modern design with a dark background and white text.
Updates the time every second.
Example Use Case
To run the clock, simply execute the main.py file. The clock will be displayed in a window, and it will continue to run until the window is closed.
Tips and Variations
To change the font or color of the time and date labels, modify the QFont and QColor objects used in the initUI method.
To add additional features, such as alarms or a stopwatch, you can create new methods and widgets, and integrate them into the existing layout.
To improve the performance of the clock, you can optimize the update_time method to reduce the number of operations performed every second.