Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...