This tutorial will guide you on how to create a simple digital clock using Python and Tkinter. The clock will display the current time and update in real-time. This program is great for beginners looking to understand GUI programming in Python.
Objective
The objective of this project is to create a digital clock that displays the current time in hours, minutes, and seconds, and updates every second. We will use Python’s Tkinter library to build the GUI for the clock.
Python Code
# Python Digital Clock using Tkinter import tkinter as tk import time # Function to update the time in the clock def time(): string = time.strftime('%H:%M:%S %p') # Get current time in hours, minutes, and seconds label.config(text=string) label.after(1000, time) # Update time every 1000 milliseconds (1 second) # Setting up the main window root = tk.Tk() root.title("Digital Clock") # Creating a label to display the time label = tk.Label(root, font=("calibri", 50, 'bold'), background='black', foreground='yellow') label.pack() # Start the clock time() # Run the Tkinter main loop root.mainloop()
Explanation of the Program Structure
The program consists of the following components:
- tkinter: A built-in Python module for creating graphical user interfaces (GUIs). We use this to create the clock’s window and update it with real-time time.
- time: A Python module that allows us to retrieve the current system time. We use the
strftime()
function to format the time as “hours:minutes:seconds AM/PM”. - Label: We create a label widget that displays the time in the Tkinter window. The text of the label updates every second.
- root.mainloop(): This function keeps the Tkinter window running and ensures that the clock continuously updates its display.
How to Run the Program
To run this program, you need to have Python installed on your system. The Tkinter library comes pre-installed with Python, so no additional installation is required.
Steps:
- Open your text editor or IDE (like VSCode or PyCharm) and create a new Python file (e.g.,
digital_clock.py
). - Copy and paste the Python code into the file.
- Save the file and open a terminal or command prompt in the directory where the file is saved.
- Run the file using the command:
python digital_clock.py
. - The digital clock will appear with the current time displayed in a window.
© 2025 Learn Programming. All rights reserved.