Home » Create a digital clock using Turtle in Python

Create a digital clock using Turtle in Python

Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription

In this article we create a digital clock using turtle and we will add a digital clock

Table of Contents

Code

Installation: To install this module type the below command in the terminal.

pip install turtle
import time
import datetime as dt
import turtle
  

# create a turtle to display time
timet = turtle.Turtle()
 
# create a turtle to create rectangle box
rectt = turtle.Turtle()
 
# create screen
screen = turtle.Screen()
 
# set background color of the screen
screen.bgcolor("yellow")
  
# current hour, minute and second
sec = dt.datetime.now().second
min = dt.datetime.now().minute
hr = dt.datetime.now().hour
rectt.pensize(5)
rectt.color('black')
rectt.penup()
  
# set the position of turtle
rectt.goto(-20, -5)
rectt.pendown()
  
# create rectangular box
for i in range(2):
    rectt.forward(200)
    rectt.left(90)
    rectt.forward(70)
    rectt.left(90)
     
# hide the turtle
rectt.hideturtle()
 
while True:
    timet.hideturtle()
    timet.clear()
    # display the time
    timet.write(str(hr).zfill(2)
            +":"+str(min).zfill(2)+":"
            +str(sec).zfill(2),
            font =("Arial Narrow", 40, "bold"))
    time.sleep(1)
    sec+= 1
     
    if sec == 60:
        sec = 0
        min+= 1
     
    if min == 60:
        min = 0
        hr+= 1
     
    if hr == 13:
        hr = 1

When run you should see something like this

Link

turtledigclock

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More