事件驱动环境中的 Python Turtle `While True` [英] Python Turtle `While True` in Event Driven Environment

查看:25
本文介绍了事件驱动环境中的 Python Turtle `While True`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Stack Overflow 上的几篇文章中读到像乌龟这样的事件驱动环境不应该有 while True:,因为它可能会阻止事件(例如键盘)."

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)."

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

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

推荐答案

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

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.

现在尝试使用以下代码进行相同的实验,以消除 while True::

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.

这篇关于事件驱动环境中的 Python Turtle `While True`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆