Kivy 布局之StackLayout,AnchorLayout

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

StackLayout

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

可以理解為 Box Layout 的增強(qiáng)版,在線性排序的基礎(chǔ)上增加了換行效果

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('應(yīng)用程序已關(guān)閉')

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

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

代碼運(yùn)行效果如下圖所示

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('應(yīng)用程序已關(guān)閉')

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

代碼解釋

創(chuàng)建 Anchor Layout 布局,向布局中添加一個按鈕

anchor_x 屬性其默認(rèn)值是 ‘center’,可選值有 ‘left’, ‘center’ or ‘right’
anchor_y 屬性其默認(rèn)值是 ‘center’,可選值有 ‘top’, ‘center’ or ‘bottom’
padding 屬性其默認(rèn)值是 [0, 0, 0, 0],分別對應(yīng)小部件 [左,上,右,下] 與容器的間距

搞不明白這種布局有什么應(yīng)用場景,有知道的可以評論區(qū)告訴我。

以上代碼運(yùn)行效果

anchorlayout01.JPG

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容