自定义事件:TypeError: 'NoneType' 对象不可下标访问

6 投票
4 回答
10409 浏览
提问于 2025-04-18 06:45

我在使用Kivy 1.8.0,想用自定义事件来管理一个是/否的弹窗。这段代码是在网上找到的。我只找到这个例子,想把它修改成可以管理多个弹窗,但运行时出现了错误。

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty

Builder.load_string('''
<ConfirmPopup>:
    cols: 1
        Label:
            text: root.text
        GridLayout:
            cols: 2
            size_hint_y: None
            height: '44sp'
            Button:
                text: 'Yes'
                on_release: root.dispatch('on_reponse_user','yes')
            Button:
                text: 'No'
                on_release: root.dispatch('on_reponse_user', 'no')
''')

我不确定问题出在kv字符串上还是代码上。

class ConfirmPopup(GridLayout):
    text = StringProperty('')

    def __init__(self,**kwargs):
        self.register_event_type('on_reponse_user')
        super(ConfirmPopup,self).__init__(**kwargs)

    def on_reponse_user(self, instance, answer):
        pass    


class PopupTest(App):
    def build(self):
        content = ConfirmPopup(text='Do You Love Kivy?')
        content.bind(on_reponse_user=self.on_answer_callback)
        self.popup = Popup(title="Answer Question",
                           content=content,
                           size_hint=(None, None),
                           size=(480,400),
                           auto_dismiss= False)
        self.popup.open()

    def on_answer_callback(self, instance, answer):
        print("USER ANSWER: " , repr(answer))
        self.popup.dismiss()

if __name__ == '__main__':
    PopupTest().run()

当我运行这段代码时,出现了这个错误:

 Traceback (most recent call last):
   File "F:\Kivy-1.8.0\test_event.py", line 24, in <module>
     ''')
   File "F:\Kivy-1.8.0\kivy\kivy\lang.py", line 1491, in load_string
     parser = Parser(content=string, filename=fn)
   File "F:\Kivy-1.8.0\kivy\kivy\lang.py", line 1049, in __init__
     self.parse(content)
   File "F:\Kivy-1.8.0\kivy\kivy\lang.py", line 1122, in parse
     objects, remaining_lines = self.parse_level(0, lines)
   File "F:\Kivy-1.8.0\kivy\kivy\lang.py", line 1271, in parse_level
     if current_property[:3] == 'on_':
 TypeError: 'NoneType' object is not subscriptable

我不知道为什么自定义事件会出错。根据Kivy的文档,是可以添加自定义事件的。

4 个回答

0

在我的情况下,我通过查看我的kv文件发现了问题,发现一个按钮的功能那里少了一个制表符(Tab)。所以这个按钮没有和布局连接起来:

在这里输入图片描述

0

我在笔记本电脑上也遇到了同样的问题,但当我在安卓上试这个代码时,它运行得很好。你可以试试在安卓上用kivy启动器和Python来运行这个代码。

0

异常的名字说明 current_propertyNone,你应该检查一下周围的代码。顺便问一下,你的事件名字为什么是 'on_reponse_user'?难道不应该是 on_reSponse_user 吗?如果这个字符串在 Kivy 中除了名字还有其他重要的意义,那可能就是你问题的根源。

7

这个错误肯定是在kivy的解析器中出现的,这说明你要加载的字符串里有问题。看起来像是字符串中的缩进出了问题。

如果这个例子是从这里拿来的,那么里面的缩进层次可能有点奇怪,GitHub的代码格式化工具可能把这些问题隐藏了。如果你的缩进和那个页面上的一样,试着把你发的代码片段完全按照那里的格式复制一遍,看看这样能不能解决问题。

撰写回答