mnrl mnrl - 1 year ago 536
Python Question

How to center text horizontally in a kivy text input?

I want to center a single line text in kivt text input.
I'm going to use padding

widget.padding = [ (self.textinput.width - width of line) / 2, 20, 0, 0]

but i can't find width of the line. how can i calculate or reach width of the line?
enter image description here

Answer Source

You could make a textinput behind a button, and make the button visualize as the text input.

When pushing the button, put the focus to the textinput, and update the buttons text.

I have made an example here.

from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.clock import Clock
from import App
from kivy import require


class MyWidget(BoxLayout):
    def __init__(self,**kwargs):

        self.orientation = "vertical"

        self.cur = False

        self.textinput = TextInput(text='',halign="center",multiline=False)

        self.button = Button(background_normal="",background_color=[0,0,0.1,1],font_size="40sp")

        self.my_float_layout = FloatLayout()


        self.add_widget(Label(text="type text below",font_size="40sp"))

        Clock.schedule_interval(self.cursor, 0.5)

    def cursor(self,dt):          # function to visualize a cursor
        if self.textinput.focus:
            cur_pos = self.textinput.cursor[0]
            if not self.cur:
                self.button.text = self.textinput.text[:cur_pos] + "|" + self.textinput.text[cur_pos:]
                self.cur = True
                self.button.text = self.textinput.text[:cur_pos] + " " + self.textinput.text[cur_pos:]
                self.cur = False
        elif self.cur:
            self.button.text = self.textinput.text + " "
            self.cur = False

    def on_text(self, *args):     # function to set the button text
        self.button.text = self.textinput.text

    def button_click(self,*args): # function to focus the input
        self.textinput.focus = True

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

if __name__ == "__main__":