简体   繁体   English

Python/Kivy:启动后初始化开关(不运行 on_active)

[英]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.我遇到了 Kivy 小部件Switch的问题,无法找到解决方案。 Each topic on the Inte.net deals with "Working with the active property", which is understandable to me. Inte.net 上的每个主题都涉及“使用活动属性”,这对我来说是可以理解的。 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.就我而言:我有一个可以运行的 Wifi 电源插头。 So in this case when the app starts I want the switch with active: True .因此,在这种情况下,当应用程序启动时,我希望切换为active: True If the plug is deactivated, the switch shall start with active: False如果插头被停用,开关应以active: False开头

Normaly you can do this from the main.py with sth.通常,您可以从 main.py 中使用某物执行此操作。 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.一般来说,这可以工作并更改 state。但这里的问题是:一旦您以这种方式更改开关值,它的行为就像您单击开关一样,因为默认值 = 0更改为 1on_active:函数()将被调用。 But I need a solution which allows me just to change the start value without running the on_active property.但我需要一个解决方案,它允许我在不运行 on_active 属性的情况下更改起始值。

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.可能的解决方案:可能我必须将逻辑放入 my.kv 文件中,以便在交换机初始化期间设置正确的启动参数。 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.试图将逻辑放入我的活动属性 in.kv-File,但这没有用。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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