我正在尝试通过on_press行为按下此简单脚本来更改按钮的颜色。
Python脚本:kivytest.py
#Import Libraries
#Import Kivy GUI
import kivy
#From kivy, import base class App
# app: always refers to instance of this application
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
################################################################################
# Creating the root widget used in the .kv file
class testLayout(StackLayout):
pass
################################################################################
class kivytestApp(App):
def build(self):
return testLayout()
test = kivytestApp()
test.run()
对应的.kv文件:kivytest.kv
<StackLayout>:
#Create the canvas
canvas:
#Color the canvas background a dark gray with alpha = 1
Color:
rgba: 0.11, 0.15, 0.17, 1
Rectangle:
pos: self.pos
size: self.size
#Provide the orientation of the stack layout from left to right / top to bottom
orientation: "lr-tb"
#Add padding between children and layout
padding: 10
#Add spacing between each of its children
spacing: 5
Button:
size_hint: 0.2, None
text: "second button"
background_color: [1, 0, 0, 1]
background_normal: ''
on_press:
background_color: [0, 1, 0, 1]
print("second button pressed")
不幸的是,当我按下应用程序中的按钮时,颜色仍然是红色,但是on_press上的红色略深一些,而不是我指定的绿色。我应该纠正什么?这种实现不是看起来那么简单吗?
答案 0 :(得分:1)
您有2个错误:
仅通过指示background_color即可创建除Button的background_color属性以外的变量。要引用具有范围的同一对象,必须使用self
。
您不应在事件内的分配中使用:
,而应使用=
(我认为这是一个错误,在这种情况下kivy不会引发错误)
考虑到上述情况,解决方案是:
on_press:
self.background_color = [0, 1, 0, 1]
print("second button pressed")