Clock.schedule_interval 没有安排回调

Clock.schedule_interval doesn't schedule callback

我正在测试 kivy.clock.Clock.schedule_interval 函数的功能。

我的 schedule_interval 没有调用测试函数,而是在没有任何错误的情况下退出。

我不明白什么?我已经通过文档正确地模拟了这个测试。

from kivy.clock import Clock

class TestClass:

    def __init__(self):
        print("function __init__.")
        schedule = Clock.schedule_interval(self.test, 1)

    def test(self, dt):
        print("function test.")

if __name__ == '__main__':
    a = TestClass()

预期的输出应该是:

function __init__.
function test.
function test.
function test.
function test.
function test.
function test.

相反,我只是得到:

function __init__.

主要问题是您的程序在一秒钟之前就退出了。我不确定,但我还假设必须有一个 kivy 应用程序才能使时钟工作(我试图制作一个空的 while 循环而不是 运行 一个应用程序,但这没有帮助)。

这是一个简单的修复方法,可以提供所需的输出:

from kivy.clock import Clock
from kivy.base import runTouchApp


class TestClass:
    def __init__(self, **kwargs):
        print("function __init__.")
        schedule = Clock.schedule_interval(self.test, 1)

    def test(self, dt):
        print("function test.")


if __name__ == '__main__':
    test = TestClass()
    runTouchApp() # run an empty app so the program doesn't close

否则考虑让 TestClass 继承 kivy 的 App 和 运行 它与 TestClass().run() - 你会得到相同的结果。