Search code examples
pythonkivytextinput

Kivy Character Counter from TextInput


again! I'm trying to add a character counter to my TextInput widget, but I don't know what parameters to pass for the four arguments, or much on how they're supposed to function. I checked the documentation, but it was putting me further into the woods. Anyway, here are the relevant snippets.

def charsLeft(window, keycode, text, modifiers):
     # Do some magic, pass some parameters, and then...
     ansLen.text = str(len(hidden.text) - len(answer.text))

And here's the code for my layout:

ansLen = Label(bold=True, halign="center", size_hint=(.2, .5), text_size=self.size, valign="middle")
answer = TextInput(id="sbt", multiline=False, size_hint=(.8, .5), text="")
answer.bind(keyboard_on_key_down=charsLeft)

I figure since it's on virtually every website, it ought to be fairly straightforward. I just don't know what I don't know here.


Solution

  • if you want to set a text counter you do not need to use keyboard_on_key_down, you just need to catch the text change for them we use bind, then we can use a lambda function to update the values since the bind returns the instance and the property changed, to set the value we use setattr:

    from kivy.app import App
    from kivy.uix.label import Label
    from kivy.uix.textinput import TextInput
    from kivy.uix.boxlayout import BoxLayout
    
    
    class MyApp(App):
        def build(self):
            layout = BoxLayout(orientation='vertical')
            answer = TextInput(multiline=False, text="", size_hint=(1, 0.5))
            ansLen = Label(bold=True, halign="center", text="", size_hint=(1, 0.5))
    
            answer.bind(text=lambda instance, text: setattr(ansLen, "text", str(len(text))))
            layout.add_widget(answer)
            layout.add_widget(ansLen)
            return layout
    
    
    if __name__ == '__main__':
        MyApp().run()