Question

I'm trying to center the text of a TextInput vertically in Kivy. But no solution yet.

How can I do a valign for text input in the kv file? Also centering horizontally would be great to know, how to do it.

For labels I have checked the text align example from Kivy and there the alginment is working because there you can use 'valign' and 'halign' to do the alignment, but that's not available for TextInputs.

Maybe a trick with texture_size could help, but I need to check how this works. I have seen such a trick for a label, but I don't know if it works for the TextInput.

Here's my kv code that I have right now:

#: set Buttonheight1 40
BoxLayout:
    size_hint_y: None
    height: Buttonheight1
    Label:
        id: _number_label
        text: "Number:"
        font_size: 10
        size_hint_x: None
        width: 50
        canvas.after:
            Color:
                rgba: 1,0,0,.5
            Rectangle:
                pos: self.pos
                size: self.size
        TextInput:
            multiline: False
            size_hint_y: None
            height: _number_label.height
            #padding_top: 10
            font_size: 10
            text: str(self.font_size)
            #text: '%s, %s' % (self.get_center_x(), self.get_center_y()) #position test

Explanation of the kv code:

  • Buttonheight1 is a constant with kv set
  • Canvas.after is just for debugging the size of the label
  • The text of the text input shows font size as dummy text

Maybe it's simple to fix but I'm pretty new to Kivy and haven't found an example for this.

Here is how it looks like at the moment:

Screenshot TextInput

(Note: The OK button in the screenshot is not in the kv code above)

Was it helpful?

Solution

Looking at the api, all I could suggest is that you could try using padding, since you can specify:

Padding of the text: [padding_left, padding_top, padding_right, padding_bottom].

padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding].

Maybe usingpadding_top and/or padding_bottom for instance you could center the text vertically.

OTHER TIPS

As already suggested in the comments by AWolf. This seems to work best:

padding: [0, (self.height-self.line_height)/2]

What worked for me was using pos_hint as follows:

TextInput:
    multiline: False
    size_hint_y: None
    height: _number_label.height
    font_size: 10
    text: str(self.font_size)
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

I know this is old post .. I just wanna put the answer if anyone search for this again. Here is the solution:

In the kivy file add this line in the TextInput Properties

padding : 6,self.height/2 - self.font_size/2,6,6

I used this code in my custom text input.

As you see it works fine: enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top