Search code examples
pythonkivykivy-language

How can i prevent my label from stretching when i resize the window in kivy?


In this program when i want to resize the window i do not want to my label to resize or stretch and i want it to have fixed width How can i do that? (I set the size_hint: (.1, None) but i do not know why it stretches with changing window size)

code:

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.relativelayout import RelativeLayout
 

Builder.load_string("""


<relative>
    RelativeLayout:
    
            
        size: root.width,root.height
        Label:
            pos_hint:{'x':0,'y':.01}
            size_hint: (.1, None)
            height: 22
            text:'1'
            background_color: 6/255, 61/255, 81/255, 1
            canvas.before:
                Color:
                    rgba:self.background_color
                Rectangle:
                    size: self.size
                    pos: self.pos

        TextInput:
        
            cursor_color: 255/255, 143/255, 5/255, 0.8 
            pos_hint:{'x':.1,'y':0}
            multiline:False
            height: 33
            size_hint: (5, None)
            background_color: 0,0,0,0
            foreground_color: 255/255, 167/255, 167/255, 0.51













""")

class relative(Widget):
    pass

class foo(App):

    def build(self):
        Window.clearcolor='#1618388'
        return relative()







if __name__ == '__main__':
    foo().run()

before changing the window size: enter image description here

after changing the window size: enter image description here


Solution

  • The Label changes size because size_hint: (.1, None) tells kivy that the Label width should be 0.1 times the RelativeLayout. If you want the size to be constant, do not use size_hint. Try this:

        Label:
            pos_hint:{'x':0,'y':.01}
            size_hint: (None, None)
            width: 100
            height: 22
            text:'1'
            background_color: 6/255, 61/255, 81/255, 1
            canvas.before:
                Color:
                    rgba:self.background_color
                Rectangle:
                    size: self.size
                    pos: self.pos