简体   繁体   中英

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

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?

带有包含两个标签的 StackLayout 的 Kivy 应用程序仅显示第一个标签,居中于应用程序的中间。第二个标签无处可见

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 ?

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()

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