I have made a strange program that can draw fractals and circles and spirals and I have been trying for hours to get a way to save the turtle output to a image file (preferably png or jpeg). I am getting the '_Screen' object has no attribute 'tk' when trying to use canvasvg.saveall() on turtle. here is the code:
import turtle
import random
import canvasvg
root = turtle.Screen()
drawing = 1
def save():
canvasvg.saveall("spircles.svg", root)
print("turning angle:")
turningangle = float(input())
print("size:")
forward = float(input())
print("spiral:")
try:
spiral = float(input())
if spiral == None:
spiral = random.random()
except:
pass
spiral = random.random()
turtle = turtle.Turtle(visible=False)
turtle.speed(speed=0)
turtle.hideturtle()
turtle.ht()
print("drawing. spiral:", spiral)
try:
while drawing == 1:
root.listen()
root.onkey(save, "s")
turtle.left(turningangle)
turtle.forward(forward)
turningangle = spiral
spiral = (spiral / turningangle)
except Exception as e:
drawing = 0
pass
print("done. press enter to exit. error:", e)
input()
exit()
turtle.mainloop()
anybody know an easy way of doing this? have tried PIL and it hasn't worked. I also want to not have to install third party programs. I want to be able to install some modules with pip (if necessary) and be able to run it without hassle. it should save to an image file when the user presses "s".
I have tried PIL, and canvasvg.saveall() and I want canvasvg.saveall() as it seems to be the easiest way of doing this.
CodePudding user response:
While Turtle uses tkinter.Canvas
to draw your shapes, the Screen
object is not a tkinter.Canvas
object, nor is it a tkinter.Widget
at all. Turtle provides a method for this task, it's called turtle.getcanvas
and you can use it on your Screen
object. So canvas = root.getcanvas()
should work just fine.
It seems like you can use canvasvg.saveall(filename, canvas)
, but be aware that they state not all items are supported.
def save():
canvas = root.getcanvas()
canvasvg.saveall("spircles.svg", canvas)