如何在 wxPython 中使用 GridBagSizer 滚动面板

How to scroll Panel with GridBagSizer in wxPython

我需要使 Panel 可滚动。我用过 GridBagSizer

代码:

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()

我该怎么做?

如果以下解决方案对您有帮助,请尝试:

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()

现在不再使用 MPanel=wx.Panel(self),而是使用 `MPanel = MyPanel(self),其余代码将保持原样。

修改后的代码如下:

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()