在 Python 中,“写动画”涵盖了从简单的图形移动、游戏开发,到复杂的 3D 可视化、数据动画等广泛领域。由于 Python 拥有丰富的库,不可能列出每一条可能的语句,但可以按库分类,穷举其中最核心、最常用的动画相关语句。以下内容覆盖了从标准库到第三方库、从 2D 到 3D、从终端到图形界面的主要动画实现方式。
1. 标准库动画
1.1 turtle – 入门级图形动画
import turtle
# 创建画布和画笔
t = turtle.Turtle()
screen = turtle.Screen()
# 基本移动语句
t.forward(100) # 前进
t.backward(50) # 后退
t.left(90) # 左转
t.right(45) # 右转
t.goto(x, y) # 移动到绝对坐标
t.setx(100) # 设置 x 坐标
t.sety(200) # 设置 y 坐标
# 绘图控制
t.penup() # 抬笔,移动时不画线
t.pendown() # 落笔
t.pensize(3) # 笔宽
t.color("red") # 设置颜色
# 填充
t.begin_fill()
t.circle(50)
t.end_fill()
# 动画循环与刷新
screen.tracer(0) # 关闭自动刷新(手动更新)
screen.update() # 手动刷新屏幕
screen.ontimer(func, t) # 定时执行函数(实现帧动画)
t.clear() # 清除画笔痕迹
t.reset() # 重置所有状态
# 事件绑定
screen.onclick(func) # 鼠标点击事件
screen.onkey(func, "space") # 键盘事件
screen.listen() # 监听键盘
# 主循环
screen.mainloop() # 进入事件循环
1.2 tkinter – GUI 动画(Canvas)
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# 创建图形对象
rect = canvas.create_rectangle(10, 10, 50, 50, fill="blue")
circle = canvas.create_oval(100, 100, 150, 150, fill="red")
line = canvas.create_line(0, 0, 200, 200, width=2)
# 移动对象
canvas.move(rect, dx, dy) # 相对移动
canvas.coords(rect, x1, y1, x2, y2) # 设置新坐标
# 删除对象
canvas.delete(rect)
# 动画更新(递归或 after 循环)
def animate():
canvas.move(circle, 2, 0)
root.after(10, animate) # 每 10ms 调用一次
animate()
root.mainloop()
2. 游戏与多媒体库
2.1 pygame – 最流行的 2D 游戏/动画库
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
# 加载图像
image = pygame.image.load("sprite.png")
rect = image.get_rect()
# 主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新逻辑
rect.x += 1
# 绘制
screen.fill((0, 0, 0)) # 清屏
screen.blit(image, rect) # 绘制图像
pygame.display.flip() # 刷新屏幕
# 控制帧率
clock.tick(60) # 60 FPS
pygame.quit()
2.2 pyglet – 纯 Python 多媒体库
import pyglet
window = pyglet.window.Window(width=800, height=600)
image = pyglet.image.load("sprite.png")
sprite = pyglet.sprite.Sprite(image, x=0, y=0)
@window.event
def on_draw():
window.clear()
sprite.draw()
def update(dt):
sprite.x += 1
pyglet.clock.schedule_interval(update, 1/60.0) # 每帧调用
pyglet.app.run()
2.3 kivy – 跨平台 UI/动画框架
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.animation import Animation
from kivy.clock import Clock
class MyWidget(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.anim = Animation(x=200, y=200, duration=2)
self.anim.start(self)
def on_touch_down(self, touch):
# 属性动画
Animation(x=touch.x, y=touch.y, duration=0.5).start(self)
class MyApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyApp().run()
3. 数据可视化动画
3.1 matplotlib.animation – 科学计算动画
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 100)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0)) # 更新数据
return line,
ani = animation.FuncAnimation(fig, animate, frames=100, interval=50, blit=True)
plt.show()
# 保存为 GIF/视频
ani.save("animation.gif", writer='pillow')
ani.save("movie.mp4", writer='ffmpeg')
3.2 plotly – 交互式动画(简要)
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year",
animation_group="country", size="pop", color="continent")
fig.show()
4. 专业动画/图形库
4.1 manim – 数学动画引擎(3Blue1Brown 所用)
from manim import *
class SquareToCircle(Scene):
def construct(self):
square = Square()
circle = Circle()
self.play(Create(square)) # 播放创建动画
self.play(Transform(square, circle)) # 变换动画
self.play(FadeOut(square)) # 淡出
# 运行命令:manim -pql file.py SquareToCircle
4.2 vpython – 3D 动画
from vpython import *
# 创建物体
ball = sphere(pos=vector(0,0,0), radius=0.5, color=color.red)
floor = box(pos=vector(0,-1,0), size=vector(4,0.1,4), color=color.green)
# 动画循环
while True:
rate(60) # 控制帧率
ball.pos.x += 0.1
if ball.pos.x > 2:
ball.pos.x = -2
5. 图像/视频处理动画
5.1 opencv – 视频处理与动画
import cv2
import numpy as np
cap = cv2.VideoCapture(0) # 打开摄像头
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
while True:
ret, frame = cap.read()
if not ret:
break
# 在帧上绘制图形(动画)
cv2.circle(frame, (100,100), 50, (0,255,0), -1)
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
5.2 PIL / Pillow – 图像序列与 GIF
from PIL import Image, ImageSequence
# 创建 GIF
frames = []
for i in range(10):
img = Image.new('RGB', (100,100), color=(i*25, i*25, i*25))
frames.append(img)
frames[0].save('animation.gif', save_all=True, append_images=frames[1:], duration=100, loop=0)
# 读取 GIF 每一帧
with Image.open('animation.gif') as img:
for frame in ImageSequence.Iterator(img):
# 处理每一帧
pass
6. 终端/文本动画
6.1 curses – 终端图形界面
import curses
import time
def main(stdscr):
curses.curs_set(0) # 隐藏光标
stdscr.nodelay(1) # 非阻塞输入
y, x = 0, 0
while True:
stdscr.clear()
stdscr.addstr(y, x, "@") # 在指定位置绘制字符
stdscr.refresh()
time.sleep(0.1)
x += 1
if x > 20:
x = 0
c = stdscr.getch()
if c == ord('q'):
break
curses.wrapper(main)
6.2 rich – 富文本动画
from rich.live import Live
from rich.table import Table
import time
with Live(refresh_per_second=10) as live:
for i in range(10):
table = Table()
table.add_column("Frame", str(i))
live.update(table)
time.sleep(0.5)
6.3 ASCII 动画(简单循环清屏)
import os
import time
frames = [
" O \n /|\\ \n / \\ ",
" O \n /|\\ \n | ",
" O \n /| \n / \\ ",
]
while True:
for frame in frames:
os.system('cls' if os.name == 'nt' else 'clear')
print(frame)
time.sleep(0.3)
7. 通用动画模式与辅助语句
7.1 帧循环与时间控制
import time
# 简单帧循环
while True:
# 更新逻辑
# 绘制
time.sleep(0.016) # 约 60 FPS(不精确)
# 精确帧率控制(使用 pygame 的 clock 或自定义)
import time
FPS = 60
frame_time = 1.0 / FPS
while True:
start = time.time()
# 更新、绘制
elapsed = time.time() - start
time.sleep(max(0, frame_time - elapsed))
7.2 双缓冲(防止闪烁)
pygame.display.flip()已实现双缓冲。tkinter可通过update_idletasks()和after()实现。turtle通过tracer(0)+update()实现。
7.3 动画事件回调
# tkinter 的 after
def animate():
canvas.move(obj, 1, 0)
root.after(10, animate)
# pygame 的 pygame.time.set_timer
pygame.time.set_timer(pygame.USEREVENT, 100) # 每 100ms 触发自定义事件
# pyglet 的 schedule_interval
pyglet.clock.schedule_interval(update, 1/30.0)
总结
Python 中“写动画”的语句因库而异,但核心可归纳为:
- 创建/初始化:
init(),Canvas(),Screen(),set_mode() - 绘图:
create_*,draw*,blit,addstr - 更新:
move,coords,set_ydata,pos.x = - 刷新:
update(),flip(),refresh() - 定时:
after(),ontimer(),clock.tick(),schedule_interval() - 事件循环:
mainloop(),run(),while running: ...
以上列出了各类库的核心动画语句,足以覆盖绝大多数 Python 动画场景。如需特定库的更详细用法,可进一步提问。

1242

被折叠的 条评论
为什么被折叠?



