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}
广告
© . All rights reserved.