1

I want to simulate the user action and after looking in the doc, I saw the Clock.schedule_once(my_callback, 1).

.

Question: Is this the only way to do it ? I would have prefered something like my_button.press().

.

I want to press the button and then, it will call my_callback, I don't want to directly call my_callback.

(Because if I do this and my callback evolve, I lost the good reference)

PS: I saw that there was the possibility to use Clock.create_trigger(my_callback) but it didn't seems to be the good solution here.

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.clock import Clock

KV_APP = '''
BoxLayout:
    Button:
        id: my_button
        text: "Click on me"
'''

class TestApp(MDApp):
    def build(self):
        self.screen = Builder.load_string(KV_APP)
        self.screen.ids["my_button"].bind(on_press=self.on_button_click)
        event = Clock.schedule_once(self.on_button_click, 1)
        return self.screen

    def on_button_click(self, instance):
        print("hello there !")

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

1 Answers1

4

You can create an Event and dispatch it. Here is an example:

from kivy.app import App
from kivy.clock import Clock
from kivy.input.providers.mouse import MouseMotionEvent
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout


class MyBoxLayout(BoxLayout):
    def mydispatchAnEvent(self, *args):
        # create and dispatch a fake event
        touch = MouseMotionEvent(None, 123, (123, 456))  # args are device, id, spos
        touch.button = 'left'
        touch.pos = (321, 654)
        self.dispatch('on_touch_down', touch)


theRoot = Builder.load_string('''
MyBoxLayout:
    orientation: 'vertical'
    Label:
        text: 'Button below should demonstrate receiving touch event'
    Button:
        text: 'Waiting for event'
        on_press: print('touched')
''')


class EventDispatcherPlayApp(App):
    def build(self):
        Clock.schedule_once(theRoot.mydispatchAnEvent, 2)
        return theRoot

EventDispatcherPlayApp().run()
John Anderson
  • 35,991
  • 4
  • 13
  • 36
  • I'm gonna try this tomorrow, I have an aws api gateway to finish, thanks for the answer ! –  Feb 24 '21 at 15:15
  • I used this answer to automate some testing of my app. I know the kivy unit tests could be another way to do it, but still I'm surprised there aren't more questions and answers on the topic. – J B Jun 06 '22 at 01:51