要使用turtle方法和功能,我们需要导入turtle。 “龟” 附带标准 Python 包,无需外部安装。 执行海龟程序的路线图分为 3 个步骤: a- 导入海龟模块。 b- 创建一只乌龟来控制。 c- 使用海龟方法进行绘制。
使用说明:
这是我的代码:
from turtle import *
# Set up the screen and turtle
screen = Screen()
t = Turtle()
t.speed(1) # You can adjust the speed as needed
# Define colors
color_fill = "yellow"
color_border = "blue"
border_size = 5
gap_size = 10
rectangle_width = 50 # Adjust the width as needed
rectangle_height = 100 # Adjust the height as needed
circle_radius = 50 # Adjust the radius for the circular space
# Function to draw a colored rectangle with a border
def draw_rectangle_with_border(fill_color, border_color, border_size, width, height):
# Draw the border
t.pencolor(border_color)
t.pensize(border_size)
t.penup()
t.goto(-width / 2, -height / 2)
t.pendown()
for _ in range(2):
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
# Draw the fill
t.fillcolor(fill_color)
t.begin_fill()
for _ in range(2):
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.end_fill()
# Set the starting position
t.penup()
t.goto(0, -rectangle_height / 2)
# Draw the central circular space
t.pencolor("white") # Set the color to match the background
t.fillcolor("white")
t.penup()
t.goto(0, -circle_radius)
t.pendown()
t.begin_fill()
t.circle(circle_radius)
t.end_fill()
# Calculate the total number of rectangles to form a complete circle
num_rectangles = 8
angle = 360 / num_rectangles
# Draw the circular pattern of rectangles around the central circular space
for _ in range(num_rectangles):
draw_rectangle_with_border(color_fill, color_border, border_size, rectangle_width, rectangle_height)
t.penup()
t.goto(0, -rectangle_height / 2)
t.left(angle)
t.forward(gap_size)
# Close the window on click
screen.exitonclick()
这是输出:
我想要这个输出:
尽管您不需要单独绘制填充和轮廓,但您的矩形看起来相当不错。所缺少的只是从起点到每个方块的角点向前和向后移动:
from turtle import Screen, Turtle
def draw_rectangle_with_border(t, width, height):
t.pendown()
t.begin_fill()
for _ in range(2):
t.forward(height)
t.left(90)
t.forward(width)
t.left(90)
t.end_fill()
t.penup()
def draw_rectangles_in_circle(t):
color_fill = "yellow"
color_border = "blue"
border_size = 9
rectangle_width = 60
rectangle_height = 90
circle_radius = 110
num_rectangles = 8
angle = 360 / num_rectangles
t.pencolor(color_border)
t.pensize(border_size)
t.fillcolor(color_fill)
t.penup()
for _ in range(num_rectangles):
t.forward(circle_radius)
draw_rectangle_with_border(t, rectangle_width, rectangle_height)
t.backward(circle_radius)
t.left(angle)
if __name__ == "__main__":
draw_rectangles_in_circle(Turtle())
Screen().exitonclick()
现在,实际图像在正方形之间有一点重叠,因此您可以做一个小转弯来实现这一点并根据口味进行调整:
# ...
t.penup()
t.right(5)
for _ in range(num_rectangles):
t.forward(circle_radius)
t.left(5)
draw_rectangle_with_border(t, rectangle_width, rectangle_height)
t.right(5)
t.backward(circle_radius)
t.left(angle)
# ...
请注意,
from turtle import *
的建议很差。这将超过 100 个方法添加到全局命名空间中,很容易遇到别名错误以及实例和函数接口之间的混淆。您仅使用海龟中的 Screen
和 Turtle
,因此仅明确导入您需要的内容。