Python Turtle `While True` in Event Driven Environment

送分小仙女□ 提交于 2021-02-10 20:47:51

问题


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()

回答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.



来源:https://stackoverflow.com/questions/60575538/python-turtle-while-true-in-event-driven-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!