Article | carefree huan \

Source: Python Technology “ID: pythonall”

The clock is one of the most common and essential objects in our daily lives. Have you ever thought of drawing a real-time dynamic clock in Python? Let’s see how to use simple code to implement a dynamic clock.

Introduction to Turtle Mapping

The Turtle library is a popular Python library for drawing images. We don’t know why it has such a strange name, but it reminds us that we are manipulating the Turtle to crawl along a binary coordinate system on the X and y axes. From this perspective, the author is also a very interesting person.

There are many commands for manipulating turtle drawings, which can be divided into three types: motion commands, brush control commands, and global control commands.

Brush movement command

Brush movement command

Brush control command

Brush control command

Global control command

Global control command

Other commands

Other commands

The overall train of thought

Now that we know the turtle drawing command, let’s organize our drawing ideas.

As we know, a clock consists of a dial and an hour hand.

Dial is composed of scale, a total of 60 scale, corresponding to a circle of 60 points, every 4 scale will have a scale is a short line, every 5 multiple scale will be marked with hours (1-12).

There are three hands, respectively for the second hand, minute hand and hour hand, the length of the three hands from short to long. The second hand goes one circle, the minute hand goes one scale, the minute hand goes one circle, the hour hand goes one scale.

In addition, we can also display the day and date in the dial.

Thus, the elements of our clock are clear, including the dial (60 dials and hours), the hands (three), the day and the date.

Code implementation

code

With that in mind, we started drawing images using the Turtle draw command. The overall code is as follows:

import turtle
from datetime importDef skip(step): turtle.penup() turtle.forward(step) turtle.pendown() def mkHand(name, length): Reset () # Move the pointer in the opposite direction for a certain distance. Skip (-length *0.1Start recording the vertices of the polygon. The current turtle position is the first vertex of the polygon. turtle.begin_poly() turtle.forward(length *1.1Stop recording the vertices of the polygon. The current turtle position is the last vertex of the polygon. It's going to be connected to the first vertex. Turtle.end_poly () # returns the last recorded polygon. handForm = turtle.get_poly() turtle.register_shape(name, handForm) def init(): Global secHand, minHand, houHand, printer # reset Turtle points to north Turtle. mode("logo"Create three pins Turtle and initialize mkHand("secHand".135)
    mkHand("minHand".125)
    mkHand("houHand".90)
    secHand = turtle.Turtle()
    secHand.shape("secHand")
    minHand = turtle.Turtle()
    minHand.shape("minHand")
    houHand = turtle.Turtle()
    houHand.shape("houHand")

    for hand in secHand, minHand, houHand:
        hand.shapesize(1.1.3)
        hand.speed(0) # create output text Turtle printer = turtle.turtle () # hide the shape of the pen Turtle printer. Hideturtle () printer. Penup () # draw the dial def SetupClock (radius): # set the outer box of the table turtle.reset() turtle.pensize(7)
    for i in range(60Skip (radius) :if i % 5= =0: # draw a long line turtle.forward(20) # return to center skip(-radius -20) # move to the end of the scale skip(radius +20) # Write dial values below, so as not to overlap with the marking, so special positions are treatedif i == 0:
                turtle.write(int(12), align="center", font=("Courier".14."bold"))
            elif i == 30:
                skip(25)
                turtle.write(int(i/5), align="center", font=("Courier".14."bold"))
                skip(- 25)
            elif (i == 25 or i == 35):
                skip(20)
                turtle.write(int(i/5), align="center", font=("Courier".14."bold"))
                skip(- 20)
            else:
                turtle.write(int(i/5), align="center", font=("Courier".14."bold") # return to center skip(-radius -20)
        else: # Draw the dot turtle.dot(5Skip (-radius) # move clockwise6° turtle. Right (6)

def week(t):
    week = ["Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"."Sunday"]
    return week[t.weekday()]

def date(t):
    y = t.year
    m = t.month
    d = t.day
    return "%s %d%d"% (y, m, d) def tick(): t = datetime.today() second = t.second + t.icrosecond *0.000001
    minute = t.minute + second / 60.0
    hour = t.hour + minute / 60.0
    secHand.setheading(6 * second)
    minHand.setheading(6 * minute)
    houHand.setheading(30 * hour)

    turtle.tracer(False)
    printer.forward(65)
    printer.write(week(t), align="center",
                  font=("Courier".14."bold"))
    printer.back(130)
    printer.write(date(t), align="center",
                  font=("Courier".14."bold"))
    printer.home()
    turtle.tracer(True)

    # 100Call tick Turtle. ontimer(tick,100Def main(): # turn on/off the turtle animation and set a delay for updating the drawing. turtle.tracer(False) init() setupClock(160)
    turtle.tracer(True)
    tick()
    turtle.mainloop()

if __name__ == "__main__":
    main()
Copy the code

The code on

Let’s look at some of the methods in the code.

  • The skip() method is a common method used to lift the brush, move it forward a short distance, and then drop the brush.
  • The mkHand() method is a pointer drawing method, the idea is to start from the center of the dial, first reverse a distance, the end point as the starting point for drawing the pointer, and then draw a line to the center point as the pointer.
  • The setupClock() method is to draw the dial, drawing the dial mainly pays attention to the need to draw a short line to the fifth scale and the number of marking hours.
  • The tick() method is the key method to realize our dynamic clock. On the basis of initializing the clock, it displays the information of the day and date in the dial on the one hand, and periodically refreshes the pointer position on the other hand to achieve the real-time display effect.
  • The init() method initializes the clock information, including the day and date information on the pointer and dial.

Finally, we call Tkinter’s mainloop function in the main() method to start the event loop, which must be the last statement in the Turtle graphics program.

The results

Dynamic clock

Directly run the program, you will see a pop-up window, above is the dynamic clock we draw, the pointer is walking oh!

conclusion

This paper realizes a dynamic refresh clock by using turtle drawing. The code itself is not complicated, but the idea of implementation is important. If you find it interesting, share it with your friends!

PS: Reply “Python” within the public number to enter the Python novice learning exchange group, together with the 100-day plan! \

Old rules, brothers still remember, the lower right corner of the “watching” click, if you feel the content of the article is good, remember to share moments to let more people know!

[Code access ****]

Identify the qr code at the end of the text, reply: 200623