Kivy - 相對佈局



相對佈局的行為與浮動佈局非常相似。兩者主要區別在於,相對佈局中子元件的位置座標是相對於佈局大小的,而不是像浮動佈局那樣相對於視窗大小。

為了理解這意味著什麼,請考慮以下使用 FloatLayout 設計的 UI。

Kivy Relative Layout

當您調整視窗大小時,由於浮動佈局中的絕對定位,元件的位置與調整後的視窗不成比例。結果,介面設計不一致。

Kivy Resize Window

相對佈局沒有這種效果,因為元件的大小和位置是相對於佈局的。

當將位置為 (0,0) 的元件新增到 RelativeLayout 時,如果 RelativeLayout 的位置發生變化,子元件也會移動。子元件的座標始終相對於父佈局。

RelativeLayout 類定義在 "kivy.uix.relativelayout" 模組中。

from kivy.uix.relativelayout import RelativeLayout
rlo = RelativeLayout(**kwargs)

示例

以下程式碼在 RelativeLayout 中組合標籤、文字框和提交按鈕。

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.relativelayout import RelativeLayout
from kivy.core.window import Window

Window.size = (720, 400)

class RelDemoApp(App):
   def build(self):
      rlo = RelativeLayout()
      
      l1 = Label(
         text="Name", size_hint=(.2, .1),
         pos_hint={'x': .2, 'y': .75}
      )
      rlo.add_widget(l1)
      t1 = TextInput(
         size_hint=(.4, .1), pos_hint={'x': .3, 'y': .65}
      )
      rlo.add_widget(t1)
      l2 = Label(
         text="Address", size_hint=(.2, .1),
         pos_hint={'x': .2, 'y': .55}
      )
      rlo.add_widget(l2)
      t2 = TextInput(
         multiline=True, size_hint=(.4, .1),
         pos_hint={'x': .3, 'y': .45}
      )
      rlo.add_widget(t2)
      l3 = Label(
         text="College", size_hint=(.2, .1),
         pos_hint={'x': .2, 'y': .35}
      )
      rlo.add_widget(l3)
      t3 = TextInput(
         size_hint=(.4, .1), pos=(400, 150),
         pos_hint={'x': .3, 'y': .25}
      )
      rlo.add_widget(t3)
      b1 = Button(
         text='Submit', size_hint=(.2, .1),
         pos_hint={'center_x': .5, 'center_y': .09}
      )
      rlo.add_widget(b1)
      return rlo
      
RelDemoApp().run()

輸出

執行以上程式碼後,應用程式視窗將顯示如下 UI:

Kivy Relative Layout UI

請注意,與 FloatLayout 不同,調整視窗大小不會改變元件的比例大小和位置。

Kivy College Form

"kv" 設計語言指令碼

用於生成上述 UI 的 "kv" 檔案(而不是 App 類中的 build() 方法)如下:

RelativeLayout:
   Label:
      text:"Name"
      size_hint:(.2, .1)
      pos_hint:{'x':.2, 'y':.75}

   TextInput:
      size_hint:(.4, .1)
      pos_hint:{'x':.3, 'y':.65}
   
   Label:
      text:"Address"
      size_hint:(.2, .1)
      pos_hint:{'x':.2, 'y':.55}
   
   TextInput:
      multiline:True
      size_hint:(.4, .1)
      pos_hint:{'x':.3, 'y':.45}
   
   Label:
      text:"College"
      size_hint:(.2, .1)
      pos_hint:{'x':.2, 'y':.35}
   
   TextInput:
      size_hint:(.4, .1)
      pos:(400, 150)
      pos_hint:{'x':.3, 'y':.25}
   
   Button:
      text:'Submit'
      size_hint : (.2, .1)
      pos_hint : {'center_x':.5, 'center_y':.09}
廣告