询问用户要绘制什么形状以及 Python 海龟中有多少

Ask user what shape to draw and how many in Python turtle

我正在尝试制作一个程序,要求用户绘制一个形状以及要在 Python 乌龟中绘制多少个形状。我不知道如何制作对话框以便用户可以说出要添加的数量并使其正确 运行。任何帮助都会很棒!到目前为止,这是我的代码:

import turtle

steps = {"triangle": 3, "square": 4, "pentagon": 5, "hexagon": 6, "octagon": 7}

#this is the dialogue box for what shape to draw and moving it over a bit so the 
#next shape can be seen
def onkey_shape():
    shape = turtle.textinput("Enter a shape", "Enter a shape: triangle, 
square, pentagon, hexagon, octagon")
    if shape.lower() in steps:
        turtle.forward(20)
        set_shape(shape.lower())
    turtle.listen()  

def set_shape(shape):
    global current_shape
    turtle.circle(40, None, steps[shape])
    current_shape = shape





turtle.onkey(onkey_shape, "d")

turtle.listen()

turtle.mainloop()

正如您使用 textinput() 计算形状一样,您可以使用 numinput() 计算形状的数量:

count = numinput(title, prompt, default=None, minval=None, maxval=None)

这是对您的代码的修改,出于示例目的,它只绘制同心形状——您可以将它们绘制在您想要的位置:

import turtle

STEPS = {"triangle": 3, "square": 4, "pentagon": 5, "hexagon": 6, "octagon": 7}

# this is the dialogue box for what shape to draw and
# moving it over a bit so the next shape can be seen

def onkey_shape():
    shape = turtle.textinput("Which shape?", "Enter a shape: triangle, square, pentagon, hexagon or octagon")

    if shape.lower() not in STEPS:
        return

    count = turtle.numinput("How many?", "How many {}s?".format(shape), default=1, minval=1, maxval=10)

    turtle.penup()
    turtle.forward(100)
    turtle.pendown()

    set_shape(shape.lower(), int(count))

    turtle.listen()

def set_shape(shape, count):
    turtle.penup()
    turtle.sety(turtle.ycor() - 50)
    turtle.pendown()

    for radius in range(10, 10 - count, -1):
        turtle.circle(5 * radius, steps=STEPS[shape])
        turtle.penup()
        turtle.sety(turtle.ycor() + 5)
        turtle.pendown()


turtle.onkey(onkey_shape, "d")
turtle.listen()

turtle.mainloop()

您发现的棘手部分是,通常我们只在 turtle 程序中调用 turtle.listen() 一次,但调用 textinput()numinput() 会将侦听器切换到对话框弹出,因此我们需要在对话框完成后再次显式调用 turtle.listen()