Search code examples
wxpython

how can i fill Shape consist of lines and filled (wxpython)


i am new to wxpython. i want to draw a custom shape and upon completion the shape be filled with any or selected color (SetBrush) maybe.

Can anyone please help me example code. they are just 5 lines drawn but i cant fill the color inside this shape or any other custom shape.


Solution

  • You are right that SetBrush is the key to do it. Did you use DrawLines when you draw lines? If so, you can use DrawPolygon instead. This will close the polygon and fill the inside with the brush color. Pen color is for the outline. Here's a minimum example I wrote and tested on wxpython 2.8 on windows.

    SetDoubleBuffered is probably not important here but that is my default setting to prevent flickering.

    You can find a lot of other useful methods for drawing in the documentation for wx.DC.

    import wx
    
    class myframe(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, -1, title='Test', size=(200,200))
            self.Bind(wx.EVT_PAINT, self.OnPaint)
            self.SetDoubleBuffered(True)
            self.Show()
    
        def OnPaint(self, event):
    
            dc = wx.BufferedPaintDC(self)
            dc.Clear()
    
            dc.BeginDrawing()
    
            dc.SetBrush(wx.Brush(wx.RED, wx.SOLID))
            # dc.SetBrush(wx.Brush(wx.RED, wx.TRANSPARENT)) # when you dont want to fill
    
            dc.SetPen(wx.Pen(wx.NamedColour('cyan'), 1))
    
            #dc.DrawLines([(100,100), (120,100), (120,120), (100,120)]) # without fill, open end
            dc.DrawPolygon([(100,100), (120,100), (120,120), (100,120)])  # closed, filled
    
            dc.EndDrawing()
    
    if __name__ == '__main__':
    
        app = wx.PySimpleApp(0)
        frame = myframe()
        app.MainLoop()