我的应用只有一个默认背景颜色的按钮。我只是想在on_press
事件上将其背景颜色更改为另一种颜色。您可能会认为它类似于访问过的和未访问过的html超链接,即当点击链接时,它会改变颜色。
我的尝试:
#!/usr/bin/kivy
import kivy
kivy.require('1.7.2')
from random import random
from random import choice
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.properties import StringProperty
Builder.load_string("""
<Highest>:
GridLayout:
cols: 1
Button:
text: "Hi"
on_press: root.new()
""")
class Highest(Screen):
def new(self):
self.background_color=(1.0, 0.0, 0.0, 1.0)
# Create the screen manager
sm = ScreenManager()
sm.add_widget(Highest(name='Highest'))
class TestApp(App):
def build(self):
return sm
if __name__ == '__main__':
TestApp().run()
但on_press
没有任何反应@inclement
实际上,我试图最小化我的问题。
我真正需要的是根据变量
在不同的条件下给出不同的颜色class Highest(Screen):
def new(self):
if(a==5):
self.background_color=(1.0, 0.0, 0.0, 1.0)
else:
self.background_color=(1.0, 1.0, 1.0, 1.0)
所以我想要在我的班级最高级别。请指导。提前谢谢。
答案 0 :(得分:4)
但on_press
没有任何反应
实际上,您设置了最高实例的background_color属性 - 但是您没有看到任何事情发生,因为它没有使用background_color。
你可以改为:
on_press: self.background_color = (1.0, 0.0, 0.0, 1.0)
通过将其置于按钮规则中,self
指的是您实际想要更改的按钮实例。
答案 1 :(得分:0)
如果你想将它保留在一个函数中,你也可以在按钮中添加一个id,然后从最高实例中更改它。
Builder.load_string("""
<Highest>:
GridLayout:
cols: 1
Button:
id: button_one
text: "Hi"
on_press: root.new()
""")
然后你可以引用id来改变颜色......
class Highest(Screen):
def new(self):
self.ids['button_one'].background_color = 1.0, 0.0, 0.0, 1.0
答案 2 :(得分:0)
I just want to change its background color to another color on on_press event.
I actually ran into similar problem. I am going all idiomatic python for kivy. I use a callback function on_press
.
Class MainWindow(ScreenManager):
<..code to add screens and add widget to screen...>
<...>
def add_button(self):
Button(id='button1', text='Hello %d'%i, size_hint=(0.2,0.2),
on_press=self.callback, background_color=[1,0,0,1])
In my callback,
def callback(self, value):
print '%s pressed.'%value
print value.id
value.background_color= (0,1,0,1)
Thats it. This will change the background color of the button from red to green.
What i actually need is to give different colors on different conditions based on a variable
You can implement that logic in your callback.. pass a
to the callback (I would suggest using partial for doing that)
ps. I also see you are using a separate class for Screen but that shouldn't matter here
答案 3 :(得分:0)
我知道这是在不久前问到的,但是当我尝试使用以上建议时,我的按钮从未变回其原始颜色。我最终解决该问题的方法是添加on_release以将其更改为所需的任何颜色:
on_press: self.background_color = (0, 1, 0, 1)
on_release: self.background_color = (1, 0, 0, 1)
想知道如果我遇到这个问题,可能有人想知道这个问题