简体   繁体   中英

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?

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()

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.

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