【问题标题】:Creating Kivy widgets in a loop在循环中创建 Kivy 小部件
【发布时间】:2018-07-11 07:54:29
【问题描述】:

我有一个 kivy 屏幕,我需要通过循环在其中创建元素。我可以这样做:

class HomeScreen(Screen):

    def show_tasks(self):
        global user

        tasks = DB.get_tasks(user) # Returns an array of tuples
        for task in tasks:
            self.add_widget(Label(text=task[1]))

但是,当我这样做时,标签会相互重叠——实际上是在 z 轴上,使它们都无法读取。相反,我希望它们将一个填充在另一个之上(在 y 轴上)。不仅如此,最终我还想从数据中创建一个类似表格的结构。

这是我的kv:

<HomeScreen>:
    name: 'home'    
    FloatLayout:
        BoxLayout:
            orientation: "horizontal"
            pos_hint: {"x": 0, "y": 0}
            GridLayout:
                id: grid
                rows: 4
                cols: 1
                padding: 10
                spacing: 10
                row_force_default: True
                row_default_height: 40
                Label:
                    text: 'Your Tasks:'
                    size_hint_x: None
                    width: 200
                    font_size: 24

任何关于如何解决此问题的帮助或见解将不胜感激!

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    在以下代码中:

    self.add_widget(Label(text=task[1]))
    

    self 指的是HomeScreen 类的一个实例,因此您将一个子级添加到HomeScreen,而不是GridLayout,也就是说,它相当于:

    <HomeScreen>:
        name: 'home' 
        FloatLayout:
            ...
        Label:
            ...
        Label:
            ...
    

    解决方案是添加到GridLayout 来做网格类的一个属性:

    <HomeScreen>:
        name: 'home'
        grid: grid    # <---
        FloatLayout:
            BoxLayout:
                orientation: "horizontal"
                pos_hint: {"x": 0, "y": 0}
                GridLayout:
                    id: grid
                    # rows: 4
                    cols: 1
                    padding: 10
                    spacing: 10
                    row_force_default: True
                    row_default_height: 40
                    Label:
                        text: 'Your Tasks:'
                        size_hint_x: None
                        width: 200
                        font_size: 24
    

    然后我们在python部分使用grid添加它:

    class HomeScreen(Screen):
        def show_tasks(self):
            global user
            tasks = DB.get_tasks(user) # Returns an array of tuples
            for task in tasks:
                self.grid.add_widget(Label(text=task[1])) # <---
    

    【讨论】:

    • 这肯定回答了我原来的问题!
    • @user2283234 删除rows: 4
    • @user2283234 当您设置 rows = 4 和 cols = 1 时,您表示您将只有 rows * cols 小部件,在您的情况下只有 4 个,如果您不设置 rows 那么将假定它是未定义的。
    • 我刚刚看到您已将其注释掉,并对其进行了测试,它确实有效。我今天好像特别密集。非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多