[Tutor] can I make a while loop true again

Ian D duxbuz at hotmail.com
Thu Feb 13 12:05:42 CET 2014


Hi 
It has taken me longer than I thought to get back to this topic. tut.
Anyway thanks. I wondered why array was being mentioned ha ha
So have I got this correct in that when I run a turtle program I am in fact using this forever loop, so I do not need to use a while True loop at all really in a turtle gui program?

 

> To: tutor at python.org
> From: __peter__ at web.de
> Date: Tue, 11 Feb 2014 14:01:47 +0100
> Subject: Re: [Tutor] can I make a while loop true again
> 
> 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.
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor 		 	   		  


More information about the Tutor mailing list