海龟每步画保存为png与合成gif程序源代码

"""海龟每步画保存为png.py,
   本程序把海龟每步所画的图形都保存为png格式的图片,以便合成gif动画。
原理是用(画布)screen.cv.postscript命令,然后用ghostscript进行转换。
首先需要安装ghostscript,设定好搜索路径。"""

import os
import io
from PIL import Image
from turtle import * 

本文隐藏内容 登陆 后才可以浏览
def draw_tree(length,level): if level > 0: for i in range(int(length//4)):# 慢慢地前进 t.fd(4) savepng(screen.cv,"path") # 每个步骤都保存为图片 for i in range(9): # 慢慢地左转 t.left(5) savepng(screen.cv,"path") # 每个步骤都保存为图片 draw_tree(length/1.5,level-1) # 往左画一颗更小的树 for i in range(18): # 慢慢地右转 t.right(5) savepng(screen.cv,"path") # 每个步骤都保存为图片 draw_tree(length/1.5,level-1) # 往右画一颗更小的树 for i in range(9): # 慢慢地左转 t.left(5) savepng(screen.cv,"path") # 每个步骤都保存为图片 for i in range(int(length//4)):# 慢慢地倒退 t.bk(4) savepng(screen.cv,"path") "下面变量需根据安装ghostscript的路径决定" ghostscrpit = 'C:\\Program Files\\gs\\gs9.26\\bin' counter = 0 "以下是添加搜索ghostscript的路径" path = os.environ['path'] path = path.split(";") path.append(ghostscrpit) path = ';'.join(path) os.environ['path'] = path screen = Screen() screen.delay(10) screen.setup(500,660) t = Turtle(shape='turtle') t.shapesize(2,2) t.color("blue") t.penup() t.pensize(4) t.setheading(90) t.bk(200) t.pendown() draw_tree(200,4) t.ht() screen.mainloop()

以下是把png合成gif图源代码:

import glob,os
import imageio

def makegif(path,filename):
    
   images = glob.glob("path" + os.sep +"*.png")
   frames = [imageio.imread(image) for image in images]
   imageio.mimsave(filename, frames, 'GIF', duration=0.1) 
    

if __name__ == "__main__":

    makegif("path","tree.gif")