Ask User What Shape To Draw And How Many In Python Turtle
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 h
Solution 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 seendefonkey_shape():
shape = turtle.textinput("Which shape?", "Enter a shape: triangle, square, pentagon, hexagon or octagon")
if shape.lower() notin 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()
defset_shape(shape, count):
turtle.penup()
turtle.sety(turtle.ycor() - 50)
turtle.pendown()
for radius inrange(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.
Post a Comment for "Ask User What Shape To Draw And How Many In Python Turtle"