1. Python code implementation and a brief introduction to the turtle library
Desktop clock project description
1. Use the turtle library to draw the clock shape and hands;
2. Use datetime Get the system time;
3. Clock dynamic display
turtle library basic commands
1. turtle.setup() function: used to start a graphics window, which has four The two parameters turtle.setup(width, height, startx, starty) are respectively: the width and height of the startup window represent the coordinate position of the upper left corner of the window on the screen when the window is started.
2. turtle.pensize() function: represents the width of the turtle’s movement trajectory.
The color of the turtle's movement trajectory can be set by calling the turtle.pencolor() function. This function takes an input parameter, which we can set to blue, or use another color word. Turtle uses RGB to define colors. If you want to get a snake with the same color as the picture, please enter turtle.pencolor("#3B9909")
The movement direction of the turtle when it starts can be called turtle.seth (angle) function to set. It contains one input parameter, which is the angle value. Direction can be expressed as an angle: 0 degrees represents east, 90 degrees represents north, 180 degrees represents west, and 270 degrees represents south; negative values represent the opposite direction. We let the little turtle start crawling at an angle of -40 degrees, that is, toward the southeast.
5. Turtle.circle() function: Let the little turtle crawl along a circle. The parameter rad describes the position of the radius of the circular trajectory. This radius is on the left side of the turtle's running position, rad far away. When rad is a negative number, the radius is on the right side of the turtle's running path, and the parameter angle represents the arc of the turtle crawling on the circular trajectory.
6. Turtle.fd() function: Indicates that the turtle crawls forward in a straight line. It indicates that the turtle crawls forward in a straight line. It has a parameter indicating the crawling distance.
datetime module function
1.datetime.date: A class representing date, returning year-month-day
2.datetime.datetime: A class representing date and time, returning year, month, day, hours, minutes and seconds
3.datetime.time: a class representing time,
4.datetime.timedelta: representing a time interval, that is, the interval between two time points
5.datetime.tzinfo: time zone Related information
python code example
import turtle # 导入绘图海龟模块 import datetime # 导入日期时间模块 # 移动一段距离 def skip(distance): # 移动方法,不留移动痕迹 turtle.penup() # 抬笔不绘制 turtle.forward(distance) # 移动指定距离 turtle.pendown() # 落笔移动绘制 def draw_clock_dial(): # 绘制表盘的方法 turtle.reset() # 删除图形归位 turtle.hideturtle() # 隐藏箭头 for i in range(60): # 循环执行60次,一圈为360度所以每一秒的角度为6度 skip(160) # 移动160,相当于表盘圆的半径 # 每5秒绘制一个小时刻度 if i % 5 == 0: turtle.pensize(7) # 刻度大小 # 画时钟 turtle.forward(20) # 小时刻度的长度为20 skip(-20) # 复原小时刻度的位置 else: turtle.pensize(1) # 将画笔大小设置为1 turtle.dot() # 绘制分钟刻度的小圆点 skip(-160) # 回到中心位置 turtle.right(6) # 向右旋转6度 def get_week(t): # 获取星期的方法 week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'] return week[t.weekday()] # 返回当天的星期 def create_pointer(length, name): # 创建指针方法 turtle.reset() # 删除图形归位 skip(-length * 0.1) # 抬笔移动指定距离 turtle.begin_poly() # 记录多边形 turtle.forward(length * 1.1) # 绘制指定长度的指针 turtle.end_poly() # 停止记录多边形 # 注册多边形状 turtle.register_shape(name, turtle.get_poly()) def init_pointer(): # 初始化指针 global secHand, minHand, hurHand, printer turtle.mode("logo") # 重置Turtle指向上 create_pointer(135,"secHand") # 创建秒针图形 create_pointer(110,"minHand") # 创建分针图形 create_pointer(90,"hurHand") # 创建时针图形 secHand = turtle.Turtle() # 创建秒针turtle对象 secHand.shape("secHand") # 创建指定秒针名称的形状 minHand = turtle.Turtle() # 创建分针turtle对象 minHand.shape("minHand") # 创建指定分针名称的形状 hurHand = turtle.Turtle() # 创建时针turtle对象 hurHand.shape("hurHand") # 创建指定时针名称的形状 for hand in secHand, minHand, hurHand: # 循环遍历三个指针 hand.shapesize(1, 1, 5) # 设置形状拉伸大小和轮廓线 hand.speed(0) # 设置速度为最快 printer = turtle.Turtle() # 创建绘制文字的Turtle对象 printer.hideturtle() # 隐藏箭头 printer.penup() # 抬笔 def move_pointer(): # 移动指针的方法 # 不停的获取时间 t = datetime.datetime.today() second = t.second + t.microsecond * 0.000001 # 计算移动的秒 minute = t.minute + second/60 # 计算移动的分 hour = t.hour + minute/60 # 计算移动的小时 secHand.setheading(6*second) # 设置秒针的角度 minHand.setheading(6*minute) # 设置分针的角度 hurHand.setheading(30*hour) # 设置时针的角度 turtle.tracer(False) # 关闭绘画效果 printer.forward(65) # 向上移动65 # 绘制星期 printer.write(get_week(t), align="center",font=("Courier", 14, "bold")) printer.back(130) # 倒退130 # 绘制年月日 printer.write(t.strftime('%Y-%m-%d'), align="center",font=("Courier", 14, "bold")) printer.home() # 归位 turtle.tracer(True) # 开启绘画效果 turtle.ontimer(move_pointer, 10) # 10毫秒后调用move_pointer()方法 if __name__ == '__main__': turtle.setup(450, 450) # 创建窗体大小 init_pointer() # 调用初始化指针的方法 turtle.tracer(False) # 关闭绘画效果 draw_clock_dial() # 绘制表盘 move_pointer() # 调用移动指针的方法 turtle.mainloop() # 不关闭窗体
Running results:
II. MFC code implementation
You can find a dial image yourself and add it to the bitmap resource.
Added a timer to realize pointer rotation update
Calculation of hour hand, minute hand and second hand Formula:
First convert to 12-hour format, h = h % 12
The hour hand is equivalent to 30 degrees clockwise relative to the y-axis. 0.5 degrees per minute (seconds can be ignored)
The minute hand is 6 degrees per minute, and 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. Define it according to the longest second hand, followed by the hour hand, and the shortest hour hand.
Then with the angle and length of the pointer, you can get the coordinates of the end of the pointer, and just use the LineTo method to draw a line from the center of the clock.
MFC code example
void CdrawdateDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 UpdateData(TRUE); CTime time = CTime::GetCurrentTime(); //获得系统时间 m_Sec = time.GetSecond(); m_Min = time.GetMinute(); m_Hour = time.GetHour(); CDC* pDC = GetDC(); CRect rect; GetClientRect(&rect); //获取客户区域 CBitmap bitmap; //定义图片类 bitmap.LoadBitmap(IDB_BITMAP2); //加载位图 CDC memdc; //定义临时画布 memdc.CreateCompatibleDC(pDC); //创建画布 memdc.SelectObject(&bitmap); //关联图片 int x = rect.Width() / 2; int y = rect.Height() / 2; //memdc.DrawText(weekDay(time), &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); // 显示星期 CString csCurrTime; csCurrTime.Format("%04d-%02d-%02d %s", time.GetYear(), time.GetMonth(), time.GetDay(), weekDay(time)); memdc.DrawText(csCurrTime, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); // 显示当前日期 CPen MinutePen(PS_SOLID, 5, RGB(0, 0, 0)); //设置分针画笔 memdc.SelectObject(&MinutePen); memdc.MoveTo(x, y); //绘制分针 memdc.LineTo(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)); //设置时针画笔 memdc.SelectObject(&HourPen); memdc.MoveTo(x, y); //绘制时针 memdc.LineTo(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)); //设置秒针画笔 memdc.SelectObject(&SecondPen); memdc.MoveTo(x, y); memdc.LineTo(x + (long)140 * cos(PI / 2 - 2 * PI*m_Sec / 60.0), y - (long)140 * sin(PI / 2 - 2 * PI*m_Sec / 60.0));//绘制秒针 memdc.MoveTo(x, y); memdc.LineTo(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));//绘制秒针 SecondPen.DeleteObject(); MinutePen.DeleteObject(); HourPen.DeleteObject(); pDC->BitBlt(0, 0, rect.right, rect.bottom, &memdc, 0, 0, SRCCOPY); //复制图片 memdc.DeleteDC(); //复制临时画布到预览窗口 bitmap.DeleteObject(); //删除图片 ReleaseDC(pDC); CDialogEx::OnTimer(nIDEvent); }
Output cstring (determine what day it is today)
CString CdrawdateDlg::weekDay(CTime oTime) { CString str; int nDayOfWeek = oTime.GetDayOfWeek(); switch (nDayOfWeek) { case 1: str = "星期日"; break; case 2: str = "星期一"; break; case 3: str = "星期二"; break; case 4: str = "星期三"; break; case 5: str = "星期四"; break; case 6: str = "星期五"; break; case 7: str = "星期六"; break; } return str; }
The above is the detailed content of How to use Python code to simulate a dynamic analog clock. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.