You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy中如何让嵌套的垂直BoxLayout保持顶部对齐?

Kivy布局问题:垂直BoxLayout置顶失效与高度计算异常

我用Kivy开发带屏幕导航菜单的应用,菜单是包含按钮的垂直BoxLayout,用来切换屏幕,这个菜单嵌套在水平BoxLayout里,布局内还包含ScreenManager。我尝试通过pos_hint: {"top":1}让这个垂直BoxLayout置顶,但未达到预期效果。此外,打印interface.ids["menu"].height得到100,interface.ids["menu"].minimum_height得到0,这与菜单内控件总高度400不符。

Python代码

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen

class Menu(BoxLayout):
    pass

class ArtistTab(Screen):
    pass

class SongTab(Screen):
    pass

class AlbumTab(Screen):
    pass

class MuDoApp(App):
    def build(self):
        interface = Builder.load_file('main.kv')
        sm = ScreenManager()
        sng_tab = SongTab(name="song")
        art_tab = ArtistTab(name="artist")
        alb_tab = AlbumTab(name="album")
        sm.add_widget(art_tab)
        sm.add_widget(alb_tab)
        sm.add_widget(sng_tab)
        interface.add_widget(sm)
        print(interface.ids["menu"].height)
        print(interface.ids["menu"].minimum_height)
        return interface
    
if __name__ == '__main__':
    app = MuDoApp()
    app.run()

KV文件内容

BoxLayout:
    Menu:
        orientation: "vertical"
        pos_hint: {"y":1}
        id: menu
        
        Label:
            size_hint: (None,None)
            size: 500,100
            text: "Download by ..."
        Button:
            size_hint: (None,None)
            size: 300,100
            text: "songtitel"
        Button:
            size_hint: (None,None)
            size: 300,100
            text: "artist"
        Button
            size_hint: (None,None)
            size: 300,100
            text: "album"
        
        
<ArtistTab>:
    BoxLayout:
        id: artist_tab
        TextInput:
            size_hint: (None,None)
            width: 500
        Button:
            size_hint: (None,None)
            width: 300
            text: "download"

不同pos_hint参数测试结果

  • pos_hint: {"top":1}:菜单部分被挤出屏幕顶部
  • pos_hint: {"top":0}:菜单贴在屏幕底部
  • pos_hint: {"top":.7}:菜单位置在屏幕中部偏上
  • pos_hint: {"y":1}:菜单完全在屏幕顶部外,不可见
  • pos_hint: {"y":0}:菜单贴在屏幕底部
  • pos_hint: {"y":.7}:菜单位置在屏幕中部偏上

疑问

是我对pos_hint的理解有误,还是该属性在BoxLayout嵌套场景下无法生效?

内容的提问来源于stack exchange,提问作者Becks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:47:51