How can I save turtle output as an image?

Question:

I have a code and draw circles. I would like to save the output as image. I am able to save the output as .svg file. But when i try to open, it only shows white page. I also tried to turn it to .jpg or .jpeg version. Again I see only the white screen. How can I solve the problem?

from turtle import Screen, Turtle
from random import randint
from svg_turtle import SvgTurtle
Asked By: atuatu

||

Answers:

This is a good example of why a minimal example is critcal in debugging. Once you remove all of the irrelevant drawing code, you’re left with:

def fiber_circle(fiber):
    # ...
    fiber = Turtle()
    # now start drawing...

# ...
fiber = SvgTurtle(width, height)
fiber_circle(fiber)
# ...

You’ve gone through a lot of trouble to create a SvgTurtle fiber only to overwrite it with a plain old Turtle() instance before you draw anything with it.

Remove fiber = Turtle() and use the SvgTurtle fiber instead.

This creates new problems:

  1. Nothing shows up on the screen.
  2. Nothing shows up in the SVG.

Problem 1 can be solved by mirroring all fiber commands with a Screen turtle and may not even matter for your use case. If you don’t care about the screen, you can keep it off, or temporarily bring it up to validate your drawing logic by swapping in a Turtle() for the fiber during development.

Problem 2 seems to be a characteristic in the SVG library which is that it doesn’t write sprite positions to SVG. stamp rather than showturtle works.

Here’s a new version that implements these changes with a few simplifications (map was overly complex):

from random import randint
from svg_turtle import SvgTurtle
from turtle import Turtle


def fiber_circle(fiber, width, height):
    fiber_r = 35
    fiber_num = 50
    cursor_size = 20
    fiber.hideturtle()
    fiber.color("black")
    fiber.shape("circle")
    fiber.shapesize(fiber_r / cursor_size)
    fiber.speed("fastest")
    fiber.penup()
    fibers = []

    for _ in range(fiber_num):
        fiberr = fiber.clone()
        fiberr.setposition(
            randint(fiber_r - width / 2, width / 2 - fiber_r),
            randint(fiber_r - height / 2, height / 2 - fiber_r),
        )

        while any((a.distance(fiberr) < fiber_r for a in fibers)):
            fiberr.setposition(
                randint(fiber_r - width / 2, width / 2 - fiber_r),
                randint(fiber_r - height / 2, height / 2 - fiber_r),
            )

        fiberr.stamp()
        fibers.append(fiberr)

def write_file(fiber_circle, filename, width, height):
    fiber = SvgTurtle(width, height)
    fiber_circle(fiber, width, height)
    fiber.save_as(filename)

def main():
    write_file(fiber_circle, "fiber.svg", 500, 500)
    print("Done.")


if __name__ == "__main__":
    main()
Answered By: ggorlen