如何在Kivy ScrollView中自动向下滚动?

时间:2016-06-03 17:02:32

标签: python python-3.x kivy

我将小部件添加到GridLayout中的ScrollView,因此其内容会动态展开。
默认情况下,无需用户滚动,无论您添加多少小部件,视图都会保持在顶部。如果用户滚动,视图会附加到这一点,但对于我来说,向下滚动(甚至一点点)以使视图始终显示最新内容似乎有点烦人。如何默认显示最下面的部分?

以下是示例代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout

Builder.load_string('''
<MessageView>:
    canvas:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

<Message>:
    canvas:
        Color:
            rgba: 0, 1, 0, 0.3
        Rectangle:
            pos: self.pos
            size: self.size
''')

class Message(Widget):
    pass

class MessageView(ScrollView):
    pass

class TestApp(App):
    def msg_in(self, btn):
        msg = Message()
        msg.size_hint = [None, None]
        self.msg_layout.add_widget(msg)

    def build(self):
        self.scr = Screen()
        self.sv1_main = MessageView(pos_hint = {"top":0.87, "center_x":0.5},
                                    size_hint = (0.97, 0.65))
        self.msg_layout = GridLayout(cols = 1,
                                     size_hint_y = None)
        self.msg_layout.bind(minimum_height = self.msg_layout.setter('height'))
        self.bt1_main = Button(size_hint = (0.1, 0.078),
                               pos_hint = {"top":0.097, "center_x":0.927},
                               on_press = self.msg_in)
        self.scr.add_widget(self.sv1_main)
        self.sv1_main.add_widget(self.msg_layout)
        self.scr.add_widget(self.bt1_main)
        return self.scr

TestApp().run()

1 个答案:

答案 0 :(得分:3)

添加新内容后,您可以使用scroll_to方法。

class TestApp(App):
    def msg_in(self, btn):
        msg = Message()
        msg.size_hint = [None, None]
        self.msg_layout.add_widget(msg)
        self.sv1_main.scroll_to(msg)
    # ...