【问题标题】:Kivy - Accessing Elements of a ListProperty in .kv fileKivy - 在 .kv 文件中访问 ListProperty 的元素
【发布时间】:2018-10-09 13:56:12
【问题描述】:

我已经开始使用 Kivy 编程,这是 Python 中令人惊叹的开源 GUI 库。

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

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

更准确地说,我收到以下错误:

  • 生成器异常:解析器:在我评论的那一行(见下面的 .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

【问题讨论】:

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


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 感谢您的回答!事实上我现在明白了!由于我首先生成了一个小部件类 MyCustomLabel 的实例,然后我为它分配了自定义列表,它最初有一个空列表作为 custom_list 属性......所以我当然会收到这个错误:)!
    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2015-07-24
    • 2021-06-24
    相关资源
    最近更新 更多