Home > other >  How to resize a widget so it size is fit to its text in kivy
How to resize a widget so it size is fit to its text in kivy

Time:12-26

When I add a widget, namely Label, sometimes its size cannot fit it's text height. Changing its height manually doesn't helped because i can type a text so its height will exceed the label's height. Here is the example of the code .py file

#testing.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
import random
import GlobalVariable
from GlobalVariable import *
import time

class ScreenOne(Screen):
    pass

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("testing.kv")

class testing(App):
    def build(self):
        return kv

if __name__ == "__main__":
    testing().run()

.kv file

#testing.kv
WindowManager:
    ScreenOne:

<ScreenOne>:
    ScrollView:
        size: self.size
        GridLayout:
            size_hint_y: None
            size: root.height, root.width
            cols: 2
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            

When you run the code, you will see that there is text that exceed it's label height. I expect to make those label always fit the text (not shorter but also not longer than its text) whatever the text is, and is scrollable. Any help or suggestion is appreciated. Thanks.

CodePudding user response:

Use these properties for your Label

Label:
    text_size: self.width, None
    size_hint: 1, None
    height: self.texture_size[1]
  • Related