Python实现
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
class MyGridLayout(GridLayout):
def __init__(self, **kwargs):
super(MyGridLayout, self).__init__(**kwargs)
self.cols = 3 # 设定3列
# 添加按钮并指定位置
self.add_widget(Button(text='1', row=0, col=0))
self.add_widget(Button(text='2', row=0, col=1))
self.add_widget(Button(text='3', row=0, col=2))
self.add_widget(Button(text='4', row=1, col=0))
self.add_widget(Button(text='5', row=1, col=1))
self.add_widget(Button(text='6', row=1, col=2))
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()
KV实现
from kivy.app import App
from kivy.lang import Builder
Builder.load_string('''
<MyGridLayout>:
cols: 3 # 设定3列
Button:
text: '1'
row: 0
col: 0
Button:
text: '2'
row: 0
col: 1
Button:
text: '3'
row: 0
col: 2
Button:
text: '4'
row: 1
col: 0
Button:
text: '5'
row: 1
col: 1
Button:
text: '6'
row: 1
col: 2
''')
class MyGridLayout(GridLayout):
pass
class MyApp(App):
def build(self):
return MyGridLayout()
if __name__ == '__main__':
MyApp().run()