Creating an Analog Clock in Python using Tkinter

Posted by

To create an analog clock using Python’s Tkinter library, we can use a combination of Python code and HTML tags. In this tutorial, I will show you how to create a simple analog clock using Tkinter and Python.

First, make sure you have Python installed on your computer. You can download Python from the official website at https://www.python.org/. Once you have Python installed, open a new Python script and follow the steps below.

Step 1: Import the necessary libraries

import tkinter as tk
import math
import time

Step 2: Create the main window

root = tk.Tk()
root.title("Analog Clock")
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

Step 3: Create the clock background

canvas.create_oval(50, 50, 350, 350, width=2)

Step 4: Create the clock hands

hour_hand = canvas.create_line(200, 200, 200, 150, width=4)
minute_hand = canvas.create_line(200, 200, 200, 100, width=2)
second_hand = canvas.create_line(200, 200, 200, 50, fill="red", width=1)

Step 5: Create a function to update the clock hands

def update_clock():
    current_time = time.localtime()
    second = current_time.tm_sec
    minute = current_time.tm_min
    hour = current_time.tm_hour
    angle_second = math.radians((second / 60) * 360 - 90)
    angle_minute = math.radians((minute / 60) * 360 - 90)
    angle_hour = math.radians(((hour % 12) / 12) * 360 + ((minute / 60) * 30) - 90)
    x1_s = 200 + 50 * math.cos(angle_second)
    y1_s = 200 + 50 * math.sin(angle_second)
    x1_m = 200 + 40 * math.cos(angle_minute)
    y1_m = 200 + 40 * math.sin(angle_minute)
    x1_h = 200 + 30 * math.cos(angle_hour)
    y1_h = 200 + 30 * math.sin(angle_hour)
    canvas.coords(second_hand, 200, 200, x1_s, y1_s)
    canvas.coords(minute_hand, 200, 200, x1_m, y1_m)
    canvas.coords(hour_hand, 200, 200, x1_h, y1_h)
    root.after(1000, update_clock)

Step 6: Call the update_clock function to start the clock

update_clock()

Step 7: Run the main loop

root.mainloop()

That’s it! You have successfully created a simple analog clock using Python’s Tkinter library. You can further customize the clock by changing the size of the clock hands, the colors, or adding additional features such as a digital display of the current time.

I hope you found this tutorial helpful. Have fun creating your own analog clock with Python and Tkinter!