wxPython, dynamically modify window

cmcp mcphail_colin at hotmail.com
Tue Dec 12 14:52:19 EST 2006


Grant wrote:
> Hi, I am looking for a tip.  I have a panel and a checkbox.  When I
> check the checkbox, I would like to add buttons to the panel
> (dynamically).  When the checkbox is unchecked, the buttons should not
> appear (be deleted)---all the while, the window should resize if necessary.
>
Here is one way that seems to work (wxPython 2.7, Python 2.5, Mac OS X
10.4.8). It uses a sizer's Hide() and Show() methods to control
visibility of a child sizer containing the buttons. To resize the frame
containing the checkbox and buttons, ensure the frame has a sizer and
use the Fit() method after Hiding and Showing the buttons.
HTH,
-- CMcP

import wx

class AppFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title)
        panel = wx.Panel(self, -1)
        panel_sizer = wx.BoxSizer(wx.VERTICAL)
        panel.SetSizer(panel_sizer)

        cb = wx.CheckBox(panel, -1, 'Need some buttons')
        cb.SetValue(False)
        self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, cb)

        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        b1 = wx.Button(panel, -1, 'Button 1')
        b2 = wx.Button(panel, -1, 'Button 2')
        button_sizer.Add(b1, 0, wx.ALL, 5)
        button_sizer.Add(b2, 0, wx.ALL, 5)

        panel_sizer.Add(cb, 0, wx.ALL, 5)
        panel_sizer.Add(button_sizer)

        panel_sizer.Hide(button_sizer, recursive=True)

        frame_sizer = wx.BoxSizer()
        frame_sizer.Add(panel, 1, wx.EXPAND)

        self.SetSizer(frame_sizer)
        self.panel_sizer = panel_sizer
        self.button_sizer = button_sizer

        self.Fit()

    def EvtCheckBox(self, event):
        cb = event.GetEventObject()
        if cb.GetValue() == True:
            self.panel_sizer.Show(self.button_sizer, recursive=True)
        else:
            self.panel_sizer.Hide(self.button_sizer, recursive=True)
        self.Fit()

class App(wx.App):
    def OnInit(self):
        frame = AppFrame(None, 'Hide/Show Example')
        self.SetTopWindow(frame)
        frame.Show()
        return True
    
if __name__ == '__main__':
    app = App()
    app.MainLoop()




More information about the Python-list mailing list