首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >事件驱动环境中的Python Turtle ` `While True`

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

Stack Overflow用户
提问于 2020-03-07 15:57:12
回答 1查看 497关注 0票数 1

我在Stack Overflow上读到过几篇文章,“像turtle这样的事件驱动环境永远不应该有while True:,因为它可能会阻塞事件(例如键盘)。”

下面是一个Python Turtle程序,它看起来工作得很好,但它使用了while True:构造。

谁能解释一下为什么这种方法是错误的,它造成了什么问题,正确的方法是什么才能达到同样的结果?

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-08 10:03:54

我可以提供一个粗略的例子。按原样运行上面的代码。让蛇开始移动。单击窗口的关闭按钮。统计您在控制台得到的错误消息行数。它很容易就会超过24个。

现在用下面的代码尝试相同的实验,它消除了while True:

代码语言:javascript
复制
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()

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

还有一些其他的效果,你稍后会去追逐。这只是一个简单的,容易看到的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60575538

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档