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