【问题标题】:Python kivy app with kv and py files for every screenPython kivy 应用程序,每个屏幕都有 kv 和 py 文件
【发布时间】:2021-02-07 14:38:37
【问题描述】:

请解释我如何在 kivy 上创建一个应用程序,以便每个屏幕都有单独的 py 和 kv 文件。包括从屏幕调用的屏幕。事实上,我们需要一个表单的示例应用程序: 主屏-> 1屏-> 2屏

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    这是一种方法:

    main.py:

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager
    
    
    class WindowManager(ScreenManager):
        pass
    
    class TestApp(App):
        def build(self):
            return Builder.load_file('main.kv')  # this method can be eliminated if `main.kv` is renamed to `test.kv`
    
    if __name__ == '__main__':
        TestApp().run()
    

    main.kv:

    #  import the python files defining the Screens
    #: import Screen1 screen1.Screen1
    #: import Screen2 screen2.Screen2
    
    #  include the kv files for the other Screens
    #: include screen1.kv
    #: include screen2.kv
    
    WindowManager:
        Screen1:
        Screen2:
    

    screen1.py:

    from kivy.uix.screenmanager import Screen
    
    
    class Screen1(Screen):
        pass
    

    screen1.kv:

    <Screen1>:
        name: 'screen1'
        BoxLayout:
            Label:
                text: 'Screen1'
            Button:
                text: 'back'
                on_release: app.root.current = 'screen2'
    

    screen2.py:

    from kivy.uix.screenmanager import Screen
    
    
    class Screen2(Screen):
        pass
    

    screen2.kv:

    <Screen2>:
        name: 'screen2'
        BoxLayout:
            Label:
                text: 'Screen2'
            Button:
                text: 'back'
                on_release: app.root.current = 'screen1'
    

    当然,有不同的方法可以做到这一点。另一种方法是在main.py 中导入所有py 文件,然后在main.py 中为每个kv 文件使用Builder.load_file()

    如果您将所有文件(main.py 除外)放在名为subs 的子文件夹中,则只需对 main.py 进行更改:

    class TestApp(App):
        def build(self):
            return Builder.load_file('subs/main.kv')
    

    并更改为main.kv

    #  import the python files defining the Screens
    #: import Screen1 subs.screen1.Screen1
    #: import Screen2 subs.screen2.Screen2
    
    #  include the kv files for the other Screens
    #: include subs/screen1.kv
    #: include subs/screen2.kv
    
    WindowManager:
        Screen1:
        Screen2:
    

    【讨论】:

    • 太棒了!但据我了解,这种方法不允许您从其他目录下载 py 和 kv 文件。我还尝试在您的示例中使用来自 kivymd 的导航抽屉,但我也失败了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2023-01-24
    • 1970-01-01
    • 2021-02-06
    • 2018-05-25
    • 2015-07-10
    • 2021-09-20
    相关资源
    最近更新 更多