Python Turtle:使用circle()方法绘制同心圆

5 投票
5 回答
50858 浏览
提问于 2025-04-18 12:31

我在给我的孙子展示用Python的Turtle模块画的图案时,他想看看同心圆。我觉得用turtle的circle()函数来画会比自己写代码画圆快。结果,我卡住了。我发现这个函数画的圆是从海龟当前的位置开始的,而且画的方向也取决于海龟当前的运动方向,但我就是搞不清楚怎么才能画出同心圆。此时我并不想找出一种高效的方法来画同心圆,我只是想知道怎么才能让这个方法奏效:

def turtle_pos(art,posxy,lift):
    if lift:
        art.penup()
        art.setposition(posxy)
        art.pendown()

def drawit(tshape,tcolor,pen_color,pen_thick,scolor,radius,mv):
    window=turtle.Screen() #Request a screen
    window.bgcolor(scolor) #Set its color

    #...code that defines the turtle trl

    for j in range(1,11):
        turtle_pos(trl,[trl.xcor()+mv,trl.ycor()-mv],1)
        trl.circle(j*radius)

drawit("turtle","purple","green",4,"black",20,30)

5 个回答

0

我现在并不想找出一种高效的方法来画同心圆:我只是想看看要怎么做才能让这个方法有效。

为了回答提问者的问题,修改他们原来的代码让它能正常工作其实很简单:

turtle_pos(trl, [trl.xcor() + mv, trl.ycor() - mv], 1)
trl.circle(j * radius)

变成:

turtle_pos(trl, [trl.xcor(), trl.ycor() - mv], 1)
trl.circle(j * mv + radius)

完整的代码加上上面的修复和一些样式的修改:

import turtle

def turtle_pos(art, posxy, lift):
    if lift:
        art.penup()
        art.setposition(posxy)
        art.pendown()

def drawit(tshape, tcolor, pen_color, pen_thick, scolor, radius, mv):
    window = turtle.Screen()  # Request a screen
    window.bgcolor(scolor)  # Set its color

    #...code that defines the turtle trl
    trl = turtle.Turtle(tshape)
    trl.pencolor(pen_color)
    trl.fillcolor(tcolor)  # not filling but makes body of turtle this color
    trl.width(pen_thick)

    for j in range(10):
        turtle_pos(trl, (trl.xcor(), trl.ycor() - mv), True)
        trl.circle(j * mv + radius)

    window.mainloop()

drawit("turtle", "purple", "green", 4, "black", 20, 30)

在这里输入图片描述

0

现在我给你提供一段可以画同心圆的具体代码。

import turtle
t=turtle.Turtle()
for i in range(5):
  t.circle(i*10)
  t.penup()
  t.setposition(0,-(i*10))
  t.pendown()
turtle.done()
2

根据文档的说明:

圆心在海龟的左边,距离是半径的单位。

这就是说,当你开始画一个圆的时候,圆心的位置是在海龟的右边,距离海龟一定的距离。每画完一个圆后,你可以向左或向右移动几个像素,然后再画一个新的圆,这个新圆的半径要根据海龟移动的距离来调整。例如,如果你画了一个半径为50像素的圆,然后向右移动了10像素,那么你接下来画的圆的半径就应该是40像素,这样两个圆就会重叠在一起。

5

你可以这样做:

import turtle

turtle.penup()
for i in range(1, 500, 50):
    turtle.right(90)    # Face South
    turtle.forward(i)   # Move one radius
    turtle.right(270)   # Back to start heading
    turtle.pendown()    # Put the pen back down
    turtle.circle(i)    # Draw a circle
    turtle.penup()      # Pen up while we go home
    turtle.home()       # Head back to the start pos

这样就会生成下面的图片:

在这里输入图片描述

简单来说,这段代码把海龟(图形绘制工具)向下移动了一个半径的长度,这样所有圆的中心点就保持在同一个位置了。

撰写回答