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

2024-04-29 06:54:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我展示了一个用Python的海龟模块绘制的孙子图案, 他要求看同心圆。 我想用乌龟的画会更快些 而不是写我自己的代码来生成一个圆。哈!我卡住了。 我看到产生的圆圈从海龟的周长开始 当前位置及其绘制方向取决于海龟的电流 运动方向,但我不知道该怎么做 同心圆。 我现在对有效的生产方式不感兴趣 同心圆:我想看看我要做什么 这种工作方式:

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)

Tags: posdef绘制方向color海龟turtleart
3条回答

你可以这样做:

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

它创建了下面的图片:

enter image description here

基本上,它将海龟向下移动一个半径长度,以保持所有圆的中心点在同一点上。

从文档中:

The center is radius units left of the turtle.

所以当你开始画一个圆的时候,不管乌龟在哪里,这个圆的中心离右边有一段距离。在每个圆之后,只需向左或向右移动一些像素,然后绘制另一个半径根据海龟移动的距离进行调整的圆。例如,如果绘制一个半径为50像素的圆,然后向右移动10像素,则会绘制另一个半径为40的圆,并且这两个圆应同心。

I am not at this point interested in an efficient way of producing concentric circles: I want to see what I have to do to get this way to work

为了解决OP的问题,对其原始代码进行更改以使其正常工作是很简单的:

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)

enter image description here

相关问题 更多 >