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

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

我已经开始使用 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:

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

中号

最佳答案

导致问题的原因是转换列表不完整,因为首先在更改列表之前它是空的,导致某些索引不存在,因此一个选项是验证它不是列表或至少具有一定大小,例如有以下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)

关于python-3.x - Kivy - 访问 .kv 文件中 ListProperty 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722844/

相关文章:

python - Gtk-ERROR ** : GTK+ 2. x 检测到符号。不支持在同一进程中使用 GTK+ 2.x 和 GTK+ 3(Kivy 应用程序)

python - Kivy:访问列表对象时出现AttributeError: 'NoneType'对象没有属性 'bind'

python - KivyMD 小部件显示在 MDBoxLayout 中的页面底部

python - Kivy 语言可以访问继承的布局和小部件吗?

python - Google Colab csv 文件上传速度慢得可怜

python - PyInstaller 与 Pymongo 的问题

python - 如何检查用户输入的字符列表中是否有相同的字符?

android - Android 上的 Kivy 和 OSC

python - 在 kvlang 中访问 Kivy 布局大小

Python 将一列的字符串匹配到另一列的子字符串