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

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

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

def savepng(canvas,path):
    """把canvas.postscript的内容转换成png写入文件"""     
    global counter
    psimage = canvas.postscript(colormode = 'color')    # 生成ps字符串
    filename = path + os.sep + str(counter) + ".png"    # 形成文件名
    im = Image.open(io.BytesIO(psimage.encode('utf-8')))# 打开图像
    im.save(filename,format="PNG")                      # 保存图像
    im.close()                                          # 关闭图像
    counter = counter + 1                               # 计数器加1

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) 

You must log in to read the rest of this article. Please log in or register as a user.