Kivy屏幕转换带延时

时间:2016-07-21 17:31:56

标签: python-2.7 kivy kivy-language

目标是在我的主屏幕上有一个按钮,当按下延迟屏幕时将打开。然后需要5秒的时间延迟,之后屏幕将返回到家。

我的问题是与按下按钮相关的任何时间延迟,停止延迟屏幕打开

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.floatlayout import FloatLayout
import time


Builder.load_string("""
<MainScreen>:
    name: "main"
    FloatLayout:
        canvas:
        Rectangle:
            pos: self.pos
            size: self.size
    Button:
        background_color: 1, .8, .3, 1
        text:'Home'
        size_hint: .8,.2
        pos_hint: {'center_x':.5,'y':.1}
        on_press:root.manager.current = "delay"

<TimeDelay>:
    name: "delay"

    FloatLayout:
        Button:
            color: 0,1,0,1
            font_size: 25
            size_hint: 0.3,0.2
            text: "delay"
            pos_hint: {'center_x':0.5,'top':0.5}
            on_press:root.manager.current = "main"
""")
class MainScreen(Screen):
    pass

class TimeDelay(Screen):
        time.sleep(5)
        sm.switch_to('main')

sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(TimeDelay(name='delay'))

class timedelayapp(App):
    def build(self):
        return sm

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

1 个答案:

答案 0 :(得分:1)

如果您不想阻止用户界面,则不想使用time.sleep()。请改用kivy.clock

我不清楚是否要在按下按钮后5秒钟返回屏幕,或者在进入屏幕后5秒钟返回屏幕。按下按钮后,此示例将返回:

from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock, mainthread
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button


kv_string = """
ScreenManager:
    MainScreen:
    TimeDelay:

<MainScreen>:
    name: "main"
    FloatLayout:
        canvas:
            Rectangle:
                pos: self.pos
                size: self.size
    Button:
        background_color: 1, .8, .3, 1
        text:'Home'
        size_hint: .8,.2
        pos_hint: {'center_x':.5,'y':.1}
        on_press: root.manager.current = "delay"

<TimeDelay>:
    name: "delay"
    FloatLayout:
        ButtonDelay:
            color: 0,1,0,1
            font_size: 25
            size_hint: 0.3,0.2
            text: "delay"
            pos_hint: {'center_x':0.5,'top':0.5}
            ##on_press: root.manager.current = "main"
            on_press: self.clocked_switch()
"""


class MainScreen(Screen):
    pass


class TimeDelay(Screen):
    pass


class ButtonDelay(Button):
    def clocked_switch(self):
        Clock.schedule_once(self.switch_to_main, 5)

    def switch_to_main(self, *args):
        app = App.get_running_app()
        app.root.current = "main"


class TimeDelayApp(App):
    def build(self):
        root_widget = Builder.load_string(kv_string)
        return root_widget


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

如果您想在输入屏幕后返回5秒,请使用类似的时钟功能调用,但是来自Screen.on_enter()