Kodewick
Start learning →

Python Turtle Clock

The face is drawn once; the hands are wiped and drawn again every second, following your computer's clock.

Python Turtle Clock
The full code (60 lines)
import turtle
import datetime

screen = turtle.Screen()
screen.bgcolor("#eef2f5")
screen.tracer(0)
face = turtle.Turtle()
face.hideturtle()
face.penup()

# the face
face.goto(0, 0)
face.dot(400, "#2b2d42")
face.dot(370, "white")
# 60 marks, the hours longer and thicker
for i in range(60):
    face.goto(0, 0)
    face.setheading(90 - i * 6)
    face.forward(170)
    face.pendown()
    face.pensize(5 if i % 5 == 0 else 2)
    face.forward(-18 if i % 5 == 0 else -8)
    face.penup()
# the numbers
for h in range(1, 13):
    face.goto(0, 0)
    face.setheading(90 - h * 30)
    face.forward(130)
    face.sety(face.ycor() - 12)
    face.write(str(h), align="center", font=("Arial", 20, "bold"))

hands = turtle.Turtle()
hands.hideturtle()


def hand(angle, length, width, color):
    hands.penup()
    hands.goto(0, 0)
    hands.setheading(90 - angle)
    hands.pendown()
    hands.pencolor(color)
    hands.pensize(width)
    hands.forward(length)


def tick():
    now = datetime.datetime.now()
    hands.clear()
    hand((now.hour % 12 + now.minute / 60) * 30, 90, 9, "#2b2d42")
    hand((now.minute + now.second / 60) * 6, 135, 6, "#2b2d42")
    hand(now.second * 6, 155, 2, "#ef233c")
    hands.penup()
    hands.goto(0, 0)
    hands.dot(16, "#ef233c")
    screen.update()
    screen.ontimer(tick, 1000)


tick()
turtle.done()

How it is drawn

Two turtles: face draws the face, the marks and the numbers once; hands draws the hands, and hands.clear() wipes them every second.

A clock goes clockwise from 12, while turtle's 0 degrees points right and turns anticlockwise, so the heading is 90 - angle. The second hand moves 6 degrees a second, the minute hand 6 a minute, the hour hand 30 an hour.

datetime.datetime.now() gives the time; the hour hand also adds minute / 60, so at half past three it sits between 3 and 4.

screen.ontimer(tick, 1000) calls tick again a second later, and the clock runs.

Questions

Does it run forever on this page?

Here the animation stops after 30 seconds; on your own computer it runs until you close the window.

Why a second turtle for the hands?

clear() wipes only what that turtle drew. With the hands on their own turtle, wiping them leaves the face alone.

Try another