Analog Clock in Python

How to create a analog clock in python ?. Need littlebit of mathematical knowledge.
This is the place you can brush your knowledge in Sin and Cos(Mathemaical functions)
Learn more on “Polar coordinate system” and understand the fundementals.

Clock code has been developed and tested with below versions.

Operating System – Windows 7 64-bit
Python Version – 2.7.11

Packages require – Tkinter

# Author : Manoj
# Date : Jan-18-2016
# Purpose: Analog clock

#!/usr/bin/python
import Tkinter as tk
from math import sin,cos,pi
import time

class clock(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title(“sqlandplsql.com Clock”)
self.w = tk.Canvas(self, width=520, height=520, bg=”Cyan”, relief= “sunken”, border=10)
self.xcentre = 270
self.ycentre = 270
self.radius = 250
self.w.pack()
self.w.create_oval(20,20,520,520) #Main circle
self.w.pack()
self.w.create_oval(265,265,275,275,fill = “Black”) #Centre Dot
self.w.pack()
#Second Hand
self.w.create_line(0,0,0,0,fill = “Blue”, width=1,tags=”seconds”)
#Minute Hand
self.w.create_line(0,0,0,0,fill = “Blue”, width=2,tags=”minute”)
#Hour Hand
self.w.create_line(0,0,0,0,fill = “Blue”, width=4,tags=”hour”)

for i in range (0,12):
# Drawing hour co-orninates
self.degree = i*30
self.w.create_line((self.radius * cos((self.degree*pi)/180)) + 270,(self.radius * sin((self.degree*pi)/180)) + 270, (240 * cos((self.degree*pi)/180)) + 270, (240 * sin((self.degree*pi)/180)) + 270,fill = “Red”, width=6) #

for i in range (0,60):
# Drawing minute co-orninates
self.degree = i*6
self.w.create_line((self.radius * cos((self.degree*pi)/180)) + 270,(self.radius * sin((self.degree*pi)/180)) + 270, (240 * cos((self.degree*pi)/180)) + 270, (240 * sin((self.degree*pi)/180)) + 270 )
self.change_clock()

def change_clock(self):
hour = time.localtime()[3]
minute = time.localtime()[4]
seconds = time.localtime()[5]
# seconds
sec_degree = seconds*6 – 90
sec_angle = (sec_degree*pi)/180
sec_x = 270 + 230 * cos(sec_angle)
sec_y = 270 + 230 * sin(sec_angle)
self.w.coords(“seconds”, (self.xcentre,self.xcentre,sec_x,sec_y))
# minute
min_degree = minute*6 – 90
min_angle = (min_degree*pi)/180
min_x = 270 + 200 * cos(min_angle)
min_y = 270 + 200 * sin(min_angle)
self.w.coords(“minute”, (self.xcentre,self.xcentre,min_x,min_y))
#hour
hour_degree = hour*30 – 75
hour_angle = (hour_degree*pi)/180
hour_x = 270 + 170 * cos(hour_angle)
hour_y = 270 + 170 * sin(hour_angle)
self.w.coords(“hour”, (self.xcentre,self.xcentre,hour_x,hour_y))
self.after(1000, self.change_clock)

clock = clock()
clock.mainloop()

analog_clock_python

Note:- Above code may not work if you copy and paste exactly. Please format as per python intrepreter ( or Use any python IDLE )

Advertisements