What method / methods should be be used in order to get the frame to start up in a central position of the screen, and could you also provide the code please. I'm using wxPython. thanks

Dani AI

Generated

A few extra tips building on ’s answer for .

The simplest approach is what showed: wx provides a built‑in centering convenience on top‑level windows (Center / Centre) so you don’t have to compute screen coordinates yourself. Center is a thin synonym for Centre and will centre a top‑level window relative to its parent (or the screen if no parent is set). (docs.wxpython.org)

If you need more control there are explicit alternatives: use CentreOnScreen / CenterOnScreen (or CentreOnParent) when you want to force centring on the screen or on the parent window. The centring call accepts direction flags (wx.HORIZONTAL, wx.VERTICAL, wx.BOTH) if you only want one axis centred. Using the TopLevelWindow variants makes your intent explicit. (docs.wxpython.org)

If your frame size comes from sizers, finalize the size before centring. Call Fit() or ensure Layout() has run so the frame has its final size; centring before sizers finish will yield the wrong placement. Fit() is designed to size the window to its children when sizers are used. (sasview.org)

On multi‑monitor systems use wx.Display to pick the monitor and its client area (which accounts for taskbars) and compute the top‑left position yourself. Example pattern:

# after sizers/Fit/Layout so frame.GetSize() is correct
idx = wx.Display.GetFromPoint(wx.GetMousePosition())
disp = wx.Display(idx)
r = disp.GetClientArea()
w, h = frame.GetSize()
frame.SetPosition((r.x + (r.width - w)//2, r.y + (r.height - h)//2))
frame.Show()

wx.Display has helpers like GetFromPoint, GetFromWindow, GetClientArea, and scaling info (GetScaleFactor) you can use on high‑DPI setups. (docs.wxpython.org)

These extra cases cover the common pitfalls: parent vs screen centring, sizers that change final size, and multi‑monitor/DPI issues.

Recommended Answers

All 2 Replies

Here you go ...

# a wxPython general frame template

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("red")

        # create an input widget
        #
        # bind mouse or key event to an action
        #
        # create an output widget
        #

    def onAction(self, event):
        """ some action code"""
        pass


app = wx.App(0)
# create a MyFrame instance and show the frame
mytitle = 'the title'
width = 400
height = 300
frame = MyFrame(None, mytitle, (width, height))
# his will center the frame in the display area
frame.Center()
frame.Show()
app.MainLoop()

Thanks alot!!! it works beautifully!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.