Search code examples
pythonwxpythonscrollablegridbagsizer

How to scroll Panel with GridBagSizer in wxPython


I need to make a Panel scrollable. I've used GridBagSizer

Code:

import wx

class MyFrame( wx.Frame ):
    def __init__( self, parent, ID, title ):
        wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 400, 300 ) )

        self.InitUI()
        self.Center()
        self.Show()


    def InitUI(self):

        MPanel = wx.Panel(self)
        GridBag = wx.GridBagSizer(2, 2)


        CO = ["RED", "BLUE"]

        for i in range(10):

            X = wx.StaticText(MPanel, size=(50,50), style=wx.ALIGN_CENTER, label="")
            X.SetBackgroundColour(CO[i%2])
            GridBag.Add(X, pos=(i+1, 1), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=1)

        GridBag.AddGrowableCol(1)
        MPanel.SetSizerAndFit(GridBag)

class MyApp( wx.App ):
    def OnInit( self ):
        self.fr = MyFrame( None, -1, "K" )
        self.fr.Show( True )
        self.SetTopWindow( self.fr )
        return True


app = MyApp( 0 )
app.MainLoop()

How can I do this?


Solution

  • Try if following solution helps you:

    import wx
    import wx.lib.scrolledpanel as scrolled
    class MyPanel(scrolled.ScrolledPanel):
    
        def __init__(self, parent):
            scrolled.ScrolledPanel.__init__(self, parent, -1)
            self.SetAutoLayout(1)
            self.SetupScrolling()
    

    Now Instead of using MPanel=wx.Panel(self), use `MPanel = MyPanel(self) and rest of your code will remain as is.

    Below is the modified code:

    class MyFrame( wx.Frame ):
        def __init__( self, parent, ID, title ):
            wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 400, 300 ) )
    
            self.InitUI()
            self.Center()
            self.Show()
    
        def InitUI(self):
    
            MPanel = MyPanel(self)
            GridBag = wx.GridBagSizer(2, 2)
    
            CO = ["RED", "BLUE"]
    
            for i in range(10):
                X = wx.StaticText(MPanel, size=(50,50), style=wx.ALIGN_CENTER, label="")
                X.SetBackgroundColour(CO[i%2])
                GridBag.Add(X, pos=(i+1, 1), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=1)
    
            GridBag.AddGrowableCol(1)
            MPanel.SetSizerAndFit(GridBag)
    
    class MyApp( wx.App ):
        def OnInit( self ):
            self.fr = MyFrame( None, -1, "K" )
            self.fr.Show( True )
            self.SetTopWindow( self.fr )
            return True
    
    app = MyApp( 0 )
    app.MainLoop()