python - Kivy 返回 AttributeError: object has no attribute 'name' when it clear has it
问题描述
我正在尝试使用 Kivy 构建交互式学校时间表,但在根据名称更改 Button 文本时一直遇到问题。我创建了一个网格布局,其中每个按钮都有一个唯一的名称,例如星期一的第一个按钮是one_mon
下一个按钮two_mon
,依此类推。我创建了一个继承自的类,Button
这里是该类的 Kivy 和 Python 代码:
<Tile>:
background_color: [.5, .9, 1, 1]
halign: "center"
size_hint: None, None
size: 96, 96
text: self.lesson
on_press: self.on_press()
on_release: self.on_release()
这是 Tile 的 Python 代码
class Tile(Button):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.lesson = ""
self.sub_press = ""
self.check()
self.text = self.lesson
def check(self):
if self.name == "one_mon":
self.text = "English"
self.sub_press = "Room nr. 42 \n Mr. Hetman"
...
else:
self.lesson = "None"
self.sub_press = "None"
def on_release(self):
self.text = self.lesson
self.background_color = [.5, .9, 1, 1]
def on_press(self):
self.text = self.sub_press
self.background_color = [.01, .9, 1, 1]
使用类的print(self.name)
underon_press
函数Tile
可以正常工作并返回按钮的名称,但使用if self.name == "one_mon"
会引发AttributeError 'Tile' object has no attribute 'name'
以下是将所有这些按钮放在一起的父小部件的代码:
<PlanChart>:
cols: 11
padding: 2
Tile:
id: one_mon
name: "one_mon"
Tile:
id: two_mon
name: "two_mon"
Tile:
id: three_mon
name: "three_mon"
......
Tile:
id: ten_fri
name: "ten_fri"
如何根据按钮的 id 或名称为按钮分配不同的文本?我不能只将文本单独分配给每个按钮,因为将来我希望能够切换时间表可能看起来不同的不同学生。
解决方案
当你这样做时,它会在(未声明的)中self.name
搜索一个变量name
class
为了从 kv 代码中访问 id,您需要执行以下操作
if self.ids.one_mon.name == "one_mon"
希望能帮助到你
推荐阅读
- vuejs2 - Chartjs (Non Vue) 不在 V-if/V-show 内渲染图表
- xcode - 在 React Native 上安装 OneSignal - 链接器命令失败,退出代码为 1
- r - 在R中将数字转换为逻辑数据框
- android - 应用程序仅在单击时崩溃,致命异常错误
- angular - 使用 flatMap 或地图在 Angular 中嵌套 http get 请求
- javascript - Parsley 验证字段总和
- javascript - 尝试从不同的数组创建独立的模态和发布信息
- unity3d - unity透明精灵渲染顺序
- apollo-client - 带变量的 apollo watch 方法
- php - 在 wordpress 上单击 php 中的测验的提交按钮后,不会显示 POST 的结果