Kivy盒子布局中自定义组件位置的方法,可以通过在盒子布局中添加pos_hint属性来指定组件在盒子布局中的位置

发布时间 2023-04-27 13:44:21作者: linux星

Python实现

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class MyBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super(MyBoxLayout, self).__init__(**kwargs)
        # 添加按钮并指定位置
        self.add_widget(Button(text='1', pos_hint={'x': 0, 'y': 0.5}))
        self.add_widget(Button(text='2', pos_hint={'x': 0.5, 'y': 0.5}))
        self.add_widget(Button(text='3', pos_hint={'x': 1, 'y': 0.5}))
class MyApp(App):
    def build(self):
        return MyBoxLayout()
if __name__ == '__main__':
    MyApp().run()

KV实现

from kivy.app import App
from kivy.lang import Builder
Builder.load_string('''
<MyBoxLayout>:
    Button:
        text: '1'
        pos_hint: {'x': 0, 'y': 0.5}
    Button:
        text: '2'
        pos_hint: {'x': 0.5, 'y': 0.5}
    Button:
        text: '3'
        pos_hint: {'x': 1, 'y': 0.5}
''')
class MyBoxLayout(BoxLayout):
    pass
class MyApp(App):
    def build(self):
        return MyBoxLayout()
if __name__ == '__main__':
    MyApp().run()