Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

python - How to fire one event when we release the click on a kivy switch item?

Goal: when I click then release the click on the switch widget, it fires me an event on the release.

Problem: I used the on_touch_down() Switch method but:

  • it release 2 event on the release of the click and not only one.
  • when I release and it shows "off", it says "True" and it shows "False" when it's on "on" !
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout


KV = '''
MyGridLayout:
    Switch:
        id: switch_ecs
        on_touch_up:
            root.on_switch("ecs")
'''

class MyGridLayout(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def on_switch(self,element_id):
        print(self.ids["switch_" + element_id].active)

class MyApp(MDApp):
    def build(self):
        self.screen = Builder.load_string(KV)
        return self.screen



if __name__ == '__main__':
    MyApp().run()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Kivy has some obscure logic that results in touch up events getting dispatched twice to some widgets (like Buttons and Switches). The fix for your code is to use a different trigger for your on_switch() method. You can use:

    on_touch_down:
        root.on_switch("ecs")

or:

    on_active:
        root.on_switch("ecs")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...