按标签拖动移动Kivy窗口 - Kivy,Python

时间:2018-05-05 16:07:46

标签: python click kivy drag motionevent

我想创建一个Kivy窗口的自定义窗口标题。我对kivy很新,所以请提供一些解释事件是如何工作的。我需要通过“移动”标签来移动窗口。

首先,我想知道,为什么当我点击或拖动标签时,它会调用任何函数。它在KvLang:

#:import main main.window

CustBoxLayout:
<CustBoxLayout>:
    orientation: 'vertical'

    Label:
        id: header
        text: 'MyApp'
        font_size: 24
        padding_x: 16
        color: self.theme_cls.primary_color

        on_touch_down: main.click
        on_touch_move: main.move

...

单击或拖动标签时,不会调用任何函数。但是,如果我将main.click更改为例如print('touched!')则可行。

所以我创建了自己的类:

class HeadLabel(MaterialLabel):
    def on_touch_down(self, touch):
        window.click(touch)

    def on_touch_move(self, touch):
        window.drag(touch)

这很有效。但现在我不知道如何从MotionEvent事件中获取屏幕位置。这是我的实际窗口代码:

class WindowApp(App):
    theme_cls = ThemeManager()

    def build(self):
        self.theme_cls.theme_style = 'Light'
        self.theme_cls.primary_palette = 'Purple'

        return CustBoxLayout()

    def click(self, touch):
        self.touch_x, self.touch_y = touch.spos[0], touch.spos[1]

    def drag(self, touch):
        Window.top = self.touch_y + touch.spos[0]
        Window.left = self.touch_x + touch.spos[1])

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

为自定义标签定义一个类,并实现 on_touch_down on_touch_move 方法。有关详细信息,请参阅以下示例。

Programming Guide » Input management » Touch event basics

  

默认情况下,会将触摸事件分派给当前显示的所有内容   小部件。这意味着小部件接收触摸事件是否发生   在他们的物理区域内与否。

     

为了提供最大的灵活性,Kivy发送了   所有小部件的事件,让他们决定如何对它们做出反应。   如果您只想响应窗口小部件中的触摸事件,那么   只需检查碰撞。

实施例

main.py

memcpy

test.kv

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivymd.theming import ThemeManager


class CustomLabel(Label):

    def on_touch_down(self, touch):
        print("\nCustomLabel.on_touch_down:")

        if self.collide_point(*touch.pos):
            print("\ttouch.pos =", touch.pos)
            self.touch_x, self.touch_y = touch.spos[0], touch.spos[1]
            return True
        return super(CustomLabel, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        print("\nCustomLabel.on_touch_move:")

        if self.collide_point(*touch.pos):
            print("\ttouch.pos =", touch.pos)
            Window.top = self.touch_y + touch.spos[0]
            Window.left = self.touch_x + touch.spos[1]
            return True
        return super(CustomLabel, self).on_touch_move(touch)


class CustBoxLayout(BoxLayout):
    pass


class TestApp(App):
    theme_cls = ThemeManager()

    def build(self):
        self.theme_cls.theme_style = 'Light'
        self.theme_cls.primary_palette = 'Purple'

        return CustBoxLayout()


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

输出

Img01 - on touch down Img02 - on touch move