Search code examples
pythonwxpython

How to switch panels in python using wxPython


I'm trying to create an App which allows the user to switch the information show using buttons. The basic idea of the code is that the user sees buttons on the left side of the screen and when the user presses "button 1", the code shows Panel1. I've made 2 buttons so far and the code for 2 panels is written as well but i can't figure out how to update my MainFrame so it show a different panel when one of the buttons is pressed.
Code:

import wx

TabNumber = 1


class ButtonPanel(wx.Panel):
    def __init__(self, parent):
        global TabNumber
        super(ButtonPanel, self).__init__(parent, -1)
        self.Tab1Button = wx.Button(self, label="TAB 1")
        self.Tab1Button.Bind(wx.EVT_BUTTON, self.SwitchTab(1))
        self.Tab2Button = wx.Button(self, label="TAB 2")
        self.Tab2Button.Bind(wx.EVT_BUTTON, self.SwitchTab(2))

        self.Sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer.Add(self.Tab1Button, wx.CENTER,0)
        self.Sizer.Add(self.Tab2Button, wx.CENTER, 0)

        self.SetSizer(self.Sizer)

    def SwitchTab(self, tab):
        def OnClick(event):
            print(f"Switch to tab {tab} started")
            TabNumber = tab
            print(TabNumber)
        return OnClick


class Panel1(wx.Panel):
    def __init__(self, parent):
        super(Panel1, self).__init__(parent, -1)
        self.panel = wx.Panel(self)
        self.text = wx.StaticText(self.panel, label="1")


class Panel2(wx.Panel):
    def __init__(self, parent):
        super(Panel2, self).__init__(parent, -1)
        self.panel = wx.Panel(self)
        self.text = wx.StaticText(self.panel, label="2")


class MainFrame(wx.Frame):
    def __init__(self):
        super(MainFrame, self).__init__(None, -1, "Test Application")

        self.Panels = {
            "Panel1": Panel1(self),
            "Panel2": Panel2(self)

        }
        self.MySizer = wx.BoxSizer(wx.HORIZONTAL)
        self.tabpanel = ButtonPanel(self)
        self.MySizer.Add(self.tabpanel,wx.CENTER,0)

        self.InfoPanel = self.Panels["Panel"+str(TabNumber)]
        self.MySizer.Add(self.InfoPanel, wx.CENTER,0)
        self.SetSizer(self.MySizer)

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

I was also wondering how I can adjust the ratio for the space that is given to my ButtonPanel and my InfoPanel.


Solution

  • As far as I can see, you are trying to do something that works like a Wizard... On the one hand, you can use wx.adv.Wizard. On the other hand, you can look at this tutorial that does something very similar and adapt it to what you need:

    WXPython: How to create a generic wizard

    Good luck!