繁体   English   中英

我如何在 kivy 中生成事件,例如 on_touch_down 或 on_touch_up 事件

[英]how can i generate an event in kivy, like an on_touch_down or on_touch_up event

是否可以在 kivy 中生成一个事件,以便在用户不触摸屏幕的情况下调用 on_touch_up 或 on_touch_down function?

首先查看Motion Event文档中的注释:

您永远不会自己创建 MotionEvent:这是提供者的角色。

话虽如此,您可以创建和分派这样的最小事件:

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

该类(在本例中为MyBoxLayout )必须是EventDispatcher 调用mydispatchAnEvent()将派出一个最小的事件,所有的孩子都MyBoxLayout

使用此代码,我可以生成 touch_down 事件,但由于某种原因它不适用于 touch_up。 如果有人知道答案,将不胜感激。

要切换标签,它需要 touch_down 和 touch_up。

enter code here

from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.input.providers.mouse import MouseMotionEvent

from kivymd.app import MDApp
from kivymd.uix.tab import MDTabsBase

KV = '''
BoxLayout:
    orientation: "vertical"

    MDTabs:
        id: android_tabs
        on_tab_switch: app.on_tab_switch(*args)


<Tab>:

    MDLabel:
        id: label
        text: "Tab 0"
        halign: "center"
'''


class Tab(FloatLayout, MDTabsBase):
    '''Class implementing content for a tab.'''


class Example(MDApp):
    def build(self):
        return Builder.load_string(KV)


    def on_start(self):
        for i in range(5):
            self.root.ids.android_tabs.add_widget(Tab(title=f"Tab {i}"))
        Window.bind(on_motion=self.on_motion)
        Clock.schedule_once(self.dispatchTouchDown, 2)
        Clock.schedule_once(self.dispatchTouchUp, 2.5)

    def on_motion(self, obj, tevent, touch):
        print (tevent, touch.sx*Window.width, touch.sy*Window.height)


    def on_tab_switch(
        self, instance_tabs, instance_tab, instance_tab_label, tab_text
    ):
        instance_tab.ids.label.text = tab_text

    def dispatchTouchDown(self, *args):
        # create and dispatch a fake event
        touch = MouseMotionEvent(None, 0, (0, 0))  # args are device, id, spos
        touch.button = 'left'
        touch.pos = (130, 570)
        touch.x = touch.px = touch.ox = 130
        touch.y = touch.py = touch.oy = 570
        Window.dispatch('on_touch_down', touch)
        #This works

    def dispatchTouchUp(self, *args):
        # create and dispatch a fake event
        touch = MouseMotionEvent(None, 0, (0, 0))  # args are device, id, spos
        touch.button = 'left'
        touch.pos = (130, 570)
        touch.x = touch.px = touch.ox = 130
        touch.y = touch.py = touch.oy = 570
        Window.dispatch('on_touch_up', touch)
        #This does not work

Example().run()

暂无
暂无

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

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