python - 在循环中创建 Kivy 小部件

标签 python kivy

我有一个 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

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

最佳答案

在下面的代码中:

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])) # <---

关于python - 在循环中创建 Kivy 小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275210/

相关文章:

python - get_dummies python内存错误

python - scipy csr_matrix : understand indptr

python - 为什么我的 Kivy Actionbar 不见了?

python - Selenium/ChromeDriver 未知政策错误

Python pandas 通过检查值是否更改然后之前的值进行分组

python - 会给出某些单词python的正则表达式

kivy:用颜色填充自定义形状

python - Kivy,如何在 Canvas 中使用数据

python - Kivy GridLayout 中的空 id 列表

python-3.x - Kivy:已弃用功能的替代方案