如何在 Kivy 中使用时间睡眠

How to use time sleep in Kivy

我的应用只有 1 个按钮。我想在 on_press 事件中更改它的颜色,然后等待 5 秒,然后显示一个弹出窗口。

我的尝试:

#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')

from random import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from random import random
from random import choice
from kivy.properties import StringProperty
import time

my_popup = Popup(title='Test popup',
    content=Label(text='Hello world'),
    size_hint=(None, None))


Builder.load_string("""
<Highest>:
    GridLayout:
        cols: 1
        Button:
            id: btn_0
            text: "Hi"
            on_press: root.new()
""")

class Highest(Screen):
    def new(self):
        self.ids['btn_0'].background_color = 1.0, 0.0, 0.0, 1.0
        time.sleep(5)
        my_popup.open()


# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))

class TestApp(App):

    def build(self):
        return sm

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

但是我的代码显示弹出窗口并在 5 秒后改变颜色。请帮忙。

在 Kivy 中,事件是使用 Clock 对象安排的。在您的情况下,您可以随时使用 Clock.schedule_once 调用回调。只需将您的 Highest class 重写为:

class Highest(Screen):
def new(self):
    self.ids['btn_0'].background_color = 1.0, 0.0, 0.0, 1.0
    Clock.schedule_once(my_popup.open, 5)

您在此处安排 my_popup.open() 在 5 秒后完成。