How to drag and drop an image from a wx app

Hi, I would like to drag an image from a wx app to a target control in the same app. Ideally the following code would allow me to drag the StaticBitmap to the TextCtrl and print “On Data” when finished:

import wx

class MyDropTarget(wx.DropTarget):
    def __init__(self, source):
        super().__init__()
        self.source = source
        self.SetDataObject(self.source)

    def OnData(self, x, y, d):
        print('On Data')
        if self.GetData():
            img = self.source.GetBitmap()
        return d

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title='a2')
        p = wx.Panel(self, size=(240,240))

        sz  = wx.Size(64,64)
        ic  = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, size=sz)
        sb  = wx.StaticBitmap(p, -1, bitmap=ic, size=sz)
        bdo = wx.BitmapDataObject(ic)

        tex = wx.TextCtrl(p, -1, "DRAG_SOURCE", style = wx.TE_MULTILINE|wx.HSCROLL)
        dt1 = MyDropTarget(bdo)
        tex.SetDropTarget(dt1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(tex, 1, wx.SHAPED, 10)
        sizer.AddSpacer(10)
        sizer.Add(sb,  1, wx.SHAPED, 10)
        p.SetSizer(sizer)
        self.Show()

if __name__ == '__main__':
    app = wx.App()
    frm = MyFrame()
    app.MainLoop()

Unfortunately. nothing happens when I drag the image. Any help will be appreciated.

You need to catch the appropriate mouse events in your source widget, and respond by creating a wx.DropSource with the source data object, and then call DoDragDrop to create and run the DnD event loop. See the CustomDragAndDrop sample in the demo for more insights.

1 Like

Your drop target needs its own wx.BitmapDataObject() to
which whatever gets dropped onto it gets copied into, so:

 def __init__(self):
     super().__init__()
     my_bdo = wx.BitmapDataObject()
     self.SetDataObject(my_bdo)

 def OnData(self, x, y, d):
     print('On Data')
     if self.GetData():
         my_bdo = self.GetObject()
         img = my_bdo.GetBitmap()
     return d

(along those lines, untested)

Incidentally, when I asked about how to open a new topic by
email that was because I want to create a “generic” drop
target which accepts “anything” dropped onto it … :slight_smile:

Karsten

1 Like