Kivy button binding function with argument

2019-05-24 13:51发布

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()

2条回答
我命由我不由天
2楼-- · 2019-05-24 14:47

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)  
    ...
查看更多
我只想做你的唯一
3楼-- · 2019-05-24 14:51

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!

查看更多
登录 后发表回答