Kivy 拖动行为标签和矩形

Kivy Drag Behavior Labels and Rectangles

我对一个特定的想法有疑问:

我创建了一个矩形,我可以使用 Kivy 中的拖动行为拖动它。虽然,我只想拖动矩形 left/right 并固定 Y 位置。

我怎样才能做到这一点?我尝试了多种组合,在网上查找了这个特定问题,我什至查看了源代码,但我无法将它们组合在一起。非常感谢您的帮助!

下面是代码:

from kivy.uix.label import Label
from kivy.app import App
from kivy.uix.behaviors import DragBehavior
from kivy.lang import Builder

kv = '''
<DragLabel>:
    # Define the properties for the DragLabel
    drag_rectangle: self.x, self.y, self.width, self.height
    drag_timeout: 10000000
    drag_distance: 0

FloatLayout:
    # Define the root widget
    DragLabel:
        size_hint: 1.0, 0.2
        text: 'Drag me'
        canvas.before:
            Color:
                rgb: .6, .6, .6
            Rectangle:
                pos: self.pos
                size: self.size 
'''

class DragLabel(DragBehavior, Label):
    pass

class RectangleApp(App):
    def build(self):
        object = Builder.load_string(kv)
        return object

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

如果你真的想在 DragBehaviour 中使用 Label,那么你必须重新定义 Label

on_touch_upon_touch_downon_touch_move

但更好更简单的方法是使用 ScatterLayout 并禁用 y 轴上的平移:

from kivy.app import App
from kivy.lang import Builder

kv = '''
FloatLayout:
    # Define the root widget
    ScatterLayout:
        size_hint: 1.0, 0.2
        do_translation_y: False
        Label:
            size_hint: 1.0, 1
            text: 'Drag me'
            canvas.before:
                Color:
                    rgb: .6, .6, .6
                Rectangle:
                    pos: self.pos
                    size: self.size 
'''

class RectangleApp(App):
    def build(self):
        object = Builder.load_string(kv)
        return object

if __name__ == '__main__':
    RectangleApp().run()
from kivy.uix.button import Button
from kivy.app import App
from kivy.uix.behaviors import DragBehavior
from kivy.uix.boxlayout import BoxLayout


class Box_layout(BoxLayout):
    def __init__(self,**kwargs):
        super(Box_layout, self).__init__(**kwargs)
        self.size_hint = (.50,.50)
        self.orientation = "vertical"
        for  x in range(5):
           DragButton.text=str(x)
           self.add_widget(DragButton())

class DragButton(DragBehavior, Button):
    def __init__(self,**kwargs):
       super(DragButton, self).__init__(**kwargs)
       self.drag_rect_width = 1366
       self.drag_rect_height = 768
       self.drag_timeout = 10000000
       self.drag_distance = 0
       print(self.height, self.width)

这是 DragBehavior 的另一个例子