Search code examples
wxpythonwxwidgets

How to put device context (wx.DC) into a sizer? -wxpython


Hello I would like to put device context into a sizer, however when I try to do this, python returns an error.

import wx
class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(250, 150))
        self.sizer = wx.BoxSizer()

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        button1 = wx.Button(self, id=wx.ID_ANY, label='Button',pos=(8, 38), size=(175, 28))
        self.sizer.Add(button1, 1, wx.EXPAND|wx.ALL, 10)
        self.Centre()
        self.Show()

    def OnPaint(self, e):
        dc = wx.PaintDC(self)
        self.sizer.Add(dc, 1, wx.EXPAND|wx.ALL, 10)
        dc.DrawLine(50, 60, 190, 60)

if __name__ == '__main__':
    app = wx.App()
    Example(None, 'Line')
    app.MainLoop()

Thank you!


Solution

  • The only thing you can put into a sizer is a window. A device context is not a window, so you cannot put it into a sizer.

    Create a window, put it into your sizer, then, when you need to draw on the window, create a device context from the window.

    I think that the best thing for you to do is to remove the line

        self.sizer.Add(dc, 1, wx.EXPAND|wx.ALL, 10)
    

    The line

      dc.DrawLine(50, 60, 190, 60)
    

    Will draw your line in the window that the dc belongs to ( self )