美文网首页
Kivy 布局之StackLayout,AnchorLayout

Kivy 布局之StackLayout,AnchorLayout

作者: 我的小小笔尖 | 来源:发表于2023-10-21 10:52 被阅读0次

布局就是定义如何排列小部件

StackLayout

https://kivy.org/doc/stable/api-kivy.uix.stacklayout.html

可以理解为 Box Layout 的增强版,在线性排序的基础上增加了换行效果

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout

class ExampleStackLayout(StackLayout):
    def __init__(self, **kwargs):
        super(ExampleStackLayout, self).__init__(**kwargs)

        for i in range(25):
            btn = Button(text=str(i), width=40 + i * 5, size_hint=(None, 0.15 + i*0.01))
            self.add_widget(btn)

class MyApp(App):
    def build(self):
        return ExampleStackLayout(orientation = 'rl-tb') # orientation = one of: ['lr-tb', 'tb-lr', 'rl-tb', 'tb-rl', 'lr-bt', 'bt-lr', 'rl-bt', 'bt-rl']

    def on_stop(self):
        print('应用程序已关闭')

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

orientation 属性决定了排序方向,示例中 rl-tb 的意思是 从右到左-从上到下

代码运行效果如下图所示

stacklayout01.JPG

AnchorLayout

https://kivy.org/doc/stable/api-kivy.uix.anchorlayout.html

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.anchorlayout import AnchorLayout

class ExampleAnchorLayout(AnchorLayout):
    def __init__(self, **kwargs):
        super(ExampleAnchorLayout, self).__init__(**kwargs)

        btn = Button(text='Hello World', size=(200, 80), size_hint=(None, None))
        self.add_widget(btn)

class MyApp(App):
    def build(self):
        return ExampleAnchorLayout(anchor_x='center', anchor_y='top', padding=[0, 10, 0, 0])

    def on_stop(self):
        print('应用程序已关闭')

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

代码解释

创建 Anchor Layout 布局,向布局中添加一个按钮

anchor_x 属性其默认值是 ‘center’,可选值有 ‘left’, ‘center’ or ‘right’
anchor_y 属性其默认值是 ‘center’,可选值有 ‘top’, ‘center’ or ‘bottom’
padding 属性其默认值是 [0, 0, 0, 0],分别对应小部件 [左,上,右,下] 与容器的间距

搞不明白这种布局有什么应用场景,有知道的可以评论区告诉我。

以上代码运行效果

anchorlayout01.JPG

相关文章

网友评论

      本文标题:Kivy 布局之StackLayout,AnchorLayout

      本文链接:https://www.haomeiwen.com/subject/rszkidtx.html