Side-by-side Labels in StackLayout: Why is second label missing? (kivy, python)

67 Views Asked by At

How can I display two labels side-by-side in a Kivy StackLayout?

Consider the following code

#!/usr/bin/env python3

from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.app import App

KV = """
StackLayout:
    orientation: 'lr-tb'

    Label:
        text: "Hello"

    Label:
        text: "World"
"""

class MyApp(App):
    def build(self):
        return Builder.load_string( KV )

MyApp().run()

I'm trying to make two text labels appears side-by-side. Originally I was using a BoxLayout and GridLayout, but I found that those would make the width of each widget coorespond to the width of the app. Whereas I want:

  1. The first label to be only as-wide as it needs to be for the text it contains
  2. The second label to be placed immediately next to first label, where the only gap between the text is the layout's spacing.

Unfortunately, the above code doesn't even display a second label -- it's just totally not there. Why?

Kivy app with StackLayout containing two Labels only shows the first label, centered in the middle of the app. The second label is nowhere to be seen

How can I display two labels right next to each-other, without kivy adding additional spacing or mysteriously not displaying my second label at all when using the StackLayout?

1

There are 1 best solutions below

0
Michael Altfield On

To make this work as expected, you have to:

  1. override size_hint to None and
  2. set the size of the widget to its texture_size (which is the actual pixels needed to render the font -- but you may actually want to pad this with some pixels)

For example

#!/usr/bin/env python3

from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.app import App

KV = """
StackLayout:
    orientation: 'lr-tb'

    Label:
        text: "Hello"
        size: self.texture_size
        size_hint: None, None

    Label:
        text: "World"
        size: self.texture_size
        size_hint: None, None
"""

class MyApp(App):
    def build(self):
        return Builder.load_string( KV )

MyApp().run()