简体   繁体   中英

Kivy TextInput autocompletion. How to get same result using kv file?

I would like to use a kv file for the TextInput in my code, but I don't know how to get the same result, how to translate this line of code:

text_input.bind(text=self.action)

someone could help me?

from kivy.app import App
from kivy.lang import Builder
from textwrap import dedent

class MyApp(App):

    def action(self,instance,value):

        word_list = ["hello", "hi", "man", "girl"]

        self.root.suggestion_text = ''

        val = value[value.rfind(' ') + 1:]

        if not val:
            return
        try:
            word = [word for word in word_list
                    if word.startswith(val)][0][len(val):]
            if not word:
                return
            self.root.suggestion_text = word
        except IndexError:
            print('Index Error.')

    def build(self):
        text_input = Builder.load_string(dedent('''
            TextInput
        '''))
        text_input.bind(text=self.action)
        return text_input

if __name__ == "__main__":
    MyApp().run()

You need to bind on_text event with the action method, using app keyword to refer to your MyApp instance ( app.action(args) ) and the “:” syntax:

from kivy.app import App
from kivy.lang import Builder
from textwrap import dedent


class MyApp(App):

    def action(self,instance,value):
        word_list = ["hello", "hi", "man", "girl"]
        self.root.suggestion_text = ''
        val = value[value.rfind(' ') + 1:]

        if not val:
            return
        try:
            word = [word for word in word_list
                    if word.startswith(val)][0][len(val):]
            if not word:
                return
            self.root.suggestion_text = word
        except IndexError:
            print('Index Error.')

    def build(self):
        text_input = Builder.load_string(dedent('''
            TextInput:
                on_text: app.action(self, self.text)
        '''))
        return text_input

if __name__ == "__main__":
    MyApp().run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM