Python Turtle Module- Saving an image

倖福魔咒の 提交于 2019-12-18 12:08:23

问题


I would like to figure out how to save a bitmap or vector graphics image after creating a drawing with python's turtle module. After a bit of googling I can't find an easy answer. I did find a module called canvas2svg, but I'm very new to python and I don't know how to install the module. Is there some built in way to save images of the turtle canvas? If not where do I put custom modules for python on an Ubuntu machine?


回答1:


from Tkinter import *
from turtle import *
import turtle


forward(100)
ts = turtle.getscreen()

ts.getcanvas().postscript(file="duck.eps")

This will help you; I had the same problem, I Googled it, but solved it by reading the source of the turtle module.

The canvas (tkinter) object has the postscript function; you can use it.

The turtle module has "getscreen" which gives you the "turtle screen" which gives you the Tiknter canvas in which the turtle is drawing.

This will save you in encapsulated PostScript format, so you can use it in GIMP for sure but there are other viewers too. Or, you can Google how to make a .gif from this.




回答2:


I wrote an SvgTurtle class that supports the standard Turtle interface from Python, and writes an SVG file using the svgwrite module. Install svgwrite, download svg_turtle.py, and then call it like this:

from turtle import *  # @UnusedWildImport

import svgwrite

from svg_turtle import SvgTurtle


def draw_spiral():
    fillcolor('blue')
    begin_fill()
    for i in range(20):
        d = 50 + i*i*1.5
        pencolor(0, 0.05*i, 0)
        width(i)
        forward(d)
        right(144)
    end_fill()


def write_file(draw_func, filename, size):
    drawing = svgwrite.Drawing(filename, size=size)
    drawing.add(drawing.rect(fill='white', size=("100%", "100%")))
    t = SvgTurtle(drawing)
    Turtle._screen = t.screen
    Turtle._pen = t
    draw_func()
    drawing.save()


def main():
    write_file(draw_spiral, 'example.svg', size=("500px", "500px"))
    print('Done.')


if __name__ == '__main__':
    main()


来源:https://stackoverflow.com/questions/4071633/python-turtle-module-saving-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!