如何在Kivy Python中正确使用ScrollView?

时间:2020-04-02 16:14:29

标签: python scroll grid kivy grid-layout

我有此代码想要更改按钮的位置,但是如果我更改位置,则滚动将不再起作用。如何设法使其工作?以下是工作版本。如果我将size_hint:1,.1更改为size_hint:1,.7,则滚动不再起作用...

from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.floatlayout import FloatLayout

Builder.load_string('''
<Root>:
    ScrollView:
        size_hint: 1, .1
        GridLayout:
            size_hint_y: None
            cols: 1
            # minimum_height: self.height
            Button
                text: 'one'
            Button:
                text: 'two'
            Button:
                text: 'three'
            Button:
                text: 'four'
''')

class Root(FloatLayout):
    pass

class DemoApp(App):

    def build(self):
        return Root()

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


2 个答案:

答案 0 :(得分:0)

您做对了。 ScrollView允许您滚动查看GridLayout中不适合的ScrollView部分。将size_hint设置为(1, .7)时,所有内容都适合ScrollView,因此它不会滚动。

您可以通过添加Widgets来占据更多空间来强制滚动(例如Labels,没有文本):

<Root>:
    ScrollView:
        size_hint: 1, .7
        GridLayout:
            size_hint_y: None
            cols: 1
            height: self.minimum_height
            Label:
                text: ''
                size_hint_y: None
                height: 300
            Button
                text: 'one'
                size_hint: 1, None
                height: self.texture_size[1]
            Button:
                text: 'two'
                size_hint: 1, None
                height: self.texture_size[1]
            Button:
                text: 'three'
                size_hint: 1, None
                height: self.texture_size[1]
            Button:
                text: 'four'
                size_hint: 1, None
                height: self.texture_size[1]
            Label:
                text: ''
                size_hint_y: None
                height: 300

答案 1 :(得分:0)

父窗口小部件中一旦有size_hint_y = None,则必须手动声明子窗口小部件的高度,因为 size_hint_y 处理高度或Y轴。使事情变得更清晰的代码

from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.floatlayout import FloatLayout

Builder.load_string('''
<Root>:
    ScrollView:
        size_hint_y:None
        height:root.width / 2
        GridLayout:
            size_hint_y: None
            cols: 1
            height:self.minimum_height
            spacing:dp(20)
            Button
                text: 'one'
                size_hint_y:None
                height:dp(50)
            Button:
                text: 'two'
                size_hint_y:None
                height:dp(50)
            Button:
                text: 'three'
                size_hint_y:None
                height:dp(50)
            Button:
                text: 'four'
                size_hint_y:None
                height:dp(50)
''')

class Root(FloatLayout):
    pass

class DemoApp(App):

    def build(self):
        return Root()

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