python - 带参数的 Kivy 按钮绑定(bind)函数

标签 python button arguments bind kivy

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

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 函数,或者调用你的类方法来应用它。

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

关于python - 带参数的 Kivy 按钮绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586688/

相关文章:

java - 按钮光标显示不正确

ios - 快速更改联系人添加按钮颜色

android - 在 Horizo​​ntalScrollView 中获取子位置并滚动到它

c# - 如何在 C# 中从 Python 脚本调用特定方法?

c++ - 大括号初始值设定项列表作为函数参数

python - 如何动态改变kivy python中的 Canvas 颜色?

python - 使用 Flask 和 sqlalchemy 插入到 Db2

python - 播放音频文件后 pygame 没有响应

php - 为什么我不能在 Javascript 函数中将字符串作为参数传递?

python - 提高多段落扫描的 OCR 性能