简体   繁体   中英

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

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.

Use these properties for your Label

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM