How to Build a Digital Clock in Python Tkinter
Creating a digital clock is an excellent way to learn the basics of GUI programming in Python. This guide will walk you through building a desktop application using the tkinter library. The application will feature a live clock, current date display, and a toggle button to switch between 12-hour and 24-hour formats.
Prerequisites
We will use tkinter for the interface and ttkthemes to improve the visual style.
First, install the necessary libraries:
sudo apt-get install python3-tk -y
pip install ttkthemes
Step 1: Imports and Setup
Create a file named digital_clock.py. We begin by importing tkinter, styling modules, and the time formatting function.
import tkinter as tk
from tkinter import ttk
from ttkthemes import ThemedStyle
from time import strftime
Step 2: Defining the Logic
We need two core functions:
time(): Fetches the current time, updates the label, and schedules itself to run again in 1 second.toggle_time_format(): Switches the global flag between 12-hour and 24-hour modes.
# Global variable to track format
is_24_hour_format = True
def toggle_time_format():
"""Switches between 12-hour and 24-hour formats."""
global is_24_hour_format
is_24_hour_format = not is_24_hour_format
# Update button text to show what the NEXT click will do
time_format_button.config(text="12 Hour" if is_24_hour_format else "24 Hour")
def time():
"""Updates the time and date labels every second."""
# Determine format string based on flag
# %H = 24h hour, %I = 12h hour, %p = AM/PM
current_time_format = "%H:%M:%S" if is_24_hour_format else "%I:%M:%S %p"
current_time = strftime(current_time_format)
current_date = strftime("%A, %B %d, %Y")
# Update labels
label_time.config(text=current_time)
label_date.config(text=current_date)
# Schedule next update in 1000ms (1 second)
label_time.after(1000, time)
Step 3: Creating the GUI
We initialize the main window, apply a theme, and arrange our widgets (Labels and Button) using a Frame.
# 1. Main Window Setup
root = tk.Tk()
root.title("Digital Clock")
root.geometry("400x250")
# 2. Styling
style = ThemedStyle(root)
style.set_theme("plastik") # Options: plastik, arc, radiance, etc.
# Configure colors and fonts
# 'TLabel' and 'TButton' are standard ttk widget class names
style.configure("TLabel", foreground="#FF5733", background="#333333")
style.configure("TButton", foreground="#FF5733", background="#333333", font=("calibri", 10, "bold"))
style.configure("TFrame", background="#333333")
# 3. Layout
# Create a central frame to hold everything
frame = ttk.Frame(root, style="TFrame", padding=20)
frame.place(relx=0.5, rely=0.5, anchor="center")
# Time Label (Large font)
label_time = ttk.Label(frame, font=("calibri", 48, "bold"))
label_time.pack()
# Date Label (Smaller font)
label_date = ttk.Label(frame, font=("calibri", 16))
label_date.pack()
# Toggle Button
time_format_button = ttk.Button(
frame,
text="12 Hour",
command=toggle_time_format,
style="TButton"
)
time_format_button.pack(pady=20)
Using label_time.after(1000, time) is crucial. Tkinter is event-driven; using a standard while True loop with time.sleep() would freeze the GUI. The .after() method registers a callback to run later without blocking the interface.
Step 4: Running the Application
Finally, trigger the first update manually and start the main event loop.
# Initial call to start the clock
time()
# Start the application
root.mainloop()
To run the application:
python digital_clock.py
Conclusion
You have successfully built a GUI application in Python.
tk.Tk()creates the main window.root.mainloop()keeps the window open and listening for events.widget.after()allows for periodic updates (like a clock tick) without freezing the UI.strftimeprovides flexible string formatting for time and date objects.