在Kivy的GridLayout中设置网格列宽度?

时间:2017-01-14 00:03:25

标签: python kivy grid-layout

我目前正在创建一个非常简单的GUI应用程序,左侧需要一些按钮(在一个狭窄的窗格中),右侧需要一个matplotlib图表(较宽的一个)。我没有Python GUI的经验,但我决定和Kivy一起去尝试这样的事情:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MyApp(App):

    def build(self):
        layout = GridLayout(cols=2)
        inLayout = GridLayout(rows=3)

        inLayout.add_widget(Button(text='Function 1', width = 50))
        inLayout.add_widget(Button(text='Function 2', width = 50))
        inLayout.add_widget(Button(text='Function 3', width = 50))

        layout.add_widget(inLayout)
        layout.add_widget(Button(text='Chart pane'))

        return layout


if __name__ == '__main__':
    MyApp().run()

由于按钮是左窗格中唯一需要的东西,我认为可能调整所有这些按钮会缩小整个窗格,但它并没有。有没有办法做到这一点或者GridLayout中的单元格总是必须是相同的大小,无论如何?如果是这样,Kivy中是否有类似的布局允许这样的改动?

1 个答案:

答案 0 :(得分:1)

您应该设置size_hintGridLayout个孩子的属性。在这种情况下,您需要更改inLayout对象,layout实例的第一个子对象。要使按钮始终调整为0.2宽度的可用空间,请将其设置为(0.2, 1)

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MyApp(App):

    def build(self):
        layout = GridLayout(cols=2)
        inLayout = GridLayout(rows=3, size_hint=(0.2, 1))

        inLayout.add_widget(Button(text='Function 1'))
        inLayout.add_widget(Button(text='Function 2'))
        inLayout.add_widget(Button(text='Function 3'))

        layout.add_widget(inLayout)
        layout.add_widget(Button(text='Chart pane'))

        return layout


if __name__ == '__main__':
    MyApp().run()

要将固定大小的宽度设置为size_hint(None, 1)并设置“width”属性:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MyApp(App):

    def build(self):
        layout = GridLayout(cols=2)
        inLayout = GridLayout(rows=3, width=100, size_hint=(None, 1))

        inLayout.add_widget(Button(text='Function 1'))
        inLayout.add_widget(Button(text='Function 2'))
        inLayout.add_widget(Button(text='Function 3'))

        layout.add_widget(inLayout)
        layout.add_widget(Button(text='Chart pane'))

        return layout


if __name__ == '__main__':
    MyApp().run()