问题
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 200. The color of the lines are blue and the fill color, from top to bottom is grey0, grey14, grey28, …. How can I do this and make sure the picture fits onto the screen? (Each new rectangle goes below the previous one)
This is what I have so far, but I don't know how I can fill it:
import turtle
def rectangle(t, l, w):
for i in range(2):
t.right(90)
t.forward(l)
t.right(90)
t.forward(w)
me = turtle.Turtle()
me.color('blue')
me.pensize(2)
me.penup()
l = 2.5
w = 250
x = 50
y = 150
for i in range(9):
rectangle(me, l, w)
l = l*2
w = w
x = x
y = y
me.setposition(x,y)
me.pendown()
回答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()
回答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:
I reverted the outline color to black instead of blue so there'd be pure black nearby to compare the grey shades against.
来源:https://stackoverflow.com/questions/37472761/filling-rectangles-with-colors-in-python-using-turtle