Home >Backend Development >Python Tutorial >How to use Python code to simulate a dynamic analog clock
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:
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!