Open In App

How to add drag behavior in kivy widget ?

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 

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



Below is the Implementation:




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:

Article Tags :