Kivy 布局之BoxLayout

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

BoxLayout:垂直或者水平方向布局

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

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class ExampleBoxLayout(BoxLayout):
    def __init__(self, **kwargs):
        super(ExampleBoxLayout, self).__init__(**kwargs)

        # 設(shè)置方向(垂直或水平)
        self.orientation= kwargs['orientation']
        # 設(shè)置間距
        self.spacing= kwargs['spacing']

        # 創(chuàng)建部件
        btn1 = Button(text='Hello', size_hint=(.6, 1))
        btn2 = Button(text='Kivy', size_hint=(.3, 0.5))
        btn3 = Button(text='World', size_hint=(.1, 0.8))

        # 添加部件
        self.add_widget(btn1)
        self.add_widget(btn2)
        self.add_widget(btn3)

class MyApp(App):
    def build(self):
        return ExampleBoxLayout(orientation = 'horizontal', spacing = 20) # orientation = vertical or horizontal

    def on_stop(self):
        print('應(yīng)用程序已關(guān)閉')

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

代碼解釋?zhuān)?/strong>

寫(xiě)了一個(gè) ExampleBoxLayout 類(lèi),該類(lèi)繼承了 BoxLayout 類(lèi)
通過(guò)參數(shù) orientation 設(shè)置了布局的方向(水平)
通過(guò)參數(shù) spacing 設(shè)置了部件之間的間距

size_hint 參數(shù):
這是一個(gè)表示控件大小相對(duì)性的參數(shù),它允許按照父控件的剩余空間來(lái)調(diào)整控件的大小
第一個(gè)元素表示寬度相對(duì)于父控件剩余空間的提示(可以在0(不占據(jù)任何空間)和1(占據(jù)所有剩余空間)之間)
第二個(gè)元素表示高度相對(duì)于父控件剩余空間的提示

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

BoxLayout01.JPG

將上面的代碼修改其中的4行代碼如下:

return ExampleBoxLayout(orientation = 'vertical', spacing = 20) # orientation = vertical or horizontal
# 創(chuàng)建部件
btn1 = Button(text='Hello', size=(200, 100), size_hint=(None, None))
btn2 = Button(text='Kivy', size_hint=(.8, 0.5))
btn3 = Button(text='World', size_hint=(.8, 1))

代碼解釋?zhuān)?/strong>

通過(guò)參數(shù) orientation 設(shè)置了布局的方向(垂直)

第一個(gè)按鈕,通過(guò)參數(shù) size 定義了寬高:200像素 * 100像素
第二個(gè)按鈕和第三個(gè)按鈕寬度相等,都是占窗口寬度的80%
第二個(gè)按鈕和第三個(gè)按鈕寬度的高度比例是 0.5 : 1

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

BoxLayout02.JPG

再次將創(chuàng)建三個(gè)按鈕部件的代碼修改如下:

# 創(chuàng)建部件
btn1 = Button(text='Hello', size=(200, 100), size_hint=(None, None), pos_hint={'right': 0.5})
btn2 = Button(text='Kivy', size=(100, 100), size_hint=(None, None), pos_hint={'x': 0.5})
btn3 = Button(text='World', size=(200, 200), size_hint=(None, None), pos_hint={'center_x': 0.5})

代碼解釋?zhuān)?/strong>

三個(gè)按鈕都通過(guò)參數(shù) size 定義可寬高

三個(gè)按鈕都通過(guò)參數(shù) pos_hint 定義了相對(duì)位置
第一個(gè)按鈕通過(guò) right 屬性設(shè)置了部件的右邊的位置(x方向的50%)
第二個(gè)按鈕通過(guò) x 屬性設(shè)置了部件左邊的位置(x方向的50%)
第三個(gè)按鈕通過(guò) center_x 屬性設(shè)置了部件中心點(diǎn)的位置(x方向的50%)

垂直方向布局可以使用:right, x, center_x
水平方向布局可以使用:top, y, center_y

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

BoxLayout03.JPG

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

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

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