Search code examples
pythonwxpython

wxpython - Split horizontal BoxSizer vertically


I try to write some small GUI's for testing with wxpython. I got an BoxSizer with two Panels in it. But now i want to have two panels next to each other at the bottom of my GUI. How do i split the Horizontal Sizer Vertically?

Here is my Code so far:

import wx

class MyFrame(wx.Frame):
   def __init__(self, parent, ID, title):
       wx.Frame.__init__(self, parent, ID, title, size=(300, 250))

       panel1 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
       panel2 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)   

       panel1.SetBackgroundColour("BLUE")
       panel2.SetBackgroundColour("RED")

       box = wx.BoxSizer(wx.VERTICAL)
       box.Add(panel1, 2, wx.EXPAND)
       box.Add(panel2, 1, wx.EXPAND)    

       self.SetAutoLayout(True)
       self.SetSizer(box)
       self.Layout()    

app = wx.PySimpleApp()
frame = MyFrame(None, -1, "Sizer Test")
frame.Show()
app.MainLoop()

Solution

  • You need to create a vertically oriented BoxSizer as the top level sizer and then add your horizontal sizer to it. Here's an example:

    import wx
    
    class MyFrame(wx.Frame):
        def __init__(self, parent, ID, title):
            wx.Frame.__init__(self, parent, ID, title, size=(300, 250))
    
            main_panel = wx.Panel(self)
    
            panel1 = wx.Panel(main_panel,-1, style=wx.SUNKEN_BORDER)
            panel2 = wx.Panel(main_panel,-1, style=wx.SUNKEN_BORDER)
    
            panel1.SetBackgroundColour("BLUE")
            panel2.SetBackgroundColour("RED")
    
            mainsizer = wx.BoxSizer(wx.VERTICAL)
            mainsizer.AddStretchSpacer()
    
            box = wx.BoxSizer(wx.HORIZONTAL)
            box.Add(panel1, 2, wx.EXPAND)
            box.Add(panel2, 1, wx.EXPAND)
            mainsizer.Add(box, 1, wx.EXPAND)
    
            main_panel.SetSizer(mainsizer)
            self.Layout()    
    
    app = wx.App()
    frame = MyFrame(None, -1, "Sizer Test")
    frame.Show()
    app.MainLoop()
    

    Also note that wx.PySimpleApp is deprecated. You should just use wx.App now.