Search code examples
wxpython

how to draw a rectangle box on an image; wxPython?


I am trying to draw a rectangle on an image. the image has been set up on a panel.

I have tried using wx.PaintDC, it works on the panel and gets rid of the image. I want to have the rectangle on an image.

import wx

class window (wx.Frame):
    def __init__ (self, parent, id):
        wx.Frame.__init__ (self, parent, id, "Solitair", size = (1200, 800))
        self.add_menubar()
        self.panel = wx.Panel(self)
        img = 'background.jpg'
        bmp = wx.Image(img, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.bitmap = wx.StaticBitmap(self.panel, -1, bmp, (0,0))

        self.bitmap.Bind(wx.EVT_PAINT, self.drowRec)

    def drowRec(self, event):
        dc = wx.PaintDC(self.bitmap)
        dc.SetPen(wx.Pen('green', 5, wx.SOLID))
        dc.SetBrush(wx.Brush('green', wx.TRANSPARENT))
        dc.DrawRectangle(100, 50, 150, 200)

The rectangle supposed to be on an image panel, not on the actual empty panel.

please help. Thanks in advance


Solution

  • Adapting your code and the code at wxPython draw text onto EXISTING bitmap or image

    we can quickly knock up:

    import wx
    
    class window (wx.Frame):
        def __init__ (self, parent, id):
            wx.Frame.__init__ (self, parent, id, "Solitair", size = (1200, 800))
            self.panel = wx.Panel(self)
            img = 'wxPython.jpg'
            self.bmp = wx.Image(img, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
            self.bitmap = wx.StaticBitmap(self.panel, -1, self.bmp)
            self.drowRec(None)
    
        def drowRec(self, event):
            dc = wx.MemoryDC(self.bmp)
            dc.SetPen(wx.Pen('green', 5, wx.SOLID))
            dc.SetBrush(wx.Brush('green', wx.TRANSPARENT))
            dc.DrawRectangle(20, 20, 60, 60)
            del dc
            self.bitmap.SetBitmap(self.bmp)
    
    app = wx.App(False)
    frame = window(None, -1)
    frame.Show()
    app.MainLoop()
    

    enter image description here