【问题标题】:Is there a way to draw multiple circles with Turtle based on user input?有没有办法根据用户输入用 Turtle 绘制多个圆圈?
【发布时间】:2022-01-06 01:44:54
【问题描述】:

我想创建如下所示的内容:many circles of the same size next to each other

但是,我希望由用户输入确定圈数。我似乎找不到任何关于如何解决此问题的信息。

这是我到目前为止所拥有的,但它并没有实现我的目标。

import turtle
 
print("How many circles?")
circnum = input()

#Summoning the turtle
t = turtle.Turtle()

#circling the circle
for i in circnum:
  r = 25
  t.circle(r)

非常感谢!

【问题讨论】:

    标签: python python-3.x geometry turtle-graphics python-turtle


    【解决方案1】:

    您需要将 circnum 设为一个数字,以便您可以创建 range 进行迭代,并且您需要在圆圈之间移动海龟,这样您就不会只是在其自身之上绘制相同的圆圈及以上。

    import turtle
     
    print("How many circles?")
    circnum = int(input())
    
    #Summoning the turtle
    t = turtle.Turtle()
    
    #circling the circle
    for _ in range(circnum):
      t.circle(25)
      t.forward(5)
    

    【讨论】:

    • 这和我想象的完全一样,非常感谢!
    【解决方案2】:

    我同意@Samwise 的建议 (+1),但如果您使用的是标准 Python 3 乌龟,而不是一些旧版本或子集,我说摆脱 input() 并完全使用乌龟:

    from turtle import Screen, Turtle
    
    RADIUS = 25
    DISTANCE = 10
    
    screen = Screen()
    
    number_circles = screen.numinput("A Circle in a Spiral", "How many circles?", default=10, minval=1, maxval=30)
    
    if number_circles:
        # Summoning the turtle
        turtle = Turtle()
        turtle.speed('fast')  # because I have little patience
    
        # Circling the circle
        for _ in range(int(number_circles)):  # numinput() returns a float
            turtle.circle(RADIUS)
            turtle.forward(DISTANCE)
    
        screen.exitonclick()
    else:
        # user hit 'Cancel' in the number input dialog
        screen.bye()
    

    【讨论】:

    • 当我尝试运行它时(我正在使用 Replit,不知道这是否重要)我在第 8 行收到错误:AttributeError: 'Screen' object has no attribute 'numinput' on第 8 行
    • @ManganeseHeptoxide,是的,Repl.it 是我在序言中所说的海龟“子集”的一个例子。他们不使用 Python 附带的 turtle.py,而是使用他们自己的实现来使其在 Web 浏览器中工作。
    猜你喜欢
    • 2013-12-02
    • 2014-12-22
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多