Welcome

Restoring Window Size And Position With wxPython

When we develop a GUI application, we want it to be as user friendly as possible. User friendliness means among other things, opening the window in the right size and position. But what is the best size and position for a window? A good answer for this question is the size and position that was previously selected by the user.

Here is a code snippet that demonstrates how to do it in wxPython.

The code in action
import wx
import json


class DemoFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Demo Window")

        # Restore window's state
        self.load_window_state()

        # Handle the following events for storing
        # window's state
        self.Bind(wx.EVT_CLOSE, self.on_close)
        self.Bind(wx.EVT_IDLE, self.on_idle)

        # window_rect holds the window's size and position
        self.window_rect = None

        # The rest of this function fills
        # the window with some content

        # create a panel in the frame
        pnl = wx.Panel(self)

        # Put some text
        st = wx.StaticText(pnl,
            label="""Move and resize the window
and then try to close and reopen. 
The size and position will be restored""")

        # And create a sizer to manage the layout of
        # child widgets
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(st)
        pnl.SetSizer(sizer)

    def on_idle(self, event):
        """
        When the processor is idle, store the window's
        rectangle into self.window_rect
        """
        window_rect = self.GetRect()
        # Ignore the current size and position
        # when the window is maximized
        if window_rect[0] > 0 and window_rect[1] > 0:
            self.window_rect = window_rect

    def on_close(self, event):
        """
        When closing the window, copy the size and position
        from self.window_rect into a json file
        """
        self.on_idle(None)
        self.save_window_rect()
        self.Destroy()

    def load_window_state(self):
        """
        Restore the size and position from the json file
        """
        # Use try/except for in case the file does not exist
        try:
            with self.open_window_state_file('r') as rect_file:
                window_state = json.load(rect_file)
            self.SetRect(window_state['rect'])
            if window_state['is_maximized']:
                self.Maximize(True)
        except:
            pass

    def save_window_rect(self):
        """
        Copy the size and position
        from self.window_rect into the json file
        """
        window_state = \
            dict(rect=list(self.window_rect),
                 is_maximized=(self.window_rect !=
                               self.GetRect()))
        with self.open_window_state_file('w') as rect_file:
            json.dump(window_state, rect_file)

    @staticmethod
    def open_window_state_file(mode):
        """
        Open the json file
        """
        return open('window_state.json', mode)


if __name__ == '__main__':
    app = wx.App()
    win = DemoFrame()
    win.Show()
    app.MainLoop()

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami