python - Kivy TextInput horizontal and vertical align (centering text) -
how center text horizontally in textinput in kivy?
but want centralize text this:
and part of kv language:
boxlayout: orientation: 'vertical' label: markup: true text: '[b] type something... [/b]' size_hint: 1, 0.6 size: self.parent.size[0], 200 font_size: self.size[0] * 0.1 text_size: self.size halign: 'center' valign: 'middle' canvas.before: color: rgb: 0, 0, 204 rectangle: pos: self.pos size: self.size textinput: focus: true
how can center textinput's text?
afaik, there's no such thing aligning in same way it's in label
, however, can use padding
push position wherever want. keep in mind changing size of text affect centering, therefore you'll need recalculate on change of size (e.g. when working multiple devices, sizes, etc).
or there workaround, make textinput
invisible, use label
fetch touch event trigger textinput
(which open keyboard) , change label
's text on change of textinput
's text property. you'll lose possibility work cursor way , you'll need handle wrapping text.
example:
from kivy.app import app kivy.lang import builder kivy.uix.boxlayout import boxlayout builder.load_string(''' <test>: textinput: text: 't' font_size: 60 # left, right padding_x: [self.center[0] - self._get_text_width(max(self._lines, key=len), self.tab_width, self._label_cached) / 2.0, 0] if self.text else [self.center[0], 0] # top, bottom padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0] ''') class test(boxlayout): pass class testapp(app): def build(self): return test() testapp().run()
self._get_text_width(...)
method of textinput
. it's working core of widget might unstable (first example posted buggy because of mistake) ^^
now if padding_x
's values padd left
, right
, you'll need left side (the difference in using addition , substraction in right place), let's that:
- get longest substring in
textinput
- get width (because it's not consistent!) via fancy method
- substract
center[0]
coordinate
when we've centered x axis, let's go y. padding_y
's values top
, bottom
:
- padd down half of widget's
height
- get half of height of single line
- multiply number count of lines in
textinput
- substract number
self.height / 2.0
- bottom
0
, don't care it
note: max()
expects arguments , if there's no text
, max()
raise voice. we'll shut alternative left padding padding_x
using center:
<padding_x max> if self.text else [self.center[0], 0]
Comments
Post a Comment