如何在Python中定期调用函数?

如何在Python中定期调用函数?,python,python-3.x,turtle-graphics,Python,Python 3.x,Turtle Graphics,我必须用海龟库编写一个游戏。 在规则中,有一个对象每X毫秒下降一次,直到达到某个条件 如果使用sleep(),屏幕将不再响应键盘事件。有没有办法定期“异步”调用函数? 非常感谢 Python-turtle提供了一个一次性解决方案: 您可以将其转换为每X毫秒一次的计时器事件: def my_function(): pass # do whatever if still_needed: # start again in the future if still needed

我必须用海龟库编写一个游戏。 在规则中,有一个对象每X毫秒下降一次,直到达到某个条件

如果使用sleep(),屏幕将不再响应键盘事件。有没有办法定期“异步”调用函数? 非常感谢

Python-turtle提供了一个一次性解决方案:

您可以将其转换为每X毫秒一次的计时器事件:

def my_function():
    pass  # do whatever

    if still_needed:  # start again in the future if still needed
        screen.ontimer(my_function, 100)  # repeat every 0.1 second

您应该阅读海龟图形模块的文档。为什么要投否决票?你能解释一下我为什么要拖延吗?它更不会回应。对不起,我的英语不好。我读了你的链接,我也这样做了,但不幸的是,它没有回应事件,但我只是发现了我的错误。我正在做:screen.onkey(x,“Down”)screen.onkeyrease(y,“Down”),但是第一个事件没有被触发,我把它改为“onkeypress”
def my_function():
    pass  # do whatever

    if still_needed:  # start again in the future if still needed
        screen.ontimer(my_function, 100)  # repeat every 0.1 second