gepcel
gepcel

Reputation: 1356

How to add multiple StaticBox(s) with child items within each StaticBox on a panel?

With wxpython, I want to create multiple StaticBox(s) on a panel, add some widgets to each staticbox. How can I do that? A minimal example to start with:

import wx

app = wx.App()
frame = wx.Frame(None, size=(700, 500))
panel = wx.Panel(frame)
vbox = wx.BoxSizer(wx.VERTICAL)

# Three StaticBox, with a StaticText within each
for n in range(3):
    sizer = wx.StaticBoxSizer(wx.VERTICAL, wx.StaticBox(panel,label=f"Box {n}"))
    sizer.Add(wx.StaticText(panel, label=f"StaticText of box {n}"))
    vbox.Add(sizer, 1, wx.EXPAND | wx.ALL, 5)

panel.SetSizer(vbox)
frame.Show()
app.MainLoop()

What's wrong with my code, because I got the following window:

enter image description here

Upvotes: 0

Views: 241

Answers (1)

Rolf of Saxony
Rolf of Saxony

Reputation: 22458

The manual https://wxpython.org/Phoenix/docs/html/wx.StaticBoxSizer.html gives a good example of how to use this widget container.

Here is your method modfied and a more pedantic method, commented out, using the old adage explict is better than implicit.

import wx

app = wx.App()
frame = wx.Frame(None, size=(700, 500))
panel = wx.Panel(frame)
vbox = wx.BoxSizer(wx.VERTICAL)

# Three StaticBox, with a StaticText within each
#sz1 = wx.StaticBoxSizer(wx.VERTICAL, panel, "Box1")
#sz1.Add(wx.StaticText(sz1.GetStaticBox(), wx.ID_ANY,"This window is a child of staticbox 1"))
#sz2 = wx.StaticBoxSizer(wx.VERTICAL, panel, "Box2")
#sz2.Add(wx.StaticText(sz2.GetStaticBox(), wx.ID_ANY,"This window is a child of staticbox 2"))
#sz3 = wx.StaticBoxSizer(wx.VERTICAL, panel, "Box3")
#sz3.Add(wx.StaticText(sz3.GetStaticBox(), wx.ID_ANY,"This window is a child of staticbox 3"))
#vbox.Add(sz1, 1, wx.EXPAND | wx.ALL, 5)
#vbox.Add(sz2, 1, wx.EXPAND | wx.ALL, 5)
#vbox.Add(sz3, 1, wx.EXPAND | wx.ALL, 5)

for n in range(3):
    sizer = wx.StaticBoxSizer(wx.VERTICAL, panel,label=f"Box {n}")
    sizer.Add(wx.StaticText(sizer.GetStaticBox(), label=f"StaticText of box {n}"))
    vbox.Add(sizer, 1, wx.EXPAND | wx.ALL, 5)

panel.SetSizer(vbox)
frame.Show()
app.MainLoop()

It should be noted that some themes (on Linux, don't know about other platforms) don't display the box. So while it may work on your machine, it may not on others, depending on their chosen desktop appearance.

enter image description here

Upvotes: 2

Related Questions