程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

使用python的 turtle模块制作连续动画,页面刷新率

hfteth 2025-01-06 21:46:16 技术文章 13 ℃

在使用python的turtle模块时,可以通过设置tracer()方法来实现在动态图片的效果

首先导入turtle模块

import turtle as tl

接下来是设置图画窗口大小、背景色、画笔大小、画笔颜色、对象填充色、不显示游标

screen = tl.Screen()
screen.setup(width=800,height=500)
screen.bgcolor('red')
tl.pensize(2)
tl.color('yellow')
tl.hideturtle()

接下来是创建一个待操作的对象(这里创建一个五角星)

def pentacle(x,y,angle):
    position = []   # 用来记录五角星五个顶点为的坐标
    tl.clear()					# 清除画面
    tl.left(angle)		# 画笔旋转角度
    for i in range(5):		# 循环用于取得五个顶点的坐标
        tl.penup()					# 提笔
        tl.goto(x,y)				# 五角星的中心点
        tl.pendown()  	# 下笔
        tl.left(72)					# 旋转 72度
        tl.fd(200)				# 半径为 200
        position.append(tl.position())				# 添加顶点坐标
        
    tl.begin_fill() 			# 对象填充颜色开始标记
    tl.penup()
		# 下面就是通过五个顶点的坐标来绘制五角星
    tl.goto(position[0])	
    tl.pendown()
    tl.goto(position[3])
    tl.goto(position[1])
    tl.goto(position[4])
    tl.goto(position[2])
    tl.goto(position[0])
    tl.end_fill()


接下来就是让对象(五角星)旋转起来,实际上就是快速的更新画面,同时改变五个顶点的坐标

创建一个旋转方法:rotate()

def rotate():
    tl.tracer(False) 		# 不显示绘制过程
    pentacle(0,0,10)		# 调用fiveStar
    tl.ontimer(rotate,t=100)		## 每隔100毫秒转一次 

最后就是调用rotate()方法、保持画面

if __name__ == '__main__':
    rotate()
    tl.mainloop()

完整代码:

# -*- encoding: utf-8 -*-
__Autor__ = 'Ocpt'
import turtle as tl
screen = tl.Screen()
screen.setup(width=800,height=500)
screen.bgcolor('red')
tl.pensize(2)
tl.color('yellow')
tl.hideturtle()

def pentacle(x,y,angle):
    position = []
    tl.clear()
    tl.left(angle)
    for i in range(5):
        tl.penup()
        tl.goto(x,y)
        tl.pendown()
        tl.left(72)
        tl.fd(200)
        position.append(tl.position())
    tl.begin_fill()
    tl.penup()
    tl.goto(position[0])
    tl.pendown()
    tl.goto(position[3])
    tl.goto(position[1])
    tl.goto(position[4])
    tl.goto(position[2])
    tl.goto(position[0])
    tl.end_fill()

def rotate():
    tl.tracer(False)
    pentacle(0,0,10)
    tl.ontimer(rotate,t=100)

if __name__ == '__main__':
    rotate()
    tl.mainloop()

以上是使用turtle方法,让图片的内容运动起来的方法

Tags:

最近发表
标签列表