我正在尝试制作一个程序,要求用户绘制一个形状以及在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()
答案 0 :(得分:0)
正如您使用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.listen()
一次,但是调用textinput()
或numinput()
会将监听器切换到弹出的对话框我们需要在对话框完成后再次显式调用turtle.listen()
。