如何调整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,但都没有效果。请问如何实现多多边形复合形状的轮廓尺寸调整?
问题根源
你的代码有两个关键问题导致轮廓无法调整:
- 外层多了一个
begin_poly()调用,导致多边形记录逻辑混乱 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
相关产品推荐
相关产品推荐

