Kivy:为什么 BoxLayout 将我的按钮推到底部?

use*_*489 2 python kivy kivy-language

我是 Kivy 的新手,但正在努力掌握它的窍门。我正在以“在 Kivy 中创建应用程序”中的示例作为模板,但我什至在第一章中遇到了困难。由于某种原因,我的按钮被推到了应用程序的底部。我是否错过了他们出现在下面的一些关键内容?

我的Python文件:

import kivy

from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.boxlayout import BoxLayout

# In the kv file, everything to the right of the colon is pure python
# for loading python module in kv file, use format of #:  import keyword module_name
class WeatherWidget(BoxLayout):
    def printing_test(self):
        print('This is a test')

class DailyViewApp(App):
    def build(self):
        return WeatherWidget()

if __name__ == '__main__':
    DailyViewApp().run()
Run Code Online (Sandbox Code Playgroud)

我的 kv 文件:

<WeatherWidget>:
    orientation: "vertical"
    BoxLayout: 
        height: "30dp"
        size_hint_y: None
        Button: 
            text: 'New York, NY' 
            size_hint_x: 1
            on_press: root.printing_test()
        Button: 
            text: 'Test'
            size_hint_x: 0.25
Run Code Online (Sandbox Code Playgroud)

我的(不正确的)输出:

iko*_*lim 5

在 BoxLayout 和垂直方向中,第一个小部件放置在窗口的底部,当下面添加更多小部件时向上滚动。如果您希望它出现在窗口顶部,则必须使用pos,或添加另一个 boxlayout (size_hint_y = 0.9) 来填充剩余空间,或添加小部件直到填满剩余空间。对于pos,您必须计算高度,如示例 1 所示。

pos: 0, root.height - 30
Run Code Online (Sandbox Code Playgroud)

如果您打算在按钮下方/外部框布局中放置更多小部件,我建议使用 GridLayout 作为根小部件,如示例 2 所示。

示例 1 - 嵌套 BoxLayout

dailyview.kv

#:kivy 1.10.0

<WeatherWidget>:
    orientation: "vertical"
    pos: 0, root.height - 30
    BoxLayout:
        height: "30dp"
        size_hint_y: None
        Button:
            text: 'New York, NY'
            size_hint_x: 1
            on_press: root.printing_test()
        Button:
            text: 'Test'
            size_hint_x: 0.25
Run Code Online (Sandbox Code Playgroud)

输出 1 - 嵌套 BoxLayout

在此输入图像描述

示例 2 - 网格布局

主要.py

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

# In the kv file, everything to the right of the colon is pure python
# for loading python module in kv file, use format of #:  import keyword module_name


class WeatherWidget(GridLayout):
    def printing_test(self):
        print('This is a test')


class DailyViewApp(App):
    def build(self):
        return WeatherWidget()


if __name__ == '__main__':
    DailyViewApp().run()
Run Code Online (Sandbox Code Playgroud)

dailyview.kv

#:kivy 1.10.0

<WeatherWidget>:
    cols: 1
    BoxLayout:
        height: "30dp"
        size_hint_y: None
        Button:
            text: 'New York, NY'
            size_hint_x: 1
            on_press: root.printing_test()
        Button:
            text: 'Test'
            size_hint_x: 0.25
Run Code Online (Sandbox Code Playgroud)

输出 2 - 网格布局

在此输入图像描述