Search code examples
wxpython

How to draw a rectangle and put a text inside it


I am using wxPython for first time. My requirement is to create a rectangular box and write some text in it. I tried to achieve the same but the rectangular box is not getting rendered in the windows frame:

#!/usr/bin/env python

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)
        self.InitUI()

    def InitUI(self):
        self.SetTitle('BPSK')
        self.Maximize(True)
        self.Show(True)
        dc = wx.WindowDC(self)
        dc.DrawRectangle(10, 10, 200, 200)


    def ShowMessage(self, message):
        wx.MessageBox(message, 'Info',
            wx.OK | wx.ICON_INFORMATION)


def main():
    ex = wx.App()
    Example(None)
    ex.MainLoop()


if __name__ == '__main__':
    main()

I am not sure what wrong I am doing wrong?


Solution

  • There are several issues with your example:

    While it does work (at least on wxPython 2.9.5.1/msw), it is probably not what you want:

    • The wx.WindowDC paints on the whole wx.Frame (instead of the interior of the frame). You would use a wx.ClientDC to only draw onto the interior (and not the titlebar and the icons of the frame).

    However, there will be another problem: As soon as you minimize the frame, the graphics will be gone.

    To cut it short, see the following example for the simplest way to draw properly in the wxPython wiki (meaning, fire off some drawing commands and having it repainted/refreshed properly).

    The other way would be to draw a bitmap yourself (wx.Bitmap + wx.MemoryDC + wx.GraphicsContext for antialiased drawing) and use a wx.StaticBitmap to have it displayed.