我可以在 .kv 文件中使用 for 语句吗?

can i use for statement in .kv file?

GridLayout:
    cols:
    rows: root.numberoflist

    for i in range(root.businfolist): 
        Label:
            font_name: 'C:/Windows/Fonts/HYWULM'
            text_size: cm(2), cm(2)
            pos: self.pos
            id: my_custom_label
            text: root.businfolist[0]
            color: [255,255,255,1]

.kv 文件

我想对 .kv 文件使用 FOR STATEMENT,我看到了

https://kivy.org/docs/api-kivy.lang.html?highlight=statement

这个页面,但是我看不懂。

我认为缩进似乎是错误的。 这些代码有什么问题?

traceback 在这里感谢您阅读我的问题。

 Traceback (most recent call last):
   File "C:/Users/mg/Desktop/Tubuc/TubucTest.py", line 58, in <module>
     class Bus_Information(Screen):
   File "C:/Users/mg/Desktop/Tubuc/TubucTest.py", line 60, in Bus_Information
     Builder.load_string(f.read())
   File "C:\Users\mg\Anaconda3\lib\site-packages\kivy\lang\builder.py", line 368, in load_string
     parser = Parser(content=string, filename=fn)
   File "C:\Users\mg\Anaconda3\lib\site-packages\kivy\lang\parser.py", line 392, in __init__
     self.parse(content)
   File "C:\Users\mg\Anaconda3\lib\site-packages\kivy\lang\parser.py", line 501, in parse
     objects, remaining_lines = self.parse_level(0, lines)
   File "C:\Users\mg\Anaconda3\lib\site-packages\kivy\lang\parser.py", line 605, in parse_level
     level + 1, lines[i:], spaces)
   File "C:\Users\mg\Anaconda3\lib\site-packages\kivy\lang\parser.py", line 615, in parse_level
     'Invalid property name')
 kivy.lang.parser.ParserException: Parser: File "<inline>", line 28:
 ...
      26:       rows: root.numberoflist
      27:       
 >>   28:       for i in range(root.businfolist): 
      29:           Label:
      30:               font_name: 'C:/Windows/Fonts/HYWULM'
 ...
 Invalid property name
  1. 添加导入语句,#:import Label kivy.uix.label.Label
  2. 使用on_parent事件在kv文件中执行for循环

Valid expressions

There are two places that accept python statements in a kv file: after a property, which assigns to the property the result of the expression (such as the text of a button as shown above) and after a on_property, which executes the statement when the property is updated (such as on_state).

main.py

from kivy.lang import Builder
from kivy.base import runTouchApp

runTouchApp(Builder.load_string('''
#:kivy 1.11.0
#:import Label kivy.uix.label.Label

GridLayout:
    cols: 3
    on_parent:
        for i in range(10): txt = "Label {0}".format(i); self.add_widget(Label(text = txt, text_size=(cm(2), cm(2)), pos=self.pos,
        id=txt, color=(1,1,1,1)))
'''))

输出