Python 事件驱动环境中的 Turtle `While True`

Python Turtle `While True` in Event Driven Environment

我在 Stack Overflow 上的几篇文章中读到 "An event-driven environment like turtle should never have while True: as it potentially blocks out events (e.g. keyboard)."

这是一个 Python Turtle 程序,它似乎运行良好,但它使用了 while True: 结构。

谁能解释一下为什么这种方法是错误的,会产生什么问题以及达到相同结果的正确方法是什么?

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

我可以提供一个粗略的例子。 运行 您上面的代码按原样。开始蛇移动。单击 window 的关闭按钮。计算您在控制台中收到的错误消息的行数。它很容易超过两打。

现在用下面的代码尝试同样的实验,它消除了 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()

您的错误消息计数应该降为零。这是因为 window 关闭事件发生在与海龟运动相同的事件循环中。

还有其他效果您稍后会追求。这只是一个简单易懂的例子。