0

Im new to kivy, and i encountered problem that i cant find solution to myself. Basically i want to change color of the button everytime i press F4. This is my code in main loop:

if win32api.GetAsyncKeyState(F4) or F4s == True:
        F4sw = not F4sw
        if F4sw == True:
            ApexDash().recoilon()
        else:
            ApexDash().recoiloff()

And this is the method im referencing to when F4sw is True:

class ApexDash(Screen,FloatLayout):

def recoilon(self):
    global F4s
    F4s = True

    print('check')

    self.ids.recoil_on.color = (1,0,0,1)
    self.ids.recoil_off.color = (0,1,0,1)

So the issue here is, whenever i press F4 the print check goes through as its supposed to, but the button desnt change color. They do change colors however whenever i call the function from .kv file.

Button:
        id: recoil_on
        background_normal: ''
        text: 'ON'
        on_press: root.recoilon()
        color: 0,1,0,1
        size_hint: 0.1, 0.1
        pos_hint: {"x":0.03, "top":0.65}

But when executing the method from outside the class all the widget properties dont seem to work. Sorry if i missed something obvious, any help is appreciated.

Lee K
  • 1
  • 1

1 Answers1

0

Calling ApexDash() creates a new instance of ApexDash so every time you call ApexDash().recoilon() you create a new layout that is not displayed anywhere (you'd have to call add_widget to place it somewhere), change its widgets and then silently discard it. You should store a reference to your actual visible widget to manipulate it, something like:

if win32api.GetAsyncKeyState(F4) or F4s == True:
        F4sw = not F4sw
        if F4sw == True:
            self.apex_dash.recoilon()
        else:
            self.apex_dash.recoiloff()

or

if win32api.GetAsyncKeyState(F4) or F4s == True:
        F4sw = not F4sw
        if F4sw == True:
            self.ids.apex_dash.recoilon()
        else:
            self.ids.apex_dash.recoiloff()

I don't think you should use calls of win32api outside of the framework, Kivy can capture keyboard events itself (see here).

Also try avoiding using global in python code. A root widget level property might be a better choice.

Nykakin
  • 8,657
  • 2
  • 29
  • 42