python - Kivy/Python 中的 super 属性错误
问题描述
这是导致问题的 .py 端的代码摘录:
class ScreenMath(Screen):
def __init__(self,**kwargs):
super(ScreenMath,self).__init__(**kwargs)
self.ids.anchmath.ids.grdmath.ids.score.text = str("Score:" + "3")
而 .kv 方面:
<ScreenMath>:
AnchorLayout:
id: "anchmath"
...
GridLayout:
id: "grdmath"
...
Button:
id: "score"
当我运行代码时,发生 AttributeError :
File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
如您所见,我想在屏幕启动时更改值的文本(3 稍后将成为变量),但也许有更好的方法来做到这一点。
解决方案
问题 - AttributeError
File "kivy\properties.pyx", line 841, in kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
根本原因
Kivy 无法找到该属性,因为id
您的 kv 文件中的 s 被分配了字符串值。
解决方案
要解决此问题,需要进行以下更改。
id
kv 文件中的 s 不是字符串。因此,从id
.- 替换
self.ids.anchmath.ids.grdmath.ids.score.text
为self.ids.score.text
。
警告
为 id 赋值时,请记住该值不是字符串。没有引号:好 -> id: value, bad -> id: 'value'
当你的 kv 文件被解析时,kivy 会收集所有带有 id 标记的小部件,并将它们放在这个 self.ids 字典类型属性中。这意味着您还可以遍历这些小部件并访问它们的字典样式:
for key, val in self.ids.items(): print("key={0}, val={1}".format(key, val))
片段 - Python 代码
class ScreenMath(Screen):
def __init__(self,**kwargs):
super(ScreenMath,self).__init__(**kwargs)
self.ids.score.text = str("Score:" + "3")
片段-kv 文件
<ScreenMath>:
AnchorLayout:
id: anchmath
...
GridLayout:
id: grdmath
...
Button:
id: score
输出
推荐阅读
- reactjs - 错误:尝试重新打开第二个 BrowserWindow - Electron.js 时对象已被破坏
- react-native - React Native Navigation:在 passProps 中将组件传递到屏幕
- excel - 我的 Excel 文件不会加载所有行,因为它太大了
- vue.js - 未应用 Vuetify v-data-table 自定义标头类样式
- pandas - 不能在索引上合并。尝试使用连接,合并,
- java - 为什么代码在 ASCII 二进制中循环超过 122
- excel - Office 365 中的 VBA 日期
- java - java.util.Date 正在使用 1912 年之前的日期解析错误的日期
- c++ - valgrind 和堆的问题
- r - 在 R 中正确投影栅格并检索其数据