我在Stack Overflow上读到过几篇文章,“像turtle这样的事件驱动环境永远不应该有while True:,因为它可能会阻塞事件(例如键盘)。”
下面是一个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()发布于 2020-03-08 10:03:54
我可以提供一个粗略的例子。按原样运行上面的代码。让蛇开始移动。单击窗口的关闭按钮。统计您在控制台得到的错误消息行数。它很容易就会超过24个。
现在用下面的代码尝试相同的实验,它消除了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()您的错误消息计数应降至零。这是因为窗口关闭事件发生在与海龟运动相同的事件循环中。
还有一些其他的效果,你稍后会去追逐。这只是一个简单的,容易看到的。
https://stackoverflow.com/questions/60575538
复制相似问题