Kivy应用中的JSON数据无法滚动

-1 投票
1 回答
20 浏览
提问于 2025-04-14 15:36

我有一个Kivy应用程序,其中有一个页面需要加载一些json数据,这些数据似乎比屏幕大,所以我无法让它从顶部开始并且可以滚动。

我希望这个页面加载的数据能够从顶部开始,并且可以滚动,同时底部有一个返回按钮。

我也尝试过添加ScrollView,但效果似乎不太好。

我的KV文件是:

<ContentScreen>:
    BoxLayout:
        orientation: 'vertical'
        padding: 10
        spacing: 10

        ScrollView:
            do_scroll_x: False
            do_scroll_y: True
        Label:
            id: content_label
            pos_hint: {"center_x": 0.5, "center_y": 0.5}
            font_size: '16'
            text_size: self.width, None
        Button:
            text: 'Back'
            size_hint:(None, None)
            size:(86, 34)
            background_color: (1.0, 0.0, 0.0, 1.0)
            font_size:'16'
            on_release:
                app.root.current = 'main_screen'
                app.refresh_button_text(self)
                app.clear_input()
            pos_hint: {"center_x": 0.5, "center_y": 0.5}

我用来获取数据和切换到内容页面的函数如下:

def load_content(self, query):
    req_body = json.dumps({'content': query})
    headers = {
        'Content-Type': 'application/json'
    }
    req = UrlRequest('http://127.0.0.1:5000/recipes/ask_mobile', self.got_json, req_body=req_body,
                        req_headers=headers)

def content_screen(self, result):
    self.root.current = 'content_screen'
    content_screen = self.root.get_screen('content_screen')
    content_screen.ids.content_label.text = result
    print(result)

def got_json(self, req, result):
    for key, value in req.resp_headers.items():
        print('{}: {}'.format(key, value))
    recipe = result['data']
    print(recipe)
    self.content_screen(recipe)

这就是我目前的情况。

在这里输入图片描述

所以我们加载内容,这会触发gotJson函数,然后切换到内容页面,把响应结果放到标签的文本中。我希望这一切都能让你明白。

1 个回答

0

包含内容的标签必须放在滚动视图(ScrollView)下面。滚动的项目大小必须是固定的(不能是提示大小)。下面是一个简单的例子:

from kivy.app import App
from kivy.lang import Builder

kv = """
BoxLayout:
    orientation: 'vertical'
    Label:
        text: 'Label in a ScrollView'
        size_hint_y: None
        height: dp(30)
    ScrollView:
        Label:                # the widget to scroll is UNDER the scrollview
            id: content
            text_size: self.width, None
            size_hint_y: None               # the size must be fixed - not hinted to scroll
            height: self.texture_size[1]

"""

class ScrollingLabelApp(App):
    def build(self):
        return Builder.load_string(kv)

    def on_start(self):
        self.root.ids.content.text = 'Some long, long, amount of text to demo scrolling. ' * 200

ScrollingLabelApp().run()

撰写回答