Build a Digital Clock With Python

PythonPythonBeginner
Practice Now

Introduction

In this project, we will create a digital clock application using Python and the Tkinter library. This clock will display both the current time and date, and it will allow the user to toggle between 12-hour and 24-hour time formats. We will split the code into multiple steps, starting with installing the required libraries and ending with running the project.

👀 Preview

Alt text

🎯 Tasks

In this project, you will learn:

  • How to install the necessary libraries for building a digital clock with Python.
  • How to set up the project by creating the Python script and importing the required libraries.
  • How to define a function to update and display the current time and date.
  • How to create a function to toggle between 12-hour and 24-hour time formats.
  • How to create the main application window and configure GUI styles.
  • How to create and place the GUI components on the main window.
  • How to start the clock by calling the necessary functions and running the main GUI loop.

🏆 Achievements

After completing this project, you will be able to:

  • Install libraries using pip, the Python package manager.
  • Use the Tkinter library to create graphical user interfaces in Python.
  • Format and display time and date in Python.
  • Customize the appearance of GUI components using themed styles.
  • Create buttons with different text and functionality.
  • Run a Python script and execute a main GUI loop.

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) tkinter(("`Tkinter`")) -.-> tkinter/ThemedWidgetsGroup(["`Themed Widgets`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") tkinter/ThemedWidgetsGroup -.-> tkinter/button("`Clickable Button`") tkinter/ThemedWidgetsGroup -.-> tkinter/frame("`Container Frame`") tkinter/ThemedWidgetsGroup -.-> tkinter/label("`Text Label`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/scope("`Scope`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") subgraph Lab Skills python/comments -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/with_statement -.-> lab-298851{{"`Build a Digital Clock With Python`"}} tkinter/button -.-> lab-298851{{"`Build a Digital Clock With Python`"}} tkinter/frame -.-> lab-298851{{"`Build a Digital Clock With Python`"}} tkinter/label -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/variables_data_types -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/booleans -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/conditional_statements -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/for_loops -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/tuples -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/function_definition -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/scope -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/importing_modules -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/using_packages -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/standard_libraries -.-> lab-298851{{"`Build a Digital Clock With Python`"}} python/data_collections -.-> lab-298851{{"`Build a Digital Clock With Python`"}} end

Install Required Libraries

Before we begin building our digital clock with Python, we need to ensure that we have the necessary libraries installed. In this step, we'll install the required libraries using pip, the Python package manager.

sudo apt-get install python3-tk -y
pip install ttkthemes

Here's what these libraries are for:

  • tkinter: This library provides the tools and components needed for creating graphical user interfaces (GUIs) in Python. It's a standard library for GUI development.
  • ttkthemes: This library allows us to use themed styles and customize the appearance of our Tkinter components to give our digital clock a visually appealing design.

You can install these libraries using the above commands in your terminal or command prompt. Once installed, you're ready to proceed with building the digital clock as outlined in the following steps.

Now, create a new Python file called digital_clock.py and open it in your preferred code editor.

cd ~/project
touch digital_clock.py

Setting Up the Project

First, let's set up the project by creating the necessary Python script and importing the required libraries.

## Import necessary libraries
import tkinter as tk
from tkinter import ttk
from ttkthemes import ThemedStyle
from time import strftime

In this step:

  • We import the tkinter library for creating the graphical user interface (GUI).
  • We import specific components (ttk, ThemedStyle) from tkinter for advanced styling.
  • We import the strftime function from the time module to format and display time.

Define the Time Display Function

Next, let's define a function to update and display the current time and date.

def time():
    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)

In this step:

  • We create a function called time() that updates the time and date labels.
  • The current_time_format variable determines whether to use a 24-hour or 12-hour time format based on the is_24_hour_format flag.
  • We use the strftime function to get the current time and date in the desired format.
  • The labels (label_time and label_date) are updated with the current time and date, respectively.
  • The label_time.after(1000, time) line schedules the time function to run every 1000 milliseconds (1 second) to continuously update the time.

Toggle Time Format

Let's create a function that allows the user to toggle between 12-hour and 24-hour time formats.

def toggle_time_format():
    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")

In this step:

  • We define a function called toggle_time_format() that toggles the is_24_hour_format flag between True and False.
  • The label on the time format button (time_format_button) is updated to display "12 Hour" or "24 Hour" based on the current format.

Create the Main Application Window

Now, let's create the main application window and set its title and dimensions.

root = tk.Tk()
root.title("Digital Clock")
root.geometry("400x250")

In this step:

  • We create the main application window using tk.Tk().
  • We set the window title to "Digital Clock".
  • The dimensions of the window are set to 400x250 pixels.

Configure GUI Styles

Configure the styles for the labels, buttons, and frames to customize the appearance of the clock.

style = ThemedStyle(root)
style.set_theme("plastik")
style.configure(
    "TLabel", foreground="#FF5733", background="#333333", font=("calibri", 48, "bold")
)
style.configure(
    "TButton", foreground="#FF5733", background="#333333", font=("calibri", 10, "bold")
)
style.configure("TFrame", background="#333333")

In this step:

  • We create a themed style for the GUI components to apply a consistent look and feel.
  • The label text color, background color, and font are customized.
  • The button text color, background color, and font are customized.
  • The frame background color is customized.

Create and Place GUI Components

Now, let's create and place the GUI components on the main window.

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()

is_24_hour_format = True
time_format_button = ttk.Button(
    frame, text="12 Hour", command=toggle_time_format, style="TButton"
)
time_format_button.pack(pady=20)

In this step:

  • We create a frame (frame) with the specified style and padding.
  • The frame is centered in the main window.
  • Two labels (label_time and label_date) are created to display the time and date.
  • An initial value of True is set for is_24_hour_format.
  • A button (time_format_button) is created with the text "12 Hour" and the toggle_time_format function is set as its command.
  • All components are packed and placed in the frame.

Start the Clock

Finally, let's start the clock by calling the time function and running the main GUI loop.

time()

root.mainloop()

In this step:

  • We call the time() function to initiate the clock.
  • The root.mainloop() method starts the main GUI loop, allowing the application to run and update in real-time.

Now, let's run the digital clock application.

cd ~/project
python digital_clock.py
Alt text

Summary

In this project, we've created a digital clock application using Python and Tkinter. We split the process into several steps, including setting up the project, defining functions for time display and format toggle, configuring GUI styles, creating GUI components, and running the clock application. This digital clock displays the current time and date and allows users to switch between 12-hour and 24-hour time formats.

Other Python Tutorials you may like