Search code examples
pythonmatplotlibwxpython

Aligning in wxpython


I am trying to align checkboxes and matplotlib canvas in wx frame.

  • I need those check boxes to be aligned in left side and canvas on right side
  • below code not aligning them properly

can anybody suggest changes need to be done in the code ?

  • If I want to add one more canvas in the same frame how can i add it?

    import wx
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
    
    class canvasFrame(wx.Frame):
        def __init__(self,parent,id):
            wx.Frame.__init__(self,parent,id,"MyCanvas",size =(1200,400))
    
            self.fig = plt.Figure(figsize=(15,5))
            self.ax1 = self.fig.add_subplot(1,1,1)
            self.canvas = FigureCanvas(self, -1, self.fig)
    
            b1 = wx.CheckBox(self,-1,"Apples",(10,20),(160,-1))
            b2 = wx.CheckBox(self,-1,"Mango",(10,40),(160,-1))
    
            b1sizer = wx.BoxSizer(wx.VERTICAL)
            b2sizer = wx.BoxSizer(wx.VERTICAL)
            canvSizer = wx.BoxSizer(wx.HORIZONTAL)
    
            b1sizer.Add(b1,0,wx.ALL,5)
            b2sizer.Add(b2,0,wx.ALL,5)
            canvSizer.Add(self.canvas,wx.TOP | wx.EXPAND,5)
    
    if __name__ == "__main__":
       app = wx.App()
       frame = canvasFrame(parent=None,id = -1)
       frame.Show()
       app.MainLoop()
    

Solution

  • you are missing alot of parts of how sizers work ... I would really recommend revisiting the documentation and googling for tutorials

    class canvasFrame(wx.Frame):
        def __init__(self,parent,id):
            wx.Frame.__init__(self,parent,id,"MyCanvas",size =(1200,400))
    
            self.fig = plt.Figure(figsize=(15,5))
            self.ax1 = self.fig.add_subplot(1,1,1)
            self.canvas = FigureCanvas(self, -1, self.fig)
    
            b1 = wx.CheckBox(self,-1,"Apples",(10,20),(160,-1))
            b2 = wx.CheckBox(self,-1,"Mango",(10,40),(160,-1))
            # first create your sizer for your checkboxes
            checkbox_sizer = wx.BoxSizer(wx.VERTICAL)
            checkbox_sizer.AddMany([b1,b2]) # add both buttons to the sizer
            #next create the main sizer
            main_sizer = wx.BoxSizer(wx.HORIZONTAL)
            #add the checkbox sizer to the main_sizer
            main_sizer.Add(checkbox_sizer)
            # add the canvas to the main sizer
            main_sizer.Add(self.canvas)
            #Set the sizer as the sizer for the frame
            self.SetSizer(main_sizer)
            #call layout for the sizers to layout their elements
            self.Layout()
            #call fit to make the frame fit its contents
            self.Fit()