[Tutor] can I make a while loop true again

Peter Otten __peter__ at web.de
Tue Feb 11 14:01:47 CET 2014


Ian D wrote:

> Thanks for the help on the last one.
> 
> Is it possible to restart a while loop? This doesn't work at all (surprise
> surprise)
> 
> import turtle as t
> 
> def start():
>     global more
>     more = True
>     
> def stop():
>     global more
>     more = False
> 
> more = True
> 
> while True:
>     while more:
> 
>         t.onkey(stop, "space")
>         t.onkey(start, "Up")
>         t.fd(1)
>         t.listen()

When you want your script to work like a typical GUI application you will 
soon reach the limits with turtle. turtle tries hard to hide it, but GUIs 
have an independent loop permanently running listening to user events and 
small functions to respond these events. 

To have the turtle start and stop I came up with the following which looks 
similar to normal GUI code. Instead of the explicit loop there is a function 
`step_forward` that may or may not reschedule itself depending on the state 
of the `running` flag.



import turtle

def step_forward():
    if running:
        turtle.forward(5)
        # call step_forward() again after 100 milliseconds:
        turtle.ontimer(step_forward, 100) 

def start():
    global running

    if not running:
        running = True
        step_forward()

def turn_left():
    turtle.left(10)

def turn_right():
    turtle.right(10)

def stop():
    global running
    running = False

running = False

turtle.delay(0)
turtle.onkey(start, "Up")
turtle.onkey(turn_left, "Left")
turtle.onkey(turn_right, "Right")
turtle.onkey(stop, "space")

turtle.listen()
turtle.mainloop()

As a bonus the turtle changes its direction when you hit the left or right 
array.



More information about the Tutor mailing list