如何在猕猴桃中按下按钮改变背景颜色? [英] How to change background color of button on press in kivy?

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

问题描述

我的应用程序有一个带有默认背景颜色的按钮.我只想在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

@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

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

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