Alex Delarge
Alex Delarge

Reputation: 125

Python 3.Kivy. Is there any way to limit entered text in TextInput widget?

I'm writing kivy app and resently I faced with a problem of unlimited inputing text in TextInput widget. Is there any solution to this problem?

Upvotes: 6

Views: 2836

Answers (3)

Nico
Nico

Reputation: 23

(I can't comment so I am replying here)

Mova's answer is allowing one character over the limit. This is because the additional inserted character is not part of self.text until the end of the method.

class CapitalInput(TextInput):
    max_length = 15 # sets max length of TextInput to 15 chars

and the corrected method:

def insert_text(self, substring, from_undo = False):
        s = substring.upper().strip()
        if len(self.text)+1 <= self.max_length:
            return super(CapitalInput, self).insert_text(s, from_undo = from_undo)

Upvotes: 0

Mova
Mova

Reputation: 1

I needed to do something like this, as well, and also needed to capitalize the text input for uniformity. Here is what I came up with..

First, I created a new class:

class CapitalInput(TextInput):
    max_length = 15 # sets max length of TextInput to 15 chars

Inside the class, I created a method:

def insert_text(self, substring, from_undo = False):
        s = substring.upper().strip()
        if len(self.text) <= self.max_length:
            return super(CapitalInput, self).insert_text(s, from_undo = from_undo)

Note: You don't need to keep ".upper()" inside the method if you don't need it. If you remove that part, it'll work just fine.

Lastly, inside your program, when you need to use this modified TextInput, simply use this:

self.whatever_your_user_input_is_called = CapitalInput(multiline = False, padding_y = (8, 4))
self.window.add_widget(self.whatever_your_user_input_is_called)

And that's it! Hopefully this solution helped you as it did me.

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 243955

A possible solution is to create a new property and overwrite the insert_text method:

from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.properties import NumericProperty


class MyTextInput(TextInput):
    max_characters = NumericProperty(0)
    def insert_text(self, substring, from_undo=False):
        if len(self.text) > self.max_characters and self.max_characters > 0:
            substring = ""
        TextInput.insert_text(self, substring, from_undo)

class MyApp(App):
    def build(self):
        return MyTextInput(max_characters=4)


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

Upvotes: 9

Related Questions