简体   繁体   中英

How to draw Circle using Turtle in Python 3

This is the code that I have already, but it is saying I need to define 'polygon' which I know I need to, but not exactly sure how and different ways that I have been trying just keeps giving me errors.

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()

use the circle method

import turtle
import math

apple=turtle.Turtle()

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

draw_circle(apple, 15)

turtle.exitonclick()

here is a function for polygon:

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)

Here is how you use it:

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()

Dont Forget to add import turtle, math

If you really need to define a polygon.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM