【问题标题】:How can I print a list of data each in its own label underneath each other如何在彼此下方各自的标签中打印数据列表
【发布时间】:2021-09-15 21:06:34
【问题描述】:

我想在我的应用程序上显示大量数据,但我无法找到以垂直方式打印数据的方法,每个列表元素都位于最后一个下方的标签中。将来我希望将标签替换为MDCard

此外,如果列表到达屏幕底部,我将如何向下滚动?

*.py

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen

class FirstWindow(Screen):
    def __init__(self, **kwargs):
        super(FirstWindow, self).__init__(**kwargs)

        list1 = ['1','2','3','4','5','6','7','8','9','10','11','12']

        for x in list1:
            self.add_widget(Label(text=x,pos_hint={'center_x':0.5, 'center_y':0.5}))


class WindowManager(ScreenManager):
    pass

kv = Builder.load_file('NearMe.kv')

class NearMeApp(App):
    def build(self):
        return kv

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

*.kv

WindowManager:
    FirstWindow:

<FirstWindow>:
    name:"FirstWindow"
    GridLayout:
        cols:1
        size: root.width, root.height
        GridLayout:
            cols:3
            

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    您的FirstWindow__init__() 方法是将所有Labels 添加到FirstWindow,但它们都在同一位置。我怀疑您实际上想将Labels 添加到最里面的GridLayout。为此,您可以在kv 中将id 添加到GridLayout

    WindowManager:
        FirstWindow:
    
    <FirstWindow>:
        name:"FirstWindow"
        GridLayout:
            cols:1
            size: root.width, root.height
            GridLayout:
                id: grid  # Added id
                cols:3
    

    然后重构您的 FirstWindow 类以使用该 id

    class FirstWindow(Screen):
        def __init__(self, **kwargs):
            super(FirstWindow, self).__init__(**kwargs)
            Clock.schedule_once(self.fill)  # this must be delayed until the `id` is available
    
        def fill(self, dt):
            grid = self.ids.grid  # get a reference to the GridLayout
    
            list1 = ['1','2','3','4','5','6','7','8','9','10','11','12']
    
            for x in list1:
                grid.add_widget(Label(text=x,pos_hint={'center_x':0.5, 'center_y':0.5}))  # add Labels to the GridLayout
    

    【讨论】:

    • 感谢您的输入,您能解释一下时钟部分吗?
    • Clock.schedule_once() 用于延迟对fill() 的调用,因为类中的ids__init__() 方法中尚不可用。
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多