可以在.kv文件中用于声明吗?

时间:2018-08-10 15:16:10

标签: python kivy indentation

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 (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 个答案:

答案 0 :(得分:0)

  1. 添加导入语句#:import Label kivy.uix.label.Label
  2. 使用on_parent事件在kv文件中执行for循环

Valid expressions

  

在kv文件中有 两个地方可以接受python语句 :    在属性之后 ,该属性将表达式的结果(例如上面显示的按钮的文本)分配给属性    在on_property 之后,该属性在更新属性(例如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)))
'''))

输出

Img01