我在尝试学习 kivy 中的 BoxLayout 时遇到断言错误。我不知道出了什么问题。
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class BoxLayoutApp(App):
def build(self):
return BoxLayout()
if __name__=="__main__":
BoxLayoutApp().run()
Run Code Online (Sandbox Code Playgroud)
对于 kv 代码:
<BoxLayout>:
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
Run Code Online (Sandbox Code Playgroud)
编辑:我尝试按照建议对 BoxLayout 进行子类化,但是我仍然面临 AssertionError。我在此处复制了完整(原始)错误消息:
Traceback (most recent call last):
File "boxlayout.py", line 12, in <module>
BoxLayoutApp().run()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\app.py", line 802, in run
root = self.build()
File "boxlayout.py", line 8, in build
return BoxLayout()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\boxlayout.py", line 131, in
__init__
super(BoxLayout, self).__init__(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\layout.py", line 76, in __in
it__
super(Layout, self).__init__(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\widget.py", line 345, in __i
nit__
Builder.apply(self, ignored_consts=self._kwargs_applied_init)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a
pply
self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 566, in _
apply_rule
self.apply(child)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a
pply
self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 464, in _
apply_rule
assert(rule not in self.rulectx)
AssertionError
Run Code Online (Sandbox Code Playgroud)
尝试对 boxlayout 进行子类化:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
class MyBoxLayout(BoxLayout):
pass
Builder.load_string('''
<MyBoxLayout>:
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
''')
class BoxLayoutApp(App):
def build(self):
return MyBoxLayout()
if __name__=="__main__":
BoxLayoutApp().run()
Run Code Online (Sandbox Code Playgroud)
之所以AssertionError被抛出,是因为您尝试将规则应用于正在嵌套的同一个类。
换句话说,您对一个类应用了一条规则,该规则应包含其自身。
这会导致问题。
以下将引发相同的错误。
<MyBoxLayout>:
MyBoxLayout:
Run Code Online (Sandbox Code Playgroud)