如何在kivy中更改按钮的背景颜色? [英] How to change background color of button on press in kivy?

查看:53
本文介绍了如何在kivy中更改按钮的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用只有一个按钮,默认背景颜色.我只想在 on_press 事件上将其背景颜色更改为另一种颜色.您可以认为它类似于 html 的已访问和未访问的超链接,即当单击链接时,它会改变其颜色.

My app has a single button with a default background color. I just want to change its background color to another color on on_press event. You may consider it similar to visited and non-visited hyperlinks of html ie when a linked is clicked, it changes its color.

我的尝试:

#!/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 上什么也没有发生

But nothing happens on on_press

@inclement

实际上,我试图最小化我的问题.

Actually, i tried to minimized my problem.

我真正需要的是根据一个变量在不同的条件下给出不同的颜色

What i actually need is to give different colors on different conditions based on a variable

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)

所以我想在我的班级最高.请指导.提前致谢.

so i want impementation in my class Highest. Please guide. Thanks in advance.

推荐答案

如果您想将其保留在函数中,您还可以为按钮添加一个 id,然后从最高实例更改它.

If you wanted to keep it within a function, you could also add an id to the button and then change it from the Highest instance.

Builder.load_string("""
<Highest>:
    GridLayout:
        cols: 1
        Button:
            id: button_one
            text: "Hi"
            on_press: root.new()
""")

然后你可以参考id来改变颜色...

Then you can reference the id to change the color...

class Highest(Screen):
    def new(self):
        self.ids['button_one'].background_color = 1.0, 0.0, 0.0, 1.0

这篇关于如何在kivy中更改按钮的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆