文章目录步骤1、创建stick_figure.py代码运行代码效果用turtle包即可。步骤1、创建stick_figure.py代码importturtleimporttime# --- 1. 设置画布 ---screenturtle.Screen()screen.title(Python 火柴人行走动画)screen.bgcolor(lightcyan)# 背景颜色screen.setup(800,400)# 窗口大小screen.tracer(0)# 关闭自动刷新为了实现流畅动画# 创建画笔tturtle.Turtle()t.hideturtle()t.pensize(3)t.color(black)# --- 2. 定义绘制火柴人的函数 ---defdraw_stickman(x,y,leg_offset,arm_offset): x, y: 身体中心坐标 leg_offset: 腿部摆动角度偏移 (用于走路效果) arm_offset: 手臂摆动角度偏移 t.penup()t.goto(x,y)t.setheading(0)# 重置方向# A. 画头t.penup()t.goto(x,y60)# 头部位置t.pendown()t.circle(20)# 半径20的头# B. 画身体t.penup()t.goto(x,y40)t.pendown()t.goto(x,y-40)# 身体长度80# C. 画手臂 (左右交替)# 左臂t.penup()t.goto(x,y30)# 肩膀位置t.setheading(180-arm_offset)# 向左摆动t.pendown()t.forward(30)# 右臂t.penup()t.goto(x,y30)t.setheading(arm_offset)# 向右摆动t.pendown()t.forward(30)# D. 画腿 (左右交替模拟走路)# 左腿t.penup()t.goto(x,y-40)# 胯部位置t.setheading(270-leg_offset)# 左腿向后/前蹬t.pendown()t.forward(40)# 右腿t.penup()t.goto(x,y-40)t.setheading(270leg_offset)# 右腿向前/后蹬t.pendown()t.forward(40)# --- 3. 动画主循环 ---try:whileTrue:# 这里的逻辑是让火柴人在屏幕上从左边移动到右边# 为了演示方便我们让它在一个范围内来回走或者一直往右走forstepinrange(0,360,10):# 控制步数# 计算位置让火柴人从左(-300)走到右(300)# 如果超出屏幕就回到左边current_x-350step*2ifcurrent_x350:current_x-350# 清除上一帧的画面t.clear()# 计算走路时的肢体摆动 (正弦波原理的简化版)# 通过取模运算 % 来实现左右腿交替walk_cyclestep%60leg_angle0arm_angle0ifwalk_cycle30:# 第一阶段左腿前右腿后leg_angle30arm_angle30# 手臂与腿相反else:# 第二阶段右腿前左腿后leg_angle-30arm_angle-30# 调用绘图函数# 注意手臂摆动方向和腿是相反的左手配右脚这样才自然draw_stickman(current_x,0,-leg_angle,arm_angle)# 刷新屏幕screen.update()time.sleep(0.05)# 控制速度exceptturtle.Terminator:print(窗口已关闭)运行代码效果实际效果是一个动图这里只贴下图片了。