Make a clock using TKinter in python

Creating a simple digital clock using Tkinter in Python involves updating the time periodically and displaying it on a label widget. Here’s a step-by-step example to create a basic digital clock:

import tkinter as tk
from time import strftime

# Create a Tkinter window
root = tk.Tk()
root.title('Digital Clock')
root.geometry('300x150')

# Function to update time
def update_time():
    current_time = strftime('%H:%M:%S %p')
    time_label.config(text=current_time)
    time_label.after(1000, update_time)  # Update every second (1000 milliseconds)

# Create a label widget for the time display
time_label = tk.Label(root, font=('calibri', 40, 'bold'), background='purple', foreground='white')
time_label.pack(anchor='center')

# Call the update_time function initially
update_time()

# Start the Tkinter event loop
root.mainloop()
  1. Import Libraries: Import tkinter for GUI and strftime from time for formatting time.
  2. Create Tkinter Window: Create a Tk instance and set the window title and size.
  3. Define update_time Function: This function updates the current time and sets the label text accordingly. It uses strftime to format the time string as ‘HH:MM

    AM/PM’.

  4. Create Time Label: Create a Label widget (time_label) to display the time. Customize the font, background color, and foreground color as desired.
  5. Call update_time Function: Initially call update_time() to set the initial time and start the updating process.
  6. Start Tkinter Event Loop: Start the Tkinter event loop using root.mainloop(), which listens for events (like button clicks, window resizing) and keeps the GUI responsive.

Running the Code:

Save the code in a file (e.g., digital_clock.py) and run it using Python. You should see a window displaying the current time that updates every second.

Customization:

  • You can customize the font, colors, and size of the clock by modifying the parameters in the Label widget (time_label).
  • To change the update frequency, adjust the after() method in update_time() (currently set to 1000 milliseconds, i.e., 1 second).

This example provides a basic digital clock. Depending on your needs, you can extend it further with features like date display, time zone support, or a more elaborate GUI layout.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top