简体   繁体   中英

How to change background color on click?

I would like to change the background color on click. It does not seem hard but the problem is I have button in another Kivy file, not in main. How to get property from this button and change its color?

Here's my try(code):

Python:

easy_button = ObjectProperty()
def easy_button(self):
        self.GAME_SPEED = 0.5
MainKV:
#:import menu menu

Game:

<Game>:
    menu_canvas: menu_canvas
    score_widget: score_widget
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'images/pixel.jpg'
    Label:
        font_name: "fonts/PermanentMarker-Regular.ttf"
        text: "SCORE " + str(root.score)
        size_hint: .2, .2
        pos_hint: {"x": .03, "y": .8}
        font_size: self.width/3.5
        opacity: 0
        id: score_widget
    MenuWidget:
        id: menu_canvas
 
Second Kivy File:
<MenuWidget>:
    Button:
            text: "Easy"
            font_name: "fonts/PermanentMarker-Regular.ttf"
            size_hint: .18, .15
            background_normal: ''
            background_color: .5, 1, .5, .85
            on_press: root.parent.easy_button()
            pos_hint: {"x": .2, "y": .1}
            font_size: self.width/5.5
            id: easy_button

Good day. Any kv imported allows you to use the imported widgets as you wish. When you call the widget, give it anid and you could alter its properties directly or in callback.

In your case, you would need to add a property to the MenuWidget of the id of the child button. Then you could change the properties of the child button by changing the properties of the button using the id in callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM