Skip to content
Related Articles

Related Articles

How to add drag behavior in kivy widget ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 30 Jun, 2021

In this article, we will develop a GUI window using kivy framework of python, and we will add a Label having drag behavior on this window

Note: You can follow the same pattern for implementing drag events on other widgets also.

Approach:

Actually what we are doing is we are using are just using the concept of inheritance, and we are making a new widget(DraggableLabel) by combining the properties of Kivy Label widget and Kivy’s DragBehaviour class. And from the code, you can check that we have defined three properties 

  • drag_rectangle: it is the area in which we want to enable dragging you can see from the code the have used ourselves with the values of this property because we want to enable dragging in the whole Layout.
  • drag_timeout: it specifies the time after which dragging will be disabled from the Label if Label is not dragged, but it will come into play again if we start dragging.
  • drag_distance: Distance to move before dragging the DragBehavior, in pixels. As soon as the distance has been traveled, the DragBehavior will start to drag, and no touch event will be dispatched to the children.

And after defining properties we are simply just using our newly created widget as we use others.

Below is the Implementation:

Python3




from kivy.app import App
from kivy.uix.label import Label
  
# importing builder from kivy
from kivy.lang import Builder
from kivy.uix.behaviors import DragBehavior
  
# using this class we will combine
# the drag behaviour to our label widget
class DraggableLabel(DragBehavior, Label):
    pass
  
# this is the main class which
# will render the whole application
class uiApp(App):
  
    # method which will render our application
    def build(self):
        return Builder.load_string("""
<DraggableLabel>:
    drag_rectangle: self.x, self.y, self.width, self.height
    drag_timeout: 10000
    drag_distance: 0
DraggableLabel:
    text:"[size=40]GeeksForGeeks[/size]"
    markup:True
                                   """)
  
# running the application
uiApp().run()


Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!