SoFunction
Updated on 2024-11-16

Implementing Analog Dynamic Pointer Clocks with Python Code

I. Python code implementation and turtle library brief introduction

Desktop Clock Project Description

1, the use of turtle library to draw the shape of the clock and the hands;

2. Use datetime to get the system time;

3, clock dynamic display

Basic turtle library commands

1, () function: used to start a graphic window, it has four parameters (width, height, startx, starty) are: start the width of the window and the height of the window said that the window is started, the upper-left corner of the window in the screen in the coordinate position.

2, () function: indicates the width of the movement track of the small turtle.

3, () function: indicates the color of the little turtle's movement track. It contains an input parameter, here we set it to blue, blue, other color words can also be used.Turtle uses RGB way to define the color, if you want to get the same color as the picture of the snake, please enter ("#3B9909")

4. (angle) function: indicates the direction of movement when the turtle starts. It contains an input parameter, which is an angle value. 0 means east, 90 degrees to the north, 180 degrees to the west, 270 degrees to the south; negative values mean the opposite direction. In the program, we let the turtle start crawling to -40 degrees, i.e.: 40 degrees to the southeast.

5, () function: let the turtle crawl along a circle, the parameter rad describes the location of the radius of the circular trajectory, the radius of this radius in the left side of the turtle run, rad far position. If rad is negative, then the radius is on the right side of the turtle's run, and the parameter angle indicates the radian value of the turtle's crawl along the circle.

6, () function: indicates that the turtle crawls forward in a straight line to move indicates that the small turtle crawls forward in a straight line to move, it has a parameter that indicates that the distance crawled

datetime module functions

: A class that represents a date and returns year-month-day.

: A class representing the date and time, returning the year, month, day, hour, minute and second.

: Classes that represent time.

: indicates the time interval, i.e., the interval between two points in time

: Information on time zones

Sample python code

import turtle                 # Importing the Mapping Turtles module
import datetime               # Import date-time module

# Move a distance
def skip(distance):          # Methods of movement, leaving no trace of movement
    ()           # Lift pen not drawn
    (distance) # Move the specified distance
    ()         # Falling strokes move to draw

def draw_clock_dial():            # Methods of drawing dials
    ()           # Delete graphic homing
    ()       # Hide the arrows
    for i in range(60):       # The loop is executed 60 times, and a circle is 360 degrees so the angle is 6 degrees per second.
        skip(160)              # Move 160, which corresponds to the radius of the dial circle #
        # Hourly scales plotted every 5 seconds
        if i % 5 == 0:
            (7)       # Scale size
            # Drawing clocks
            (20)       # The length of the hour scale is 20
            skip(-20)      # Reset the position of the hour scale
        else:
            (1)      # Set the brush size to 1
            ()           # Drawing dots for the minute scale
        skip(-160)                 # Back to the center
        (6)            # Rotate 6 degrees to the right


def get_week(t):                   # Ways to get the day of the week
    week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    return week[()]       # Return to the day of the week


def create_pointer(length, name):     # Create pointer methods
    ()                 # Delete graphic homing
    skip(-length * 0.1)            # Lift the pen to move a specified distance
    turtle.begin_poly()            # Recording polygons
    (length * 1.1)   # Draw pointers of specified length
    turtle.end_poly()              # Stop recording polygons
    # Register polygon shapes
    turtle.register_shape(name, turtle.get_poly())

def init_pointer():                # Initialize pointers
    global secHand, minHand, hurHand, printer
    ("logo")              # Reset Turtle to point up
    create_pointer(135,"secHand")       # Create a second hand graphic
    create_pointer(110,"minHand")       # Create a minute hand graphic
    create_pointer(90,"hurHand")        # Create hour hand graphics
    secHand = ()        # Create the second hand turtle object
    ("secHand")         # Create shapes that specify the name of the second hand
    minHand = ()        # Create a split pin turtle object
    ("minHand")         # Create shapes that specify the name of the minute hand
    hurHand = ()        # Create the hour hand turtle object
    ("hurHand")         # Create a shape with a specified hour hand name
    for hand in secHand, minHand, hurHand:   # Loop through the three pointers
        (1, 1, 5)              # Setting the shape stretch size and contour lines
        (0)                        # Set the speed to the fastest
    printer = ()                # Create a Turtle object for drawing text
    ()                     # Hide the arrows
    ()                          # Lift the pen

def move_pointer():                          # Ways to move the pointer
    # Keep getting the time
    t = ()
    second =  +  * 0.000001    # Calculating seconds of movement
    minute =  + second/60                   # Calculate the points of movement
    hour =  + minute/60                       # Calculate the hours moved
    (6*second)                     # Set the angle of the second hand
    (6*minute)                     # Set the angle of the minute hand
    (30*hour)                      # Set the angle of the hour hand
    (False)                             # Turn off the painting effect
    (65)                              # Move up 65
    # Plotting the week
    (get_week(t), align="center",font=("Courier", 14, "bold"))
    (130)                                # Rewind 130
    # Month and year of mapping
    (('%Y-%m-%d'), align="center",font=("Courier", 14, "bold"))
    ()                                   # To return to their place #
    (True)                              # Turn on the painting effect
    (move_pointer, 10)                 # Call the move_pointer() method after 10 milliseconds

if __name__ == '__main__':
    (450, 450)      # Create form size
    init_pointer()              # Call the method that initializes the pointer
    (False)        # Turn off the painting effect
    draw_clock_dial()            # Drawing dials
    move_pointer()               # Calls to move the pointer
    ()            # Without closing the form

Run results:

Second, MFC code implementation

You can find a dial chart for yourself and just add it to the bitmap resource.

Added a timer to implement a pointer rotation update

The formula for calculating the hour, minute, and second hands:

First converted to a 12-hour system, h = h % 12

Each hour of the hour hand corresponds to 30 degrees clockwise relative to the y-axis. 0.5 degrees per minute (seconds are negligible)

The minute hand is 6 degrees per minute, the second is 0.1 degrees.

The second hand is also 6 degrees per second.

Define the length of the minute hand, second hand and hour hand, according to the second hand is the longest, the hour hand is the second longest, and the hour hand is the shortest.

Then with the angle, and length of the pointer, you can get the coordinates of the end of the pointer, and just draw a line from the center of the clock using the LineTo method.

MFC Code Samples

void CdrawdateDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: add message handler code and/or call defaults here
	UpdateData(TRUE);
	CTime time = CTime::GetCurrentTime();                //Obtain system time
	m_Sec = ();
	m_Min = ();
	m_Hour = ();

	CDC* pDC = GetDC();
	CRect rect;
	GetClientRect(&rect);                                //Acquisition of client areas
	CBitmap bitmap;                                      // Define the picture class
	(IDB_BITMAP2);                      // Load Bitmap
	CDC memdc;                                           // Define temporary canvas
	(pDC);                       //Creating a Canvas
	(&bitmap);                         //Associated Pictures

	int x = () / 2;
	int y = () / 2;

	//(weekDay(time), &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); // display the day of the week
	CString csCurrTime;
	("%04d-%02d-%02d                        %s", (), (), (), weekDay(time));
	(csCurrTime, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);		// Display the current date

	CPen MinutePen(PS_SOLID, 5, RGB(0, 0, 0));               //Set the minute hand brush
	(&MinutePen);
	(x, y);
	//Drawing the minute hand
	(x + (long)100 * cos(PI / 2 - 2 * PI*m_Min / 60.0), y - (long)100 * sin(PI / 2 - 2 * PI*m_Min / 60.0));
	CPen HourPen(PS_SOLID, 8, RGB(0, 0, 0));                 //Setting the Clockwise Brush
	(&HourPen);
	(x, y);
	//Drawing the hour hand
	(x + (long)60 * cos(PI / 2 - 2 * PI*(5 * m_Hour / 60.0 + m_Min / 12.0 / 60.0))
		, y - (long)60 * sin(PI / 2 - 2 * PI*(5 * m_Hour / 60.0 + m_Min / 12.0 / 60.0)));
	CPen SecondPen(PS_SOLID, 2, RGB(255, 0, 0));            //Set the second hand brush
	(&SecondPen);
	(x, y);
	(x + (long)140 * cos(PI / 2 - 2 * PI*m_Sec / 60.0), y - (long)140 * sin(PI / 2 - 2 * PI*m_Sec / 60.0));//Drawing the second hand
	(x, y);
	(x + (long)10 * cos(PI / 2 - 2 * PI*(m_Sec + 30) / 60.0), y - (long)10 * sin(PI / 2 - 2 * PI*(m_Sec + 30) / 60.0));//Drawing the second hand
	();
	();
	();
	pDC->BitBlt(0, 0, , , &memdc, 0, 0, SRCCOPY);                    //Copy image
	();                                   //Copy temporary canvas to preview window
	();                              //Delete Pictures
	ReleaseDC(pDC);

	CDialogEx::OnTimer(nIDEvent);
}

Output cstring (to determine what day of the week it is)

CString CdrawdateDlg::weekDay(CTime oTime)
{
	CString str;
	int nDayOfWeek = ();
	switch (nDayOfWeek)
	{
	case 1:
		str = "Sunday.";
		break;
	case 2:
		str = "Monday.";
		break;
	case 3:
		str = "Tuesday.";
		break;
	case 4:
		str = "Wednesday.";
		break;
	case 5:
		str = "Thursday.";
		break;
	case 6:
		str = "Friday.";
		break;
	case 7:
		str = "Saturday.";
		break;
	}
	return str;
}

Code run results:

to this article on the use of Python code to simulate the dynamic pointer clock is introduced to this article, more related Python dynamic pointer clock content, please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future!