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 ttkthemesStep 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 strftimeStep 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.
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
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."""
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")
label_time.config(text=current_time)
label_date.config(text=current_date)
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.
root = tk.Tk()
root.title("Digital Clock")
root.geometry("400x250")
style = ThemedStyle(root)
style.set_theme("plastik") # Options: plastik, arc, radiance, etc.
style.configure("TLabel", foreground="#FF5733", background="#333333")
style.configure("TButton", foreground="#FF5733", background="#333333", font=("calibri", 10, "bold"))
style.configure("TFrame", background="#333333")
frame = ttk.Frame(root, style="TFrame", padding=20)
frame.place(relx=0.5, rely=0.5, anchor="center")
label_time = ttk.Label(frame, font=("calibri", 48, "bold"))
label_time.pack()
label_date = ttk.Label(frame, font=("calibri", 16))
label_date.pack()
time_format_button = ttk.Button(
frame,
text="12 Hour",
command=toggle_time_format,
style="TButton"
)
time_format_button.pack(pady=20)Step 4: Running the Application
Finally, trigger the first update manually and start the main event loop.
time()
root.mainloop()To run the application:
python digital_clock.pyConclusion
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.