please help on grid

  • Giorgio Luciano

    Giorgio Luciano - 2008-04-04

    dear all
    First fo all sorry if the mail,
    but I've read around lot of things about this topic that they didint' seem to help.
    As a preface I would like to say that I'm not a programmer. science is my everyday job. I used matlab/Octave and I'm swithing to python since it's a very fast language for prototyping algorithm with a lot of possibility (when scipy is not enought I can call rpy and so I'm done with the statistics I need)
    I've started making a small application that plot (using matplotlib), learned how to set and get values etc. etc.
    The application run almost smooth (and for me it was a sueful tutorial).
    It open txt files, read them in array and then plot them
    the core code is just a where self.Fname is the stored value after opening a txt file

    print self.Fname
            print a

    but now comes the pain ! i thought it was useful to create a grid (liek the one in matlab, octave, etc) just to open the txt in an editor (possibly with copy and paste) and if changed and save one value to replot everything.
    Well I've seen the example in wx (megagrid etc..) they call a table and that what probably I need (sometime I have spectra with more than 500 variables, while other just 100 variables)
    but reading and writing in a table seem to involve a lot of things
    I've created a file with my personal grid (just the simple grid), but when I have this problem
    1) it does not copy and paste (for example from excel)
    2) I dont' understand if I have to save this new grid to a .py file and then import it ot if I define the class inside directly in the main frame I am writing
    3) hot to set using pyTableBase the value ? (it's not like in the text where I can use SetValue and GetValue)

    and this is what I asked in wxmailing list.
    But there I've one more problem
    how do I have to set my special grid in Boa ?
    I mean I can put a widget in the frame, but how to initialise it ? should I use an external class in another file ? should I inizialise it in the same frame where it will be visualised ?

    do anyone know links for a simple tutorial  about that ? can someone help ?
    Sorry if this is trivial for a programmer any help appreciated

    • Giorgio Luciano

      Giorgio Luciano - 2008-04-05

      There's the code for a try which doesn't work after trying to use a personal grid

      App done in boa + frame


      #!/usr/bin/env python

      import wx
      import Frame1

      modules ={'Frame1': [1, 'Main frame of Application', '']}

      class BoaApp(wx.App):
          def OnInit(self):
              self.main = Frame1.create(None)
              return True

      def main():
          application = BoaApp(0)

      if __name__ == '__main__':

      this the app that call


      this is the frame


      import wx
      import wx.grid

      def create(parent):
          return Frame1(parent)

      ] = [wx.NewId() for _init_ctrls in range(3)]

      class Frame1(wx.Frame):
          def _init_ctrls(self, prnt):
              # generated method, don't edit
              wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
                    pos=wx.Point(255, 228), size=wx.Size(566, 339),
                    style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
              self.SetClientSize(wx.Size(558, 305))
              self.grid1 = wx.grid.MyGrid(id=wxID_FRAME1GRID1, name='grid1',
                    parent=self, pos=wx.Point(40, 64), size=wx.Size(232, 177),
              self.radioButton1 = wx.RadioButton(id=wxID_FRAME1RADIOBUTTON1,
                    label='radioButton1', name='radioButton1', parent=self,
                    pos=wx.Point(352, 80), size=wx.Size(81, 13), style=0)

          def __init__(self, parent):
      class MyGrid(wx.grid.Grid):

          """ A Copy&Paste enabled grid class"""
          def __init__(self, parent, id, pos, size, style):
              wx.grid.Grid.__init__(self, parent, id, pos, size, style)
              wx.EVT_KEY_DOWN(self, self.OnKey)

          def selection(self):
              # Show cell selection
              # If selection is cell...
              if self.GetSelectedCells():
                  print "Selected cells " + str(self.GetSelectedCells())
              # If selection is block...
              if self.GetSelectionBlockTopLeft():
                  print "Selection block top left " + str(self.GetSelectionBlockTopLeft())
              if self.GetSelectionBlockBottomRight():
                  print "Selection block bottom right " + str(self.GetSelectionBlockBottomRight())
              # If selection is col...
              if self.GetSelectedCols():
                  print "Selected cols " + str(self.GetSelectedCols())
              # If selection is row...
              if self.GetSelectedRows():
                  print "Selected rows " + str(self.GetSelectedRows())
          def currentcell(self):
              # Show cursor position
              row = self.GetGridCursorRow()
              col = self.GetGridCursorCol()
              cell = (row, col)
              print "Current cell " + str(cell)
          def OnKey(self, event):
              # If Ctrl+C is pressed...
              if event.ControlDown() and event.GetKeyCode() == 67:
                  print "Ctrl+C"
                  # Call copy method
              # If Ctrl+V is pressed...
              if event.ControlDown() and event.GetKeyCode() == 86:
                  print "Ctrl+V"
                  # Call paste method
              # If Supr is presed
              if event.GetKeyCode() == 127:
                  print "Supr"
                  # Call delete method
              # Skip other Key events
              if event.GetKeyCode():

          def copy(self):
              print "Copy method"
              # Number of rows and cols
              rows = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
              cols = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
              # data variable contain text that must be set in the clipboard
              data = ''
              # For each cell in selected range append the cell value in the data variable
              # Tabs '\t' for cols and '\r' for rows
              for r in range(rows):
                  for c in range(cols):
                      data = data + str(self.GetCellValue(self.GetSelectionBlockTopLeft()[0][0] + r, self.GetSelectionBlockTopLeft()[0][1] + c))
                      if c < cols - 1:
                          data = data + '\t'
                  data = data + '\n'
              # Create text data object
              clipboard = wx.TextDataObject()
              # Set data object value
              # Put the data in the clipboard
              if wx.TheClipboard.Open():
                  wx.MessageBox("Can't open the clipboard", "Error")
          def paste(self):
              print "Paste method"
              clipboard = wx.TextDataObject()
              if wx.TheClipboard.Open():
                  wx.MessageBox("Can't open the clipboard", "Error")
              data = clipboard.GetText()
              table = []
              y = -1
              # Convert text in a array of lines
              for r in data.splitlines():
                  y = y +1
                  x = -1
                  # Convert c in a array of text separated by tab
                  for c in r.split('\t'):
                      x = x +1
                      self.SetCellValue(self.GetGridCursorRow() + y, self.GetGridCursorCol() + x, c)
          def delete(self):
              print "Delete method"
              # Number of rows and cols
              rows = self.GetSelectionBlockBottomRight()[0][0] - self.GetSelectionBlockTopLeft()[0][0] + 1
              cols = self.GetSelectionBlockBottomRight()[0][1] - self.GetSelectionBlockTopLeft()[0][1] + 1
              # Clear cells contents
              for r in range(rows):
                  for c in range(cols):
                      self.SetCellValue(self.GetSelectionBlockTopLeft()[0][0] + r, self.GetSelectionBlockTopLeft()[0][1] + c, '')

      • Werner F. Bruhin

        As Sourceforge mangles the code I responded on the gmane list for Boa.


        Basically you need to include "name" in the __init lines for your MyGrid and change the line self.grid1 = wx.grid.MyGrid(... to self.grid1 = MyGrid(....

        If you still want to use the Boa designer then you need to define it as a custom class.
        class Frame1(wx.Frame):
            _custom_classes = {'wx.grid.Grid': ['MyGrid'],}
            def _init_ctrls(self, prnt):

        class Frame1(wx.Frame):
            _custom_classes = {'wx.grid.Grid': ['MyGrid'],}

            def _init_ctrls(self, prnt):


        • Chelonian

          Chelonian - 2008-04-07

          Hi Werner,

          Although apparently the OP managed to get it, I got a little lost on how to use custom classes.  In your message, you wrote:

          If you still want to use the Boa designer then you need to define it as a custom class.
          class Frame1(wx.Frame):
          _custom_classes = {'wx.grid.Grid': ['MyGrid'],}

          def _init_ctrls(self, prnt):

          class Frame1(wx.Frame):
          _custom_classes = {'wx.grid.Grid': ['MyGrid'],}

          def _init_ctrls(self, prnt):

          but this is the same thing unless I am staring right at the difference and can't see it!  Would you mind explaining again how to add one's own class as a custom class?  Thanks.

          • Werner F. Bruhin

            Oops, the OP got it as he saw the original code, I wanted to show the following.

            class Frame1(wx.Frame): 

            def _init_ctrls(self, prnt): 

            class Frame1(wx.Frame): 
            _custom_classes = {'wx.grid.Grid': ['MyGrid'],} 

            def _init_ctrls(self, prnt): 

            By the way the complete code is on the Boa list on gmane (for the address see the previous message).

            Create a class with the same __init__ signature as the original either within the same module or import it with "from mymodel import *" and then define the custom class.

            Here another examples:
            class CasksDet(wx.Panel):
                _custom_classes = {'wx.TextCtrl': ['TextCtrl', 'TextCtrlML'],
                                   'wx.lib.masked.numctrl.NumCtrl': ['NumCtrl'],
                                   'wx.ComboBox': ['ComboBox'],
                                   'wx.Panel': ['ListCtrlPanel']}

            As you can see with the TextCtrl you can have multiple custom classes for the same widget.

            Then to use them drop e.g. a TextCtrl onto the Panel and then in the inspector use the drop down list to select either the TextCtrl or the TextCtrlML.

            There is also a sample in the Boa\Examples\advanced folder.

            Hope this helps

            • Chelonian

              Chelonian - 2008-04-08

              Thank you, Werner.

    • Giorgio Luciano

      Giorgio Luciano - 2008-04-06

      Ok Werner, thanks for your help and patience I will to do the change you suggested

    • Giorgio Luciano

      Giorgio Luciano - 2008-04-06

      Werner thanks a lot, you really saved my day.
      now the grid works and it copy and paste from other applications. but the most important think is that I can use it in Boa !
      Thanks again


Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks