Search code examples
pythonclasskivytextinput

How to pull a TextInput value into a different class and use it in Kivy?


I just want to pull a numerical value from a text input from my Second Class in to my Home Class, then be able to mess around with it in a function. I think I am having trouble grasping the parent-child relationship and syntax here.

Please help...

Python file:

    class Home(Screen):
    
        #Generic function
        def test(self):
    
            #grab numbers from text input here and be able to use the numeric value using ids
            #distance=..? I think normally it's self.root.distance.text
            print("distance text input variable here")
            pass
    
    class Second(Screen):
        pass  
    class WindowManager(ScreenManager):
        pass
   
    class HelpMe(App):
        def build(self):
            kv = Builder.load_file("help.kv")
            self.Home=Home()
            return kv
    
    if __name__ == "__main__":
        HelpMe().run()

kivy file:

WindowManager:
    Home:
    Second:
<Home>:
    name:"Home"
    GridLayout:
        cols:1
        Button:
            text:"Go"
            on_release:
                app.root.current="Second"
                root.manager.transition.direction="left"
<Second>:
    name:"Second"
    distance:distance
    GridLayout:
        cols:1
        TextInput:
            id:distance
            input_filter:"int"
        Button:
            text:"Back"
            #Initiate test code so I can work with values
            on_release:
                app.Home.test()
                app.root.current="Home"
                root.manager.transition.direction="right"

Solution

  • You can pass it from kv language to test function when your button is clicked:

    on_release:
        app.Home.test(distance)
        app.root.current="Home"
        root.manager.transition.direction="right"
    

    And then you read it on your function:

    def test(self, dist):
        print(dist.text)
    

    Remember that it comes as string. You have to change it to int() if you want to use as numerical.