问题
I am trying to make a program that asks the user to draw a shape and how many of that shape to draw in Python turtle. I dont know how to make the dialogue box so the user can say how many to add and make it run correctly. Any help will be awesome! Here is my code so far:
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()
回答1:
Just as you used textinput()
to get your shape, you can use numinput()
to get your count of how many shapes:
count = numinput(title, prompt, default=None, minval=None, maxval=None)
Here's a rework of your code, which for example purposes just draws concentric shapes -- you draw them where you want them:
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()
The tricky part, that you figured out, is that normally we only call turtle.listen()
once in a turtle program but invoking textinput()
or numinput()
switches the listener to the dialog box that pops up so we need to explicitly call turtle.listen()
again after the dialogs finish.
来源:https://stackoverflow.com/questions/44561523/ask-user-what-shape-to-draw-and-how-many-in-python-turtle