- 1 year ago
Python on Windows: How to enclose widgets in wxPython to labelled group, similarly to <fieldset> in HTML?
In wxPython, you can use the wx.StaticBox
and wx.StaticBoxSizer
classes to create a labeled group of widgets similar to the <fieldset>
element in HTML. Here's an example of how you can enclose widgets in a labeled group:
pythonimport wx
app = wx.App()
frame = wx.Frame(None, title="Group Example", size=(300, 200))
panel = wx.Panel(frame)
# Create a static box and sizer
static_box = wx.StaticBox(panel, label="Group")
sizer = wx.StaticBoxSizer(static_box, wx.VERTICAL)
# Add widgets to the sizer
label1 = wx.StaticText(panel, label="Widget 1")
label2 = wx.StaticText(panel, label="Widget 2")
label3 = wx.StaticText(panel, label="Widget 3")
sizer.Add(label1, flag=wx.ALL, border=5)
sizer.Add(label2, flag=wx.ALL, border=5)
sizer.Add(label3, flag=wx.ALL, border=5)
# Set the sizer for the panel
panel.SetSizer(sizer)
frame.Show()
app.MainLoop()
In this example, we create a wx.StaticBox
object with the desired label, and then we create a wx.StaticBoxSizer
object using the static box as the first parameter and wx.VERTICAL
as the second parameter to stack the widgets vertically.
Next, we create the widgets we want to enclose within the group, in this case, wx.StaticText
objects. We add these widgets to the sizer using the Add
method, specifying the desired flags and borders for spacing.
Finally, we set the sizer for the panel using SetSizer
, which applies the sizer to the panel, arranging the widgets within the labeled group.
Run the code to see the widgets enclosed in a labeled group similar to the <fieldset>
element in HTML.
Feel free to modify the code and add other widgets as needed to suit your specific requirements.