带参数的 Kivy 按钮绑定函数 [英] Kivy button binding function with argument

查看:26
本文介绍了带参数的 Kivy 按钮绑定函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何在 Kivy 中创建应用程序,但在向函数发送参数时遇到问题.我想将文本从输入发送到函数并打印出来.有人能告诉我该怎么做吗?

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

推荐答案

你必须从 "g" 获取文本,然后将其发送到按钮回调,有两种方法可以做到这一点,通过 lambda 函数,或调用你的类方法适用于它.

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 版本:

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

部分版本:

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

这篇关于带参数的 Kivy 按钮绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆