Create digital clock using Python-Turtle
Turtle is a special feature of Python. Using Turtle, we can easily draw on a drawing board. First, we import the turtle module. Then create a window, next we create a turtle object and using the turtle methods we can draw in the drawing board.
Prerequisites: Turtle Programming in Python
Installation: To install this module type the below command in the terminal.
pip install turtle
Note: To create a clock we will use the ‘time’ and ‘DateTime’ modules of Python also, To install time use the following command:
Below is the implementation.
- The code starts by creating two turtles.
- The first turtle, t1, will be used to create a rectangular box on the screen.
- The second turtle, t2, will be used to display the time.
- The code then sets up some variables.
- The hour variable stores the current hour as a number (e.g., 13).
- The minute variable stores the current minute as a number (e.g., 59).
- And the second variable stores the current second as a number (e.g., 2).
- Next, the code obtains information about the system time from datetime object dt.datetime.now().second .
- This object contains information about the date and time that is currently being displayed on your computer or device.
- The next section of code sets up some variables for drawing onscreen using turtle graphics objects.
- These variables store information about how wide and high each line should be drawn in pixels (i.e., they are called pensize() variables), and they also specify which color to use for each line (i.e., they are called color() variables).
- Finally, these variables tell the turtle to start drawing at position (-20, 0) in the upper-left corner of the screen and to stop drawing. The code first creates two turtles, one to display time and another to create a rectangular box.
- Next, the code sets up the screen and obtains the current hour, minute, and second from the system.
- The code then sets the position of the turtle for each line in the for a loop.
- The first line moves the turtle 200 pixels to the right, 90 pixels down and 70 pixels forward.
- The next line moves the turtle again but this time it left 90 pixels to the right and moved it 70 pixels down.
- The last two lines move the turtle forward by 200 pixels again and left it at its original position.
- Next, the code hides both turtles and waits for a second.
- Once a second has passed, it displays time by writing.