2024-10-05 21:58:16 发布
网友
当我按下逃生键时,我试图让乌龟停止前进。当我按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()
我发现你的代码有几个问题。主语句是stop()中缺少的global语句。第二部分包括:混合turtle函数和对象API;使用键名“Esc”而不是“Escape”;把onkey()和listen()放在一个循环中;并可能使用while循环阻止事件
stop()
global
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()
我发现你的代码有几个问题。主语句是
stop()
中缺少的global
语句。第二部分包括:混合turtle函数和对象API;使用键名“Esc”而不是“Escape”;把onkey()
和listen()
放在一个循环中;并可能使用while
循环阻止事件我相信此代码应该满足您的要求:
相关问题 更多 >
编程相关推荐