PyNuts PyNuts - 1 year ago 320
Python Question

Python Turtle color change

im currently playing around with pythons turtle module and im trying to make a grid of opaque square shapes, say 30x30 that can change color based on some property (doesn't matter what property) my question is, is there anyway to change the color of a shape once its already been drawn down on the canvas?

Ive tried adding all the square shapes to an array, both stamps and polygons, but it seems impossible to change the color of any of them once they have been drawn.

i know stamp doesn't work because its like a footprint of where the turtle was but is there any method at all that allows for this with polygons or some other method im not aware of?

I didn't add any snippets of code because its a pretty basic question and can be used for many things.

Answer Source

Yes, you can do it. The key to this, and many complicated turtle problems, is using stamps. They are individually, or collectively, removable. And since they take on the shape of the turtle itself, they can be images or arbitrary polygons of any size or color you wish:

from turtle import Turtle, Screen
from random import randrange, choice

GRID = 15  # GRID by GRID of squares
SIZE = 30  # each square is SIZE by SIZE

def change():
    block = choice(blocks)

    position, color, stamp = block


    color = [min(int(primary * 1.5), 255) for primary in color]  # lighten color
    blocks.append((position, color, turtle.stamp()))

    screen.ontimer(change, 100)


screen = Screen()
screen.register_shape("block", ((HALF_SIZE, -HALF_SIZE), (HALF_SIZE, HALF_SIZE), (-HALF_SIZE, HALF_SIZE), (-HALF_SIZE, -HALF_SIZE)))

turtle = Turtle(shape="block", visible=False)

blocks = list()


for x in range(-HALF_GRID, HALF_GRID):
    for y in range(-HALF_GRID, HALF_GRID):
        turtle.goto(x * SIZE, y * SIZE)
        color = [randrange(32), randrange(32), randrange(32)]
        blocks.append((turtle.position(), color, turtle.stamp()))

screen.ontimer(change, 100)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download