如何在 Python 3 中使用 Turtle 绘制圆

How to draw Circle using Turtle in Python 3

这是我已经拥有的代码,但它说我需要定义 'polygon' 我知道我需要,但不确定我一直在尝试的方式和不同的方式一直在给出我的错误。

import turtle
import math

apple=turtle.Turtle()

def draw_circle(t, r):
    circumference = 2 * math.pi * r
    n = 50
    length = circumference / n
    polygon(t, n, length)

draw_circle(apple, 15)

turtle.exitonclick()

使用圆圈法

import turtle
import math

apple=turtle.Turtle()

def draw_circle(t, r):
    turtle.circle(r)

draw_circle(apple, 15)

turtle.exitonclick()

这是一个多边形函数:

def drawPolygon (ttl, x, y, num_side, radius):
  sideLen = 2 * radius * math.sin (math.pi / num_side)
  angle = 360 / num_side
  ttl.penup()
  ttl.goto (x, y)
  ttl.pendown()
  for iter in range (num_side):
    ttl.forward (sideLen)
    ttl.left (angle)

以下是使用方法:

def main():
  # put label on top of page
  turtle.title ('Figures')

  # setup screen size
  turtle.setup (800, 800, 0, 0)

  # create a turtle object
  ttl = turtle.Turtle()

  # draw equilateral triangle
  ttl.color ('blue')
  drawPolygon (ttl, -200, 0, 3, 50)

  # draw square
  ttl.color ('red')
  drawPolygon (ttl, -50, 0, 4, 50)

  # draw pentagon
  ttl.color ('forest green')
  drawPolygon (ttl, 100, 0, 5, 50)

  # draw octagon
  ttl.color ('DarkOrchid4')
  drawPolygon (ttl, 250, 0, 8, 50)

  # persist drawing
  turtle.done()

main()

别忘了加上import turtle, math

如果确实需要定义多边形。

from turtle import *
import math

apple = Turtle()

def polygon(t, n, length):
    for i in range(n):
        left(360/n)
        forward(length)

def draw_circle(t, r):
    circumference = 2 * math.pi * r
    n = 50
    length = circumference / n
    polygon(t, n, length)
    exitonclick()

draw_circle(apple, 30)