Python - Kivy 中的錨佈局
Kivy 是一個開源的 Python 庫,用於快速開發利用創新使用者介面(例如多點觸控應用程式)的應用程式。它用於開發 Android 應用程式和桌面應用程式。在本文中,我們將瞭解如何使用錨佈局定位。
使用 AnchorLayout 時,我們會將小元件放置在其中一個邊框上。類 kivy.uix.anchorlayout.AnchorLayout 實現錨佈局。anchor_x 引數和 anchor_y 引數都可以傳入值“left”、“right”和“center”。在下面的程式中,我們建立兩個按鈕,將它們附加到兩個錨點,並將它們儲存在 BoxLayout 中。
示例
from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button class AnchorLayoutApp(App): def build(self): # Anchor Layout1 anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom') button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0)) anchor1.add_widget(button1) # Anchor Layout2 anchor2 = AnchorLayout(anchor_x='right', anchor_y='top') # Add anchor layouts to a box layout button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0)) anchor2.add_widget(button2) # Create a box layout BL = BoxLayout() # Add both the anchor layouts to the box layout BL.add_widget(anchor1) BL.add_widget(anchor2) # Return the boxlayout widget return BL # Run the Kivy app if __name__ == '__main__': AnchorLayoutApp().run()
執行以上程式碼會得到以下結果 -
輸出
廣告