Kivy-.kv文件中ListProperty的访问元素

时间:2018-10-09 13:56:13

标签: python-3.x kivy kivy-language indexoutofrangeexception listproperty

我已经开始使用Kivy(一种很棒的Python开源GUI库)进行编程。

我遇到了一个问题close to this topic,但没有令人满意的答案。

我想访问附加到我的.kv文件中的窗口小部件的ListProperty的元素,但是出现错误。我猜这是由于对KV语法的误解而引起的,但我无法完全弄清楚发生了什么。

更确切地说,出现以下错误:

  • Builder异常:解析器:在我已注释的行上(请参见下面的.kv文件)
  • IndexError:列表索引超出范围

似乎建造者不了解我的 custom_list 确实包含3个从0到2的索引元素。

这是我编写的用于说明这种情况的简单示例:

example.py文件

# Kivy modules
import kivy
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.app import App
from kivy.properties import ListProperty



class MyCustomLabel(Label):
    custom_list = ListProperty()


class MainWidget(BoxLayout):

    def generate_list(self):
        l = ["Hello","Amazing","World"]
        my_custom_label = MyCustomLabel()
        my_custom_label.custom_list = l
        self.add_widget(my_custom_label)


class MyApp(App):
    pass

if __name__=="__main__":
    MyApp().run()

my.kv文件

<MainWidget>:
    orientation: "vertical"

    Button:

        # Aspect
        text: "CLICK ME"
        size_hint_y: None
        height: dp(60)

        # Event
        on_press: root.generate_list()


<MyCustomLabel>:

    ## This is working
    ## text: "{}".format(self.custom_list)

    ## But this is not working... Why ?
    text: "{}{}{}".format(self.custom_list[0], self.custom_list[1], self.custom_list[2])

MainWidget:

提前感谢那些会花时间回答的人,

M

1 个答案:

答案 0 :(得分:1)

之所以引起此问题,是因为过渡列表不完整,因为首先在更改列表之前它是空的,导致某些索引不存在,因此一种选择是验证它不是列表或至少具有一定的大小,例如,有以下两个选项:

text: "{}{}{}".format(self.custom_list[0], self.custom_list[1], self.custom_list[2]) if self.custom_list else ""

text: "{}{}{}".format(self.custom_list[0], self.custom_list[1], self.custom_list[2]) if len(self.custom_list) >= 3 else ""

或者使用一个更好的选择join

text: "".join(self.custom_list)