Kivy拖动行为标签和矩形

时间:2017-11-26 18:59:18

标签: python python-2.7 kivy kivy-language

我遇到了一个特别的想法:

我创建了一个矩形,我可以使用Kivy中的拖动行为进行拖动。虽然,我希望只左/右拖动矩形并固定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()

2 个答案:

答案 0 :(得分:1)

如果你真的想在DragBehaviour中使用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()

答案 1 :(得分:0)

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的另一个示例