填充矩形很简单,正如@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()
宽度比高度更随意,但我把它作为字体大小和加倍的函数,所以我可以在矩形中写下阴影名称:
我将轮廓颜色恢复为黑色而不是蓝色,因此附近会有纯黑色来比较灰色阴影。