在kivy畫布點(0,0)實際上是左下方之一。你可以計算頂部容易自己的位置:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import ListProperty
kv_string = '''
<MyWidget>:
r_size: [root.size[0]/2, root.size[1]/2]
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: root.r_size
pos: 0, root.size[1]-root.r_size[1]
'''
Builder.load_string(kv_string)
class MyWidget(Widget):
r_size = ListProperty([0, 0])
class TestApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
TestApp().run()
您還可以使用FloatLayout
,設置分辨率無關SubWidget的大小和位置使用pos_hint
和size_hint
屬性,那麼每個這樣的小部件的邊框內畫點什麼:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
kv_string = '''
<MyWidget>:
Widget:
pos_hint: {'center_y': 0.5, 'center_x': 0.5}
size_hint: 0.2, 0.2
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: self.size
pos: self.pos
Widget:
pos_hint: {'center_y': 0.5, 'center_x': 0.2}
size_hint: 0.2, 0.2
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: self.size
pos: self.pos
Widget:
pos_hint: {'center_y': 0.5, 'center_x': 0.8}
size_hint: 0.2, 0.2
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: self.size
pos: self.pos
Widget:
pos_hint: {'center_y': 0.2, 'center_x': 0.5}
size_hint: 0.2, 0.2
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: self.size
pos: self.pos
Widget:
pos_hint: {'center_y': 0.8, 'center_x': 0.5}
size_hint: 0.2, 0.2
canvas:
Color:
rgb: 0.1, 0.6, 0.3
Rectangle:
size: self.size
pos: self.pos
'''
Builder.load_string(kv_string)
class MyWidget(FloatLayout):
pass
class TestApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
TestApp().run()
感謝那 :) – whatsthatsay