2

目的是在我的主屏幕上有一个按钮,按下时会打开一个延迟屏幕。然后需要 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()
4

1 回答 1

2

如果您不想阻止 UI,则不想使用 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()

于 2016-07-21T18:52:24.383 回答