2023年11月9日 星期四

Kivy screen篇 TransitionBase 講解

簡述

根據官方解釋:

TransitionBase is used to animate 2 screens within the ScreenManager. This class acts as a base for other implementations

意思是TransitionBase本身無法被實例化,主要用途是讓其他Transition來繼承它。

TransitionBase使用技巧(適用於所有Transition):

(以下以SlideTransition做為示範)

1.duration:轉換Screen的時間

在main.py中寫上此段程式碼:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.properties import ObjectProperty


class AScreen(Screen):
    pass


class BScreen(Screen):
    pass


class sm(ScreenManager):
    #duration=3代表轉換時間為3秒
    a1 = ObjectProperty(SlideTransition(duration=3))


class MyApp(App):

    def build(self):
        return sm()


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

在my.kv中寫上此段程式碼:

<AScreen>:
    name: 'menu'

    BoxLayout:

        Button:
            text: 'Goto settings'
            on_press: root.manager.current = 'settings'

        Label:
            text: str(root.transition_progress)


<BScreen>:
    name: 'settings'

    BoxLayout:

        Label:
            text: str(root.transition_progress)

        Button:
            text: 'still settings'
            on_press: root.manager.current = 'menu'


<sm>:
    transition: root.a1

    AScreen:

    BScreen:

執行結果如下:

2.is_active:判斷此Transition是否正在被執行

3.manager:回傳此Transition的ScreenManager物件

在main.py中寫上此段程式碼:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
from kivy.properties import ObjectProperty


class AScreen(Screen):
    pass


class BScreen(Screen):
    pass


class sm(ScreenManager):
    a1 = ObjectProperty(SlideTransition(duration=3))

    def btn1(self):
        print(self.a1.is_active)
        print(self.a1.manager)


class MyApp(App):

    def build(self):
        return sm()


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

在以上程式碼中,btn1方法的內容為:列印a1的is_active屬性與manager屬性

在my.kv中寫上此段程式碼:

<AScreen>:
    name: 'menu'

    BoxLayout:

        Button:
            text: 'Goto settings'
            on_press: root.manager.current = 'settings'

        Label:
            text: str(root.transition_progress)


<BScreen>:
    name: 'settings'

    BoxLayout:

        Label:
            text: str(root.transition_progress)

        Button:
            text: 'still settings'
            on_press: root.manager.current = 'menu'


<sm>:
    transition: root.a1

    AScreen:

    BScreen:

執行結果如下:

當點擊'Goto settings' Button時,SlideTransition被執行,因此列印出True;當點擊'still settings' Button時,SlideTransition沒有被執行,因此列印出False。


沒有留言:

張貼留言

精選文章

Kivy UIX篇 widget篇 TabbedPanel類 event篇 講解