问题
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