Skip to content Skip to sidebar Skip to footer

Filling Rectangles With Colors In Python Using Turtle

How can I draw a rectangle where: the smallest is 5 in height and each consecutive rectangle adds the first rectangles height, i.e. 5, 10, 15, …. The width of each rectangle is 2

Solution 1:

def filled_rectangle(t, l, w):
    t.begin_fill()
    for i in range(2):
            t.right(90)
            t.forward(l)
            t.right(90)
            t.forward(w)
    t.end_fill()

Solution 2:

Filling the rectangles is simple as @JoranBeasley has addressed. However, your specification of "smallest is 5" and "make sure the picture fits onto the screen" are in conflict. We need to fit the rectangles to the screen and take whatever starting size we get. Since each rectangle is twice the height of the next, then the starting rectangle is the available height divided by 2 (since we're doubling) raised to the power of the number of grey shades you want to represent:

from turtle import Turtle, Screen

def rectangle(t, l, w):
    t.begin_fill()
    for _ in range(2):
        t.right(90)
        t.forward(l)
        t.right(90)
        t.forward(w)
    t.end_fill()

screen = Screen()

me = Turtle(visible=False)
me.penup()

GREYS = [  # adjust to taste
    ('grey0' , '#000000'),
    ('grey14', '#242424'),
    ('grey28', '#474747'),
    ('grey42', '#6B6B6B'),
    ('grey56', '#8F8F8F'),
    ('grey70', '#B3B3B3'),
    ('grey84', '#D6D6D6'),
    ('grey98', '#FAFAFA'),
    ]

WIDTH = 2 ** (len(GREYS) + 1)  # depends on font and keep below screen.window_width()
x = WIDTH / 2  # rectangle() draws right to left -- move x right to center drawing

canvas_height = screen.window_height() * 0.90  # use most of the space available
length = canvas_height / 2 ** len(GREYS)  # determine starting length to fill canvas
y = canvas_height / 2  # begin at the top of canvas

fontsize = 1

for name, color in GREYS:
    me.fillcolor(color)
    me.setposition(x, y)

    me.pendown()
    rectangle(me, length, WIDTH)
    me.penup()

    if 4 <= fontsize <= length:
        font = ("Arial", fontsize, "bold")
        me.setposition(0, y - length / 2 - fontsize / 2)
        me.write(name, align="center", font=font)
    fontsize *= 2

    y -= length
    length *= 2

screen.exitonclick()

The width is more arbitrary than the height but I made it a function of the fontsize and the doubling so I could write the shade names in the rectangles:

enter image description here

I reverted the outline color to black instead of blue so there'd be pure black nearby to compare the grey shades against.


Post a Comment for "Filling Rectangles With Colors In Python Using Turtle"