I am trying to learn how to create application in Kivy and I have problem with sending argument to the function. I want to send text from input to the function and print it. Can somebody tell me how can I do it ?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
class TutorialApp(App):
    def gratulation(self, *args):
        print args
    def build(self):
        boxLayout = BoxLayout(spacing=10,orientation='vertical')
        g = TextInput(text='Enter gratulation', 
                      multiline=False,
                      font_size=20,
                      height=100)
        button = Button(text='Send')
        button.bind(on_press=self.gratulation)  
        boxLayout.add_widget(g)
        boxLayout.add_widget(button)
        return boxLayout
if __name__ == "__main__":
    TutorialApp().run()
                Yo must get the text from "g" and then send it to the button callback, there is 2 ways of doing this, by a lambda function, or calling your class method aplying to it.
Lambda Version:
from __future__ import print_function ##Need to import this for calling print inside lambda
def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation', 
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = lambda:print(g.text)
    button.bind(on_press=buttoncallback)  
    ...
The partial version:
from functools import partial ##import partial, wich allows to apply arguments to functions returning a funtion with that arguments by default.
def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation', 
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = partial(self.gratulation, g.text)
    button.bind(on_press=buttoncallback)  
    ...
                        One way to do it:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
class TutorialApp(App):
    def gratulation(self, instance):
        print(self.g.text)
    def build(self):
        boxLayout = BoxLayout(spacing=10,orientation='vertical')
        self.g = TextInput(text='Enter gratulation',
                      multiline=False,
                      font_size=20,
                      height=100)
        button = Button(text='Send')
        button.bind(on_press=self.gratulation)
        boxLayout.add_widget(self.g)
        boxLayout.add_widget(button)
        return boxLayout
if __name__ == "__main__":
    TutorialApp().run()
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With