简体   繁体   中英

Python/Kivy: initialize switch after startup (w/o running on_active)

I am facing a problem with the Kivy widget Switch and was not able to find a solution. Each topic on the Inte.net deals with "Working with the active property", which is understandable to me. But I want to set/initializie the start-up active value depending on the current environment within the program.

In my case: I have a Wifi Power-Plug which can be already running. So in this case when the app starts I want the switch with active: True . If the plug is deactivated, the switch shall start with active: False

Normaly you can do this from the main.py with sth. like:

if (getWifiState) == "OFF":
    self.ids[widgetName].active = False
else:
    self.ids[widgetName].active = True

Generally spoken this works and changes the state. But here the problem: as soon as you are changing the switch value this way it behaves as if you were clicking on the switch, because the default value = 0change to 1on_active: function() will be called. But I need a solution which allows me just to change the start value without running the on_active property.

Potential solution: Probably I have to put logic into my.kv file so that during the switch initialisation the correct start parameter will be set. But why? Or is there another way to do so?

Appreciate your help

Tried to put logic to my active property in.kv-File, but this did not work.

My solution:

import random
from kivy.app import App
from kivy.lang import Builder

kv = '''
BoxLayout:
    Switch:
        active: app.get_wifi_state()
        on_active: print(self.active)
'''

class Test(App):

    # method which return wifi status (replace implementation with your own)
    def get_wifi_state(self):
        return random.choice((True, False))

    def build(self):
        return Builder.load_string(kv)

Test().run()

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