【问题标题】:Getting KeyError while trying to chaneg text of kivymd label尝试更改 kivymd 标签文本时出现 KeyError
【发布时间】:2022-01-22 05:26:04
【问题描述】:

我目前正在开发 kivymd 应用程序。它并没有太大问题,但最近我在从 SettingsScreen 类调用 MainScreen 类函数时得到一个 KeyError ,该函数更改了 3 个标签的文本。 (抱歉,我可以直接把代码放到栈上,我给了google drive的链接(Main, kivy file))

主要 - https://drive.google.com/file/d/1fi9nPHdpKww9EMdaHmCCq9MI-wYpCD_X/view?usp=sharing

kivy - https://drive.google.com/file/d/1U3F-nXasoXO_ThApugaU_8_xggFzyjId/view?usp=sharing

error image

【问题讨论】:

    标签: python kivy kivymd


    【解决方案1】:

    当您从 SetScreen 调用 update_w() 函数时,您将“SetScreen”作为自己传递。因此,您的 update_w() 尝试编辑 ID 为“main_location_label”的标签,但不在 SetScreen 类中的 MainScreen 类中。但是您的 SetScreen 中没有“main_location_label”。如果你想编辑另一个 Screen 的小部件,你可以使用 self.manager.get_screen("Your Screen Name") 来完成,因此你需要一个 ScreenManager。

    from kivy.lang import Builder
    from kivymd.app import MDApp
    from kivy.uix.screenmanager import ScreenManager, Screen
    
    
    KV = """
    Manager:
        MainScreen:
        SetScreen:
    
    <MainScreen>: 
    
    name: "main_scr"
    FloatLayout:
        orientation: "vertical"
        
        MDLabel:
            id: main_location_label
            text: app.menu_location
            pos_hint: {"x":0.1, "y":0.32}
            
        MDLabel:
            id: main_desc_label
            text: app.menu_desc_text
            pos_hint: {"x":0.1, "y":0.273}
            
        MDLabel:
            id: main_temp_label
            text: app.menu_temp_text
            pos_hint: {"x":0.1, "y":0.248}
            
        MDRectangleFlatButton:
            text: "Go to Set Screen"
            pos_hint: {"x":0.05, "y":0.62}
            on_press: root.go_to_set()
            
    <SetScreen>: 
    name: "set_scr"
    FloatLayout:
        orientation: "vertical"
        
        MDRectangleFlatButton:
            text: "Change city"
            pos_hint: {"x":0.05, "y":0.62}
            on_press: root.change_w()
      """
    
    class MainScreen(Screen):
        def update_w(self):
            self.manager.get_screen("main_scr").ids["main_location_label"].text = "test"
    
    def go_to_set(self):
        self.manager.current = "set_scr"
    
    
    class SetScreen(Screen):
        def change_w(self):
            MainScreen.update_w(self)
            self.manager.current = "main_scr"
    
    class Manager(ScreenManager):
        pass
    
    
    class MainApp(MDApp):
    
        menu_location = "here"
        menu_desc_text = "there"
        menu_temp_text = "where"
    
        def build(self):
            return Builder.load_string(KV)
    
    
    
    if __name__ =="__main__":
        MainApp().run()
    

    【讨论】:

    • 欢迎来到 Stack Overflow!非常感谢你,你是救生员!我现在明白了,感谢您的帮助。
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2023-03-12
    • 2013-08-19
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多