如何绘制矩形,其中:最小的高度为5,每个连续的矩形添加第一个矩形高度,即5,10,15,....每个矩形的宽度为200.线条的颜色为蓝色,填充颜色从上到下依次为grey0,grey14,grey28,.... 我该怎么做并确保图片适合屏幕? (每个新矩形都低于前一个矩形)
这是我到目前为止所做的,但我不知道如何填写它:
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()
答案 0 :(得分:1)
456\n789
答案 1 :(得分:0)
填充矩形非常简单,正如@JoranBeasley所解决的那样。但是,您最小的规格是5"和"确保图片适合屏幕"有冲突。我们需要将矩形适合屏幕并采用我们得到的任何起始尺寸。由于每个矩形的高度是下一个矩形的两倍,因此起始矩形是可用高度除以2(因为我们加倍),使其增加到您想要表示的灰色阴影数量的幂:
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()
宽度比高度更随意但我把它作为fontsize和doubleing的函数,所以我可以在矩形中写下阴影名称:
我将轮廓颜色还原为黑色而不是蓝色,因此附近有纯黑色来比较灰色阴影。