How to turn turtle graphic output into an image file?

Viewed 2355

I have been trying to figure out how to output a Python turtle graphic as an image. I have checked multiple threads and still cannot quite figure it out (i've tried to make a postscript file and convert it but no luck and also tried to put the turtle onto a tkinter canvas and then save but no luck). I have installed pillow but still cannot convert the output. Below I have added a basic turtle graphic which if someone could show how to code it to make an image file (JPG or PNG) I would be grateful and explanation of what they did. I'm using Python 3.7.1 and Windows.

import turtle 

polygon = turtle.Turtle()

num_sides = 6
side_length = 70
angle = 360.0 / num_sides 

for i in range(num_sides):
    polygon.forward(side_length)
    polygon.right(angle)

turtle.done()
1 Answers

To save to a file, you can use postscript.

from Tkinter import *
from turtle import *
import turtle

polygon = turtle.Turtle()

num_sides = 6
side_length = 70
angle = 360.0 / num_sides 

for i in range(num_sides):
    polygon.forward(side_length)
    polygon.right(angle)

turtle.done()

ts = turtle.getscreen()

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

Your canvas (from Tkinter) is what has a postscript function, so you must use .getcanvas() to use postscript.

Related