You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy:如何检测带有DragBehavior属性的拖拽组件的位置

实现方案

直接修改现有代码即可实现效果,修改后完整代码如下:

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.behaviors import DragBehavior
from kivy.uix.button import Button


Builder.load_file('main.kv')


class DragButton(DragBehavior, Button):
    def on_release(self):
        # 拖拽结束释放时触发判断
        # 将按钮当前坐标转为全局窗口坐标,避免父组件坐标差异影响判断
        btn_global_x = self.to_window(self.x, self.y)[0]
        # 获取分隔栏的全局x坐标作为左右区域分界
        splitter_global_x = self.parent.parent.ids.splitter.to_window(0, 0)[0]
        
        if btn_global_x > splitter_global_x:
            # 拖到右侧区域,迁移按钮到右侧容器
            self.parent.remove_widget(self)
            # 调整按钮高度适配右侧布局
            self.size_hint_y = 0.1
            self.parent.parent.ids.right_container.add_widget(self)
        else:
            # 拖到左侧区域,删除按钮
            self.parent.remove_widget(self)


class MainScreen(Widget):
    pass


class WorkingApp(App):
    def build(self):
        return MainScreen()


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

main.kv

<DragButton>
    drag_rectangle: self.x, self.y, self.width, self.height
    drag_timeout: 10000
    drag_distance: 0
    drag_clamp: True
    text: 'Hi'
    size_hint: (1, .5)

<MainScreen>
    BoxLayout:
        size: root.width, root.height
        orientation: 'horizontal'

        BoxLayout:
            id: left_container
            orientation: 'vertical'
            Label:
                text: 'Widgets'
                size_hint: (1, .25)
            
            DragButton:
            DragButton:
            DragButton:

        Splitter:
            id: splitter
            sizable_from: 'left'
            BoxLayout:
                id: right_container
                orientation: 'vertical'
                Label:
                    text: 'Check If they are here'
                    size_hint_y: 0.2

核心改动说明

  • 给左右区域容器、分隔栏都增加了id,方便组件互相调用
  • 重写了DragButton的on_release方法,在拖拽结束释放时判断按钮位置:
    • 按钮全局x坐标大于分隔栏x坐标则判定为在右侧区域,将按钮从左侧容器移除后添加到右侧容器
    • 反之判定为在左侧区域,直接移除按钮实现消失效果
  • 新增drag_clamp: True属性限制按钮拖拽范围不会超出窗口,优化拖拽体验
  • 右侧区域新增了垂直布局容器用来容纳拖拽过来的按钮,可自动排列

内容的提问来源于stack exchange,提问作者Noah Thwing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:36:02