问题描述
当我按退出键时,我试图让乌龟停止向前移动。当我按Escape键时,什么也没有发生!谁能告诉我为什么?一个解决方案将不胜感激。
import turtle
screen = turtle.Screen()
running = True
def stop():
running = False
print(running)
while running:
turtle.forward(1)
screen.onkey(stop,"Esc")
screen.listen()
解决方法
我看到您的代码有几个问题。主要的是global
中缺少的stop()
语句。次要的包括:混合turtle函数和对象API;使用键名“ Esc”而不是“ Escape”;将onkey()
和listen()
置于循环中;并可能通过您的while
循环阻止事件。
我相信这段代码应该可以满足您的要求:
from turtle import Screen,Turtle
running = True
def stop():
global running
running = False
def run():
if running:
turtle.forward(1)
screen.ontimer(run)
screen = Screen()
screen.onkey(stop,'Escape')
screen.listen()
turtle = Turtle()
run()
screen.mainloop()