我正在尝试学习如何在 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/