Search code examples
pythonuser-interfacewxpythonsizergridbagsizer

wxPython: Why is my wx.GridBagSizer not aligning my widgets when told to?


I am writing up a GUI in wxPython, and have used the wx.GridBagSizer to manage the layout. I want certain widgets (like buttons and text) to be aligned in certain ways in their respective grid-boxes. I thought the wx.ALIGN_LEFT and wx.CENTER flags provided when I add each widget to the sizer would handle this, but as you can see in this image of my GUI below... it doesn't do anything.

https://i.imgur.com/qePQ7g2.png (can't embed image since I have <10 reputation :c)

EDIT: This is how it should look: https://i.imgur.com/7TQ6ONe.png

Here's a sample of my code that shows how I established all the pictured widgets in the sizer...

I want txtComments to be centred, and everything else right-aligned.

    sizer = wx.GridBagSizer(0, 0)

    sizer.Add(self.txtProblemName, pos = (7, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtNumberOfNodes, pos = (8, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtRouteLength, pos = (9, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtRuntime, pos = (10, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtCreationDate, pos = (11, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtAuthor, pos = (12, 0), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border = 5)
    sizer.Add(self.txtComments, pos = (7, 4), span = (1, 2), flag = wx.EXPAND | wx.ALL | wx.CENTER, border = 0)

    self.SetSizerAndFit(sizer)

If anybody knows how to fix this I'd greatly appreciate it. My GUI currently looks like a mess. If possible, also provide a fix for vertical alignment, not just horizontal.

If you need more information about my implementation do not hesitate to ask. Thanks :D


Solution

  • Try removing the wx.EXPAND flag for the static text items. That flag tells the sizer to expand the size of the item so it fills the space that the sizer is giving to the item. If it is filling the space then there is no room to move it around for the alignment flags.

    Also, if you're not already familiar with it, you should get to know the Widget Inspection Tool. It is very handy for diagnosing sizer layout issues, and gives you a way to visualize the sizers and how the items within it are being positioned within their allotted space.