我希望我的按钮在按下时从蓝色变为绿色。如果再次按下它,我希望它从绿色变回蓝色。我知道如何在按下按钮时更改按钮的颜色,但如果再次按下按钮,我不知道如何将该颜色更改回原始颜色。
kv文件:
<Type>:
name: "type"
RoundedButton:
size_hint: 0.417, 0.15625
pos_hint: {"x": 0.0556, "y": 0.15}
on_press: root.change_color()
Image:
source: 'Job.PNG'
size: self.parent.width, .85 * self.parent.height
pos: self.parent.x, self.parent.y + 5
stretch: True
keep_ratio: False
<RoundedButton@Button>:
background_normal: ""
background_color: 0, 0, 0, 0
back_color: 0.2,0.6,1,1
border_radius: 10
color: self.back_color
bold: True
canvas.before:
Color:
rgba: self.back_color
Line:
rounded_rectangle: self.x, self.y, self.width, self.height, self.border_radius
width:
蟒蛇文件:
class Type(Screen):
back_color = ObjectProperty()
def change_color(self):
if self.back_color == (0.2,0.6,1,1):
self.back_color = (0, 1, 0, 1)
else:
self.back_color = (0.2,0.6,1,1)
我认为我在 py 文件中的逻辑会检查颜色是否为蓝色 (0.2,0.6,1,1),即没有按下,它会变成绿色,如果它不是蓝色(所以必须是绿色,它会变成蓝色。但是当我按下按钮时没有任何反应,没有错误,只是没有变成绿色。
几个问题。
首先,你的change_color()
方法试图改变back_color
你的Type
实例,但你的RoundedButton
规则引用back_color
您的RoundedButton
实例(而不是一个在Type
)。因此,该方法所做的任何更改都不会影响RoundedButton
.
二、if
声明:
if self.back_color == (0.2,0.6,1,1):
永远不会是真的。部分是因为第一个问题,但也需要进行比较:
if self.back_color == [0.2,0.6,1,1]:
我不确定为什么会这样。
我认为解决第一个问题的最简单方法是id
在RoundedButton
:
<Type>:
name: "type"
RoundedButton:
id: butt
size_hint: 0.417, 0.15625
pos_hint: {"x": 0.0556, "y": 0.15}
on_press: root.change_color()
然后修改change_color()
方法为:
class Type(Screen):
def change_color(self):
if self.ids.butt.back_color == [0.2,0.6,1,1]:
self.ids.butt.back_color = (0, 1, 0, 1)
else:
self.ids.butt.back_color = (0.2,0.6,1,1)
请注意,back_color
ObjectProperty
不需要。
如果您希望RoundedButtons
独立更改颜色,您可以将您定义RoundedButton
为:
class RoundedButton(Button):
back_color = ListProperty()
def change_color(self):
if self.back_color == [0.2,0.6,1,1]:
self.back_color = [0, 1, 0, 1]
else:
self.back_color = [0.2,0.6,1,1]
在你的kv
文件中:
<Type>:
name: "type"
RoundedButton:
size_hint: 0.417, 0.15625
pos_hint: {"x": 0.0556, "y": 0.15}
Image:
source: 'Job.PNG'
size: self.parent.width, .85 * self.parent.height
pos: self.parent.x, self.parent.y + 5
stretch: True
keep_ratio: False
RoundedButton:
size_hint: 0.417, 0.15625
pos_hint: {"right": 1, "top": 1}
Image:
source: 'Job.PNG'
size: self.parent.width, .85 * self.parent.height
pos: self.parent.x, self.parent.y + 5
stretch: True
keep_ratio: False
<RoundedButton>:
background_normal: ""
background_color: 0, 0, 0, 0
back_color: 0.2,0.6,1,1
border_radius: 10
color: self.back_color
bold: True
on_press: self.change_color()
canvas.before:
Color:
rgba: self.back_color
Line:
rounded_rectangle: self.x, self.y, self.width, self.height, self.border_radius
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句