Python Turtle Module- Saving an image

后端 未结 2 858
天涯浪人
天涯浪人 2020-12-09 02:08

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 eas

相关标签:
2条回答
  • 2020-12-09 02:19
    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.

    0 讨论(0)
  • 2020-12-09 02:35

    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()
    
    0 讨论(0)
提交回复
热议问题