Search code examples
kivykivy-languagekivymd

How to get text from a KivyMD text field?


I am trying to get text from a text field, but I can't seem to get it right. I want to get the text from the MDTextField in the LoginScreen. This is my .kv file:

ScreenManager:
    LoginScreen:
    VaultScreen:
<LoginScreen>:
    id: login
    name: 'login'
    MDTextField:
        id: master_password
        hint_text: "Master Password"
        size_hint_x: None
        width: 200
        font_size: 18
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        password: True
    MDRectangleFlatButton:
        text: "Unlock"
        font_size: 12
        pos_hint: {"center_x": 0.5, "center_y": 0.4}
        on_release: app.verify()
<VaultScreen>:
    name: 'vault'
    MDLabel:
        text: 'Vault'
        halign: 'center'
    MDRectangleFlatButton:
        text: 'Back'
        pos_hint: {'center_x': 0.5, 'center_y': 0.1}
        on_press: root.manager.current = 'login'

And this is my .py file:

    from kivymd.app import MDApp
    from kivy.lang.builder import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    
    class ScMn(ScreenManager):
        pass
    
    class LoginScreen(Screen):
        pass
    
    class VaultScreen(Screen):
        pass
    
    class App(MDApp):
        def build(self):
            screen = Builder.load_file('passr.kv')
            return screen
        
        def verify(self):
            # this is where I want to get the text
            master = self.root.ids.login.master_password.text
            pass
        
    App().run()

When I try getting the contents of self.root.ids I get an empty dictionary.


Solution

  • Your code:

    self.root.ids.login.master_password.text
    

    is trying to access the ids of self.root, but self.root is the ScreenManager, and it has no ids. The ids defined in kv are stored in the ids dictionary of the widget that is the the root of the rule that contains the id definition. Since you define some ids in the <LoginScreen> rule, the ids will be in the LoginScreen object. So you must get a reference to the LoginScreen, and you can do that by using the get_screen() method, like this:

    self.root.get_screen('login').ids.master_password.text