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()
- Import Libraries: Import
tkinterfor GUI andstrftimefromtimefor formatting time. - Create Tkinter Window: Create a
Tkinstance and set the window title and size. - Define
update_timeFunction: This function updates the current time and sets the label text accordingly. It usesstrftimeto format the time string as ‘HH:MMAM/PM’.
- Create Time Label: Create a
Labelwidget (time_label) to display the time. Customize the font, background color, and foreground color as desired. - Call
update_timeFunction: Initially callupdate_time()to set the initial time and start the updating process. - 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
Labelwidget (time_label). - To change the update frequency, adjust the
after()method inupdate_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.