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.
wx.Frame.__init__(self, None, -1, "Demo Window")
# Restore window's stateself.load_window_state()
# Handle the following events for storing# window's stateself.Bind(wx.EVT_CLOSE, self.on_close)
# window_rect holds the window's size and positionself.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 windowand 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)
""" When the processor is idle, store the window's rectangle into self.window_rect """
# Ignore the current size and position# when the window is maximizedif window_rect >0and window_rect >0:
self.window_rect = window_rect
""" When closing the window, copy the size and position from self.window_rect into a json file """self.on_idle(None)
""" Restore the size and position from the json file """# Use try/except for in case the file does not existtry:
withself.open_window_state_file('r') as rect_file:
window_state = json.load(rect_file)
""" Copy the size and position from self.window_rect into the json file """
window_state = \
withself.open_window_state_file('w') as rect_file:
""" Open the json file """returnopen('window_state.json', mode)
if __name__ =='__main__':
app = wx.App()
win = DemoFrame()