用按键停止python turtle

2024-10-05 21:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

当我按下逃生键时,我试图让乌龟停止前进。当我按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()

Tags: importfalsetruedefscreenrunningforwardstop
1条回答
网友
1楼 · 发布于 2024-10-05 21:58:16

我发现你的代码有几个问题。主语句是stop()中缺少的global语句。第二部分包括:混合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()

相关问题 更多 >