[英]Kivy returning AttributeError: object has no attribute 'name' when it clearly has it
I'm trying to build an interactive school timetable using Kivy but I keep running into problems with changing the Button text based on its name.我正在尝试使用 Kivy 构建一个交互式学校时间表,但我一直遇到根据其名称更改 Button 文本的问题。 I have created a grid layout where each button has a unique name, for example the first Button in Monday is
one_mon
the next one is two_mon
and so on.我创建了一个网格布局,其中每个按钮都有一个唯一的名称,例如,星期一的第一个按钮是
one_mon
,下一个是two_mon
,依此类推。 I have created a class which inherits from Button
and here is the Kivy and Python code for this class:我创建了一个继承自
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()
Here is the Python code for Tile这是 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]
Using print(self.name)
under on_press
function of Tile
class works fine and returns the name of the button but using if self.name == "one_mon"
raises an AttributeError 'Tile' object has no attribute 'name'
在
Tile
类的on_press
函数下使用print(self.name)
工作正常并返回按钮的名称,但使用if self.name == "one_mon"
引发AttributeError 'Tile' object has no attribute 'name'
Here is the code for the parent widget holding all those buttons together:这是将所有这些按钮放在一起的父小部件的代码:
<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"
How can I assign a different text to a button based on its id or its name?如何根据按钮的 id 或名称为按钮分配不同的文本? I can't just assign the text to each button individualy becouse in the future I want to be able to switch beetwen diffrent students whose timetable might look diffrent.
我不能只是将文本单独分配给每个按钮,因为将来我希望能够切换时间表可能看起来不同的不同学生。
When you do self.name
, it would search for a variable name
within the class
(which is not declared)当您执行
self.name
,它会在class
搜索变量name
(未声明)
In order to access the id from the kv code, you need to do the following为了从 kv 代码中访问 id,您需要执行以下操作
if self.ids.one_mon.name == "one_mon"
hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.