How to change background image of button when clicked in kivy?

289 views
Skip to first unread message

mehdi alizade

unread,
Jul 7, 2021, 10:34:34 AM7/7/21
to Kivy users support

I have two images for the background a button, One of the images is the default image of the button, I want to change the background image of button, when I click it. This is my code:

class Control_(Screen):
    Status = 0
    print(Status)
    def StatusButton(self):
        if self.RelayStatus == 0:
            self.Status = 1
            print(self.Status)
        elif self.Status == 1:
            self.Status = 0   
            print(self.Status)     

and *.kv is:

<Control_>:
            Button:
            background_normal: "on.png"
            size_hint: .3, .2
            pos_hint: {"x":.3, "y":.3} 
            on_release:
                root.StatusButton()
This is my images: 

off.png
on.png

Elliot Garbus

unread,
Jul 7, 2021, 12:49:01 PM7/7/21
to kivy-...@googlegroups.com

Here is an example.  I called the button SlideButton.  It is created by adding ToggleButtonBehavior to an Image. 

 

from kivy.app import App

from kivy.lang import Builder

from kivy.uix.behaviors import ToggleButtonBehavior

from kivy.uix.image import Image

 

kv = """

<SlideButton>:

    allow_stretch: True  # you can make this False if you do not want the button to scale with widget size

    source: 'off.png'

    on_state:

        self.source = {'normal': 'off.png', 'down': 'on.png'}[self.state]

 

FloatLayout:

    SlideButton:

        pos_hint: {'center_x': 0.5, 'center_y': 0.5}

        size_hint: None, None

        size: 200, 100

 

"""

 

 

class SlideButton(ToggleButtonBehavior, Image):

    pass

 

class AMCustomToggle(App):

    def build(self):

        return Builder.load_string(kv)

 

 

AMCustomToggle().run()

--
You received this message because you are subscribed to the Google Groups "Kivy users support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kivy-users+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/kivy-users/80831568-d7a1-4123-866c-4f1a64be7575n%40googlegroups.com.

 

mehdi alizade

unread,
Jul 10, 2021, 12:59:55 PM7/10/21
to kivy-...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages