Python Turtle `while True` In Event Driven Environment
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).
Solution 1:
I can provide a crude example. Run your code above as-is. Start the snake moving. Click on the window's close button. Count the number of lines of error messages you get in the console. It could easily exceed two dozen.
Now try this same experiment with the following code which eliminates the while True:
:
from turtle import Screen, Turtle
class Head(Turtle):
def __init__(self):
super().__init__(shape="square")
self.penup()
self.direction = "stopped"
def move_snake():
if head.direction == "up":
head.sety(head.ycor() + 20)
screen.update()
screen.ontimer(move_snake, 200)
def go_up():
if head.direction != "down":
head.direction = "up"
# Snake head
head = Head()
# Set up screen
screen = Screen()
screen.tracer(0) # Disable animation so we can update screen manually.
# Event handlers
screen.onkey(go_up, "Up")
screen.listen()
move_snake()
screen.mainloop()
Your count of error messages should drop to zero. This is because the window close event happens in the same event loop as turtle motion.
There are other effects that you'll end up chasing later. This is just a simple, easily visible one.
Post a Comment for "Python Turtle `while True` In Event Driven Environment"