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

如何使用Python turtle绘制中心在(0,0)坐标点的正多边形

解决方案

首先需要在代码顶部新增math库导入,用于三角函数计算:

import turtle
import math

然后替换「center the polygon」部分的代码为以下内容,即可适配你设置的45度初始朝向,实现正多边形几何中心落在(0,0):

# center the polygon
polygon_turtle.penup()
# 计算正多边形边心距(几何中心到任意一条边的垂直距离)
apothem = length / (2 * math.tan(math.pi / sides))
# 适配初始朝向45度的起始点坐标计算
rad = math.radians(45)
x = - (apothem * math.sin(rad) + (length/2) * math.cos(rad))
y = apothem * math.cos(rad) - (length/2) * math.sin(rad)
polygon_turtle.goto(x, y)
polygon_turtle.setheading(45)
polygon_turtle.pendown()

适用说明

  • 你当前测试的正八边形场景可以直接使用,完美符合中心在(0,0)的要求
  • 如果后续需要修改初始朝向,只需要把代码中所有的45替换为你设置的朝向角度即可通用

内容的提问来源于stack exchange,提问作者Miyuu Bo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 13:45:04