Assem
Assem

Reputation: 12107

How to get the width in characters of a Kivy TextInput or Label

I have a TextInput in Kivy with long content. I want to know the width of the TextInput in characters. In other words, the length of the lines?

textinput = TextInput(text="Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps")

enter image description here

Upvotes: 3

Views: 1879

Answers (2)

Radek Glebicki
Radek Glebicki

Reputation: 1

Just to improve this discussion: In TextInput._lines_labels is field size (tuple) [0] with width of line. Each line. Just to iterate and look for the biggest and 'voilà'. This works with any font (prop or not).

Radek

Upvotes: 0

Nykakin
Nykakin

Reputation: 8747

You can check lines of TextInput using its _lines property. To get their lengths use len() builtin:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

from kivy.lang import Builder

Builder.load_string("""

<MyWidget>:
    Button:
        text: "Print width"
        on_press: print([len(line) for line in ti._lines])
    TextInput
        text: "Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps"
        id: ti
""")

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

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

Upvotes: 1

Related Questions