Search code examples
wxpythonwxgrid

copy and paste from a Python wx.Grid


I'm wondering if someone might help? I have a form which is split into two panels. A leftP which has my controls, and the rightP which has a grid. I'm trying to copy/paste from the grid to the clipboard. With the following code, I get an error: AttributeError: 'RightPanel' object has no attribute 'grid'.
I'm following the same format I use for 'LeftPanel', which seems to work. Any thoughts?

import wx
import wx.grid as gridlib
import  pyodbc
import sys,os
import csv 

class RightPanel(wx.Panel):
""""""
def __init__(self, parent):
    """Constructor"""
    wx.Panel.__init__(self, parent=parent)
    self.SetBackgroundColour("light blue")        

def LoadData(self, connstr, query, table):  

    grid = gridlib.Grid(self)
    grid.CreateGrid(20,20)  
    con = pyodbc.connect(connstr)        
    cur = con.cursor()  
    # rest of Grid code here

class LeftPanel(wx.Panel):
""""""
def __init__(self, parent):
    """Constructor"""
    wx.Panel.__init__(self, parent=parent)

    # rest of Left Panel code here

class MyForm(wx.Frame):

def __init__(self):
    wx.Frame.__init__(self, None, wx.ID_ANY, "DB Viewer", size=(1150, 450)) 

    splitter = wx.SplitterWindow(self)
    self.leftP = LeftPanel(splitter)
    self.rightP = RightPanel(splitter)

    splitter.SplitVertically(self.leftP, self.rightP)
    splitter.SetMinimumPaneSize(20)

    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(splitter, 1, wx.EXPAND)
    self.SetSizer(sizer)


    self.rightP.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.copy)

    self.Layout()

def copy(self, event):
    print "Copy method"
    # Number of rows and cols

    rows = self.rightP.grid.GetSelectionBlockBottomRight()[0][0] -    self.rightP.grid.GetSelectionBlockTopLeft()[0][0] + 1
    cols = self.rightP.grid.GetSelectionBlockBottomRight()[0][1] - self.rightP.grid.GetSelectionBlockTopLeft()[0][1] + 1
    #This is where it throws an error####################    
    #Rest of copy Code goes Here


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

Solution

  • You need to set grid as a instance variable by putting 'self.' infront of it, at the moment grid is just a local variable

    Also you will need to call the 'loaddata' method before hand so the grid is created and stored as a instance variable.