I have read in several posts here on Stack Overflow that "An event-driven environment like turtle should never have while True:
as it potentially blocks out events (e.g. keyboard)."
Here is a Python Turtle program that seems to work fine, but which uses the while True:
construct.
Could someone please explain why this approach is wrong, what problems is creates and what the correct way is to achieve the same result?
import turtle
import time
def move_snake():
"""
This function updates the position of the snake's head according to its direction.
"""
if head.direction == "up":
head.sety(head.ycor() + 20)
def go_up():
"""
callback for up key.
"""
if head.direction != "down":
head.direction = "up"
# Set up screen
screen = turtle.Screen()
screen.tracer(0) # Disable animation so we can update screen manually.
# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
# Snake head
head = turtle.Turtle()
head.shape("square")
head.penup()
head.direction = "stopped" # Cheeky use of instance property to avoid global variable.
while True:
move_snake()
screen.update()
time.sleep(0.2)
turtle.done()