Draggable Widget

Lesson 14: Creating a draggable widget

This code was Inspired by Erco’s FLTK Cheat Page and pyFltk test programs.

from fltk import *

class tux(Fl_Box):
    def __init__(self,pic, x, y, w, h):
        Fl_Box.__init__(self, x, y, w, h)
        self.image(pic.copy(w,h))
        self.dx=0 #offsets to top corner of box
        self.dy=0

    def handle(self, event):
        r = super().handle(event)
        if event==FL_DRAG:
            X= Fl.event_x()
            Y= Fl.event_y()
            self.position(X-self.dx, Y-self.dy)
            self.parent().redraw()
            return 1
        elif event==FL_PUSH:
            self.dx= Fl.event_x() - self.x()
            self.dy= Fl.event_y() - self.y()
            return 1
        elif event==FL_RELEASE:
            return 1
        else:
            return r

class win(Fl_Window):
    def __init__(self, w, h):
        Fl_Window.__init__(self, w, h)
        img = Fl_PNG_Image('tux.png')
        self.cartoon = tux(img,0,0,100,150)
        self.end()

app=win(800,600)
app.show()
Fl.run()