【问题标题】:Change screen with .kv language on button click单击按钮时使用 .kv 语言更改屏幕
【发布时间】:2020-08-06 12:19:46
【问题描述】:

我知道 kivy 和 kivymd 但我还不知道它们的功能。我想在单击按钮时更改我的应用程序的屏幕,我该怎么做?谢谢。

下面是我的代码


from kivy.lang import Builder

from kivymd.app import MDApp

KV = '''

Screen:

    MDLabel: 
        text: "Material Design"
        font_style: "H3"
        theme_text_color: "Secondary"
        pos_hint: {"center_y": 0.9}
        halign: "center"
        
    MDRaisedButton:
        text: "Start"
        md_bg_color: 0, 0.26, 0.27, 1
        pos_hint: {"center_x": 0.5, "center_y": 0.2}
        on_press: root.manager.current = "main"

    MDRectangleFlatButton:
        text: "Exit"
        md_bg_color: rgba(197, 232, 204, 1)
        text_color: 0, 0.26, 0.27, 1
        pos_hint: {"center_x": 0.5, "center_y": 0.1}

        Screen:
            name: "main"

            MDLabel:
                text: "School guru"
                font_style: "H3"
                pos_hint: {"center_y": 0.8}
                halign: "center"
'''


class MaterialDesign(MDApp):
    def build(self):
        return Builder.load_string(KV)


MaterialDesign().run()

请尝试编辑我的代码并展示如何操作。

再次感谢您。

【问题讨论】:

    标签: python-3.x kivy kivymd


    【解决方案1】:

    首先,如果您要在Screens 之间切换,您需要一个ScreenManager

    这是您的代码的修改版本:

    from kivy.lang import Builder
    
    from kivymd.app import MDApp
    
    KV = '''
    ScreenManager:
        Screen:
        
            MDLabel: 
                text: "Material Design"
                font_style: "H3"
                theme_text_color: "Secondary"
                pos_hint: {"center_y": 0.9}
                halign: "center"
        
            MDRaisedButton:
                text: "Start"
                md_bg_color: 0, 0.26, 0.27, 1
                pos_hint: {"center_x": 0.5, "center_y": 0.2}
                on_press: root.current = "main"
        
            MDRectangleFlatButton:
                text: "Exit"
                md_bg_color: rgba(197, 232, 204, 1)
                text_color: 0, 0.26, 0.27, 1
                pos_hint: {"center_x": 0.5, "center_y": 0.1}
        
        Screen:
            name: "main"
        
            MDLabel:
                text: "School guru"
                font_style: "H3"
                pos_hint: {"center_y": 0.8}
                halign: "center"
    '''
    
    
    class MaterialDesign(MDApp):
        def build(self):
            return Builder.load_string(KV)
    
    
    MaterialDesign().run()
    

    所以ScreenManager 成为App 的根,其子代是ScreensMDRaisedButtonon_press 属性现在只是 root.current = "main"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多