How to Assign the Kivy Input Text to a variable immediately on pressing Enter?

半腔热情 提交于 2020-04-16 03:15:43

问题


I'm trying to create a user-interface for a personal assistant.
I want the user to input a text and when he presses enter,i want to do something(' say print a text') and also automatically clear the input field. This is my code:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
class TetraApp(App):

    def build(self):
        Window.size=(875,600)
        Window.clearcolor = (0, 1, 1, 1)
        b = BoxLayout(orientation ='vertical')
        self.t = TextInput(hint_text='Say Something...', size_hint=(1,0.1), multiline=False)
#the multiline disables on enter. i want it to do a process on enter.
        b.add_widget(self.t)
        # code here to go to enterClicked() when enter is pressed and to clear input field
        Window.borderless=True
        return b
    def enterClicked(self):
        if 'hello' in self.t.text:
            print("hello user")
if __name__=='__main__':
    app=TetraApp()
    app.run()

I couldnt find any tutorials for this.


回答1:


You can try to bind an action to your TextInput like this:

self.t = TextInput(hint_text='Say Something...', size_hint=(1,0.1),multiline=False)
self.t.bind(on_text_validate=self.enterClicked)
b.add_widget(self.t)
def enterClicked(self,t):
    if 'hello' in self.t.text:
        print("hello user")
    self.t.text=''

The on_text_validate action is triggered only in multiline=False mode when the user hits ‘enter’.

To clear the input field, try to make a method that clears the text (similar to your enterClicked) and bind this method as well to the TextInput with on_text_validate. Let me know if it worked.



来源:https://stackoverflow.com/questions/60990739/how-to-assign-the-kivy-input-text-to-a-variable-immediately-on-pressing-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!