简体   繁体   中英

How to create new Python Turtle image each iteration?

I want to create 100 images via Python Turtle and each iteration there should be only 2 geometric shapes drawn on each image (files test0.jpg, test1.jpg etc). However, in my code each next image is drawn on the previous one, which causes collision. Can you help me please?

import turtle
import random
from PIL import Image


def generate(tur1):
    a = random.randint(2, 7)
    b = random.randint(2, 7)
    c = random.randint(50, 100)
    if a != 2:
        for i in range(a):
            tur1.forward(c)
            tur1.left(360.0 / a)
    else:
        tur1.circle(c)

    tur1.penup()
    tur1.goto(-200, 0)
    tur1.pendown()

    if b != 2:
        for j in range(b):
            tur1.forward(c)
            tur1.left(360.0 / b)
    else:
        tur1.circle(c)


for i in range(0, 100):
    tur2 = turtle.Turtle()
    tur2.color('green')
    tur2.speed(1)
    tur2.hideturtle()
    generate(tur2)
    screen = tur2.getscreen()
    screen.setup(600, 600)
    canvas = screen.getcanvas()
    canvas.postscript(file="test"+str(i)+".eps")
    img = Image.open("test"+str(i)+".eps")
    img.save("test"+str(i)+".jpg")

You need to use something like turtle.clear() (+1 @JohnnyMopp) or more likely turtle.reset() , or turtle.home() in combination with turtle.clear() , since you moved the turtle. A slight rework of your code:

from turtle import Screen, Turtle
from random import randint
from PIL import Image

def generate(turtle):
    a = randint(2, 7)
    b = randint(50, 100)

    if a == 2:
        turtle.circle(b)
    else:
        for _ in range(a):
            turtle.forward(b)
            turtle.left(360 / a)

    turtle.penup()
    turtle.setx(-200)
    turtle.pendown()

    a = randint(2, 7)

    if a == 2:
        turtle.circle(b)
    else:
        for _ in range(a):
            turtle.forward(b)
            turtle.left(360 / a)

screen = Screen()
screen.setup(600, 600)

turtle = Turtle()

for i in range(10):
    # inside loop only because reset() also resets these...
    turtle.hideturtle()
    turtle.color('green')
    turtle.speed('fastest')

    eps = "test" + str(i) + ".eps"
    jpg = "test" + str(i) + ".jpg"

    generate(turtle)
    canvas = screen.getcanvas()

    canvas.postscript(file=eps)
    img = Image.open(eps)
    img.save(jpg)

    turtle.reset()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM