how to make clock in python with source code |learn more
This code to make clock
import tkinter as tk
import time
import math
class ModernAnalogClock:
def __init__(self, root):
self.root = root
self.root.title("Modern Analog Clock")
self.root.geometry("500x500")
self.root.resizable(False, False)
Canvas to draw the clock
self.canvas = tk.Canvas(root, width=500, height=500, bg="#121212")
self.canvas.pack()
Center coordinates and radius for the clock face
self.center_x, self.center_y = 250, 250
self.radius = 200
self.draw_clock_face()
Update the clock hands every second
self.update_clock()
def draw_clock_face(self):
Draw the clock border and subtle gradients
self.canvas.create_oval(50, 50, 450, 450, outline="#555555", width=6)
self.canvas.create_oval(245, 245, 255, 255, fill="#ff6347", outline="#ff6347") # center dot
Draw numbers around the clock face in a modern font
font_style = ("Fira Sans", 24, "bold")
for i in range(1, 13):
angle = math.radians(i * 30 - 90) # Calculate angle for each number
x = self.center_x + self.radius * 0.8 * math.cos(angle)
y = self.center_y + self.radius * 0.8 * math.sin(angle)
self.canvas.create_text(x, y, text=str(i), font=font_style, fill="#ffffff", tag="numbers")
def update_clock(self):
Get current time
current_time = time.localtime()
hours = current_time.tm_hour % 12
minutes = current_time.tm_min
seconds = current_time.tm_sec
Calculate angles for the hands
second_angle = math.radians(seconds * 6 - 90)
minute_angle = math.radians(minutes * 6 - 90)
hour_angle = math.radians((hours * 30) + (minutes * 0.5) - 90)
Clear previous hands
self.canvas.delete("hands")
Draw hour hand (bold and thick)
hour_hand_length = self.radius * 0.5
hour_x = self.center_x + hour_hand_length * math.cos(hour_angle)
hour_y = self.center_y + hour_hand_length * math.sin(hour_angle)
self.canvas.create_line(self.center_x, self.center_y, hour_x, hour_y, fill="#ff6347", width=8, tags="hands")
Draw minute hand (thin and modern)
minute_hand_length = self.radius * 0.7
minute_x = self.center_x + minute_hand_length * math.cos(minute_angle)
minute_y = self.center_y + minute_hand_length * math.sin(minute_angle)
self.canvas.create_line(self.center_x, self.center_y, minute_x, minute_y, fill="#00bfff", width=6, tags="hands")
Draw second hand (sleek and thin)
second_hand_length = self.radius * 0.9
second_x = self.center_x + second_hand_length * math.cos(second_angle)
second_y = self.center_y + second_hand_length * math.sin(second_angle)
self.canvas.create_line(self.center_x, self.center_y, second_x, second_y, fill="#ff4500", width=2, tags="hands")
Schedule the update_clock function to run every 1000 milliseconds (1 second)
self.root.after(1000, self.update_clock)
Run the clock
root = tk.Tk()
clock = ModernAnalogClock(root)
root.mainloop()