Skip to content

Instantly share code, notes, and snippets.

@a740122
Forked from MelleB/Kivy Aligned TextInput
Created May 21, 2017 10:40
Show Gist options
  • Save a740122/4dcbe551ddb9e3e4b827ebc1dfc889c6 to your computer and use it in GitHub Desktop.
Save a740122/4dcbe551ddb9e3e4b827ebc1dfc889c6 to your computer and use it in GitHub Desktop.
Kivy Aligned Text Input - halign + valign for TextInput
from kivy.uix.textinput import TextInput
from kivy.properties import StringProperty
DEFAULT_PADDING = 6
class AlignedTextInput(TextInput):
halign = StringProperty('left')
valign = StringProperty('top')
def __init__(self, **kwargs):
self.halign = kwargs.get("halign", "left")
self.valign = kwargs.get("valign", "top")
self.bind(on_text=self.on_text)
super().__init__(**kwargs)
def on_text(self, instance, value):
self.redraw()
def on_size(self, instance, value):
self.redraw()
def redraw(self):
"""
Note: This methods depends on internal variables of its TextInput
base class (_lines_rects and _refresh_text())
"""
self._refresh_text(self.text)
max_size = max(self._lines_rects, key=lambda r: r.size[0]).size
num_lines = len(self._lines_rects)
px = [DEFAULT_PADDING, DEFAULT_PADDING]
py = [DEFAULT_PADDING, DEFAULT_PADDING]
if self.halign == 'center':
d = (self.width - max_size[0]) / 2.0 - DEFAULT_PADDING
px = [d, d]
elif self.halign == 'right':
px[0] = self.width - max_size[0] - DEFAULT_PADDING
if self.valign == 'middle':
d = (self.height - max_size[1] * num_lines) / 2.0 - DEFAULT_PADDING
py = [d, d]
elif self.valign == 'bottom':
py[0] = self.height - max_size[1] * num_lines - DEFAULT_PADDING
self.padding_x = px
self.padding_y = py
Note: This just aligns the position of the textblock, not the text itself.
import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from . import AlignedTextInput
class AlignedTextInputApp(App):
def build(self):
layout = GridLayout(cols=3)
layout.add_widget(self.get_input('top', 'left'))
layout.add_widget(self.get_input('top', 'center'))
layout.add_widget(self.get_input('top', 'right'))
layout.add_widget(self.get_input('middle', 'left'))
layout.add_widget(self.get_input('middle', 'center'))
layout.add_widget(self.get_input('middle', 'right'))
layout.add_widget(self.get_input('bottom', 'left'))
layout.add_widget(self.get_input('bottom', 'center'))
layout.add_widget(self.get_input('bottom', 'right'))
return layout
def get_input(self, v, h):
return AlignedTextInput(text='Example Text', halign=h, valign=v)
if __name__ == '__main__':
AlignedTextInputApp().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment