Creating a modern clock application using PyQt5 can be a fun project! Below is a complete example of a digital clock with a modern design. This clock will display the current time and update every second. Additionally, it will have a feature to change the background color randomly when you click on the clock.
Make sure you have PyQt5 installed. You can install it using pip if you haven't done so:
bash
pip install PyQt5
Here’s the code for the clock application:
python
import sys
import random
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtCore import QTimer, QTime, Qt
from PyQt5.QtGui import QFont, QColor, QPalette
class DigitalClock(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.startTimer()
def initUI(self):
self.setWindowTitle('Digital Clock')
self.setGeometry(100, 100, 300, 150)
# Set a modern font
self.label = QLabel(self)
self.label.setFont(QFont('Arial', 48))
self.label.setAlignment(Qt.AlignCenter)
# Layout
layout = QVBoxLayout()
layout.addWidget(self.label)
self.setLayout(layout)
# Set initial background color
self.setBackgroundColor()
# Connect mouse click event
self.label.mousePressEvent = self.changeBackgroundColor
self.show()
def startTimer(self):
timer = QTimer(self)
timer.timeout.connect(self.updateTime)
timer.start(1000) # Update every second
self.updateTime() # Initial call to display time immediately
def updateTime(self):
currentTime = QTime.currentTime()
self.label.setText(currentTime.toString('hh:mm:ss'))
def setBackgroundColor(self):
# Set a random background color
color = QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
palette = QPalette()
palette.setColor(QPalette.Window, color)
self.setPalette(palette)
def changeBackgroundColor(self, event):
self.setBackgroundColor()
if __name__ == '__main__':
app = QApplication(sys.argv)
clock = DigitalClock()
sys.exit(app.exec_())
Explanation of the Code:
Imports: We import necessary modules from PyQt5 and standard libraries.
DigitalClock Class: This class inherits from QWidget and sets up the clock.
initUI: Initializes the user interface, sets the window title, size, and font for the clock display.
startTimer: Sets up a timer that calls updateTime every second.
updateTime: Gets the current time and updates the label to display it.
setBackgroundColor: Sets a random background color for the window.
changeBackgroundColor: Changes the background color when the clock is clicked.
Main Block: Initializes the application and starts the event loop.
Running the Code:
To run the code, simply copy it into a Python file (e.g., digital_clock.py) and execute it. You should see a window displaying the current time, and clicking on it will change the background color randomly.
Feel free to modify the design, colors, or features to make it your own!