我正在尝试学习如何在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()
答案 0 :(得分:4)
哟必须从“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)
...
答案 1 :(得分:0)
一种方法:
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()
希望它有所帮助!