Skip to content

Instantly share code, notes, and snippets.

@tshirtman
Created January 10, 2021 01:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tshirtman/bd62828b98746dcecb1ed269b04459b9 to your computer and use it in GitHub Desktop.
Save tshirtman/bd62828b98746dcecb1ed269b04459b9 to your computer and use it in GitHub Desktop.
kivy text input with automatic font size for biggest text that fits
'''
'''
from kivy.app import App
from kivy.lang import Builder
from kivy.core.text import Text
from kivy.clock import mainthread
KV = '''
TextInput:
on_text: app.update_font_size(self)
on_size: app.update_font_size(self)
'''
class Application(App):
def build(self):
return Builder.load_string(KV)
def update_font_size(self, widget):
text = widget.text
max_width = widget.width - (widget.border[1] + widget.border[3])
max_height = widget.height - (widget.border[0] + widget.border[2])
if not text:
return
instance = Text(text_size=(max_width, None), font_size=10, text=text)
width, height = instance.render()
while height < max_height:
instance.options['font_size'] *= 2
width, height = instance.render()
while height > max_height:
instance.options['font_size'] *= .95
width, height = instance.render()
widget.font_size = instance.options['font_size']
self.reset_scroll(widget)
@mainthread
def reset_scroll(self, widget):
widget.scroll_x = widget.scroll_y = 0
if __name__ == "__main__":
Application().run()
@Ghilas-source
Copy link

Pretty good 🤩🤩 u saved my life ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment