You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整Python Turtle复合形状的轮廓尺寸?

如何调整Python Turtle复合形状的轮廓尺寸?

我正在尝试创建一个复合形状,目前想要调整该新复合形状的轮廓尺寸。我创建形状的代码如下:

import turtle

points_1 = [...] # list of points
points_2 = [...] # list of points

shape = turtle.Shape('compound')
poly = turtle.Turtle()
poly.begin_poly()

for point_list in [points_1, points_2]:
    poly.goto(point_list [0][0], point_list[0][1])
    poly.begin_poly()
    for point in point_list[1:]:
        poly.goto(point[0], point[1])
    poly.goto(point_list[0][0], point_list[0][1])
    poly.end_poly()
    shape.addcomponent(poly.get_poly(), '', 'darkgreen')

screen = turtle.Screen()
screen.register_shape('my_turtle', shape)
screen.clearscreen()

my_shape = turtle.Turtle()
my_shape.shape('my_turtle')

turtle.done()

我尝试调整poly和my_shape的pensize,但都没有效果。请问如何实现多多边形复合形状的轮廓尺寸调整?


问题根源

你的代码有两个关键问题导致轮廓无法调整:

  1. 外层多了一个begin_poly()调用,导致多边形记录逻辑混乱
  2. addcomponent()的第二个参数(轮廓色)设为空字符串,就算改了笔宽也看不到轮廓;而且绘制前没设置有效笔宽

解决方法

按照以下步骤修改代码:

  • 移除外层多余的poly.begin_poly(),每个组件单独完成多边形记录
  • 在绘制组件前,给poly设置pensize(轮廓宽度)和pencolor(轮廓颜色)
  • 把addcomponent()的第二个参数改成你需要的轮廓颜色,别留空

修改后的完整代码

import turtle

# 替换成你自己的点集
points_1 = [(0, 0), (50, 0), (50, 50), (0, 50)]
points_2 = [(10, 10), (40, 10), (40, 40), (10, 40)]

shape = turtle.Shape('compound')
poly = turtle.Turtle(visible=False)  # 隐藏绘制用的海龟,避免干扰
poly.pensize(3)  # 这里设置轮廓的宽度
poly.pencolor('black')  # 这里设置轮廓的颜色

for point_list in [points_1, points_2]:
    poly.penup()
    poly.goto(point_list[0][0], point_list[0][1])
    poly.pendown()
    poly.begin_poly()
    for point in point_list[1:]:
        poly.goto(point[0], point[1])
    poly.goto(point_list[0][0], point_list[0][1])  # 闭合多边形
    poly.end_poly()
    # addcomponent参数:多边形、轮廓色、填充色
    shape.addcomponent(poly.get_poly(), 'black', 'darkgreen')

screen = turtle.Screen()
screen.register_shape('my_turtle', shape)

my_shape = turtle.Turtle()
my_shape.shape('my_turtle')

turtle.done()

补充说明

  • 复合形状的轮廓属性是在创建组件时确定的,后续修改my_shape的pensize没用,必须在绘制组件多边形时设置
  • 如果不需要填充,把addcomponent()的第三个参数设为空字符串即可
  • 用visible=False隐藏poly海龟,能避免绘制过程中出现多余图形

内容的提问来源于stack exchange,提问作者m-sarabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:03:21