Created
January 10, 2021 01:20
-
-
Save tshirtman/bd62828b98746dcecb1ed269b04459b9 to your computer and use it in GitHub Desktop.
kivy text input with automatic font size for biggest text that fits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
''' | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty good 🤩🤩 u saved my life ❤️