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):
        self.source = 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)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(tex, 1, wx.SHAPED, 10)
        sizer.Add(sb,  1, wx.SHAPED, 10)

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

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):
     my_bdo = wx.BitmapDataObject()

 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:


1 Like