使用 Kivy 在屏幕上打印和清除输出

Print and clear output on screen with Kivy

我正在尝试使用 kivy 在屏幕上打印一些文字。 我正在寻找的是打印第一个单词然后睡眠 2 秒然后清除第一个单词并打印第二个单词

我目前在做什么:

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout

from random import choice
from time import sleep

xWords = ["hello1", "hello2", "hello3", "hello4", "hello5"]

class Test(GridLayout):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        self.cols = 1
        for x in xrange(2):
            # I want it to show frist word then sleep 2 sec then clear first word from screen then print second word
            self.add_widget(Label(text = "[b]"+choice(xWords)+"[/b]", markup = True, font_size = "40sp"))
            sleep(2)
        # then clear all words in screen
        for x in xrange(5):
            # then show the new 4 words
            self.add_widget(Label(text = "[b]"+choice(xWords)+"[/b]", markup = True, font_size = "40sp"))

class TestApp(App):
    def build(self):
        return Test()

if __name__ == "__main__":
    TestApp().run()

我该怎么做?

不要使用 time.sleep,这会阻止图形用户界面,因为整个函数不会 return 直到 time.sleep 才会。

改用Clock.schedule_once。下面是一个在 2 秒内调用名为 update 的函数的简单示例,您可以在该函数内做任何您想做的事情,包括安排另一个函数。

from kivy.clock import Clock
class Test(GridLayout):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        Clock.schedule_once(self.update, 2)  # 2 is for 2 seconds
    def update(self, *args):
        self.clear_widgets()
        # then add some more widgets here