Reputation: 13123
I have the following program that creates a wx grid, sets the background color of one cell, and then handles a left click event by setting the background color of the cell clicked:
import wx
import wx.grid as gridlib
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Sample grid")
self.grid = gridlib.Grid(self)
self.grid.CreateGrid(5,4)
self.grid.SetCellSize(4,1,1,2)
self.grid.SetDefaultCellAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
self.grid.SetColLabelSize(0) # eliminates spreadsheet-style row & col headers
self.grid.SetRowLabelSize(0)
self.grid.SetCellBackgroundColour(4, 3, wx.LIGHT_GREY)
rowHeight = 50
colWidth = 50
for i in range(1,5):
self.grid.SetRowSize(i, rowHeight)
for i in range(0,4):
self.grid.SetColSize(i, colWidth)
self.grid.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.GridLeftClick, self.grid)
def GridLeftClick(self, event):
col = event.GetCol()
row = event.GetRow()
print(f"Got col {col} and row {row}")
self.grid.SetCellBackgroundColour(row, col, wx.LIGHT_GREY)
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
Everything works as I expect except the self.grid.SetCellBackgroundColor(row, col, wx.LIGHT_GREY)
statement. The call works when I'm setting up the grid, so I think I have that correct. I get the print statement, so the event binding is working. What else do I have to do for that method to put a background color on the clicked cell?
Upvotes: 2
Views: 705
Reputation: 22443
You just need to refresh the window.
I've added a colour toggle so it will toggle between grey and white on a click.
import wx
import wx.grid as gridlib
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Sample grid")
self.grid = gridlib.Grid(self)
self.grid.CreateGrid(5,4)
self.grid.SetCellSize(4,1,1,2)
self.grid.SetDefaultCellAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
self.grid.SetColLabelSize(0) # eliminates spreadsheet-style row & col headers
self.grid.SetRowLabelSize(0)
self.grid.SetCellBackgroundColour(4, 3, wx.LIGHT_GREY)
rowHeight = 50
colWidth = 50
for i in range(1,5):
self.grid.SetRowSize(i, rowHeight)
for i in range(0,4):
self.grid.SetColSize(i, colWidth)
self.grid.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.GridLeftClick, self.grid)
def GridLeftClick(self, event):
col = event.GetCol()
row = event.GetRow()
clr = self.grid.GetCellBackgroundColour(row, col)
if clr != wx.LIGHT_GREY:
self.grid.SetCellBackgroundColour(row, col, wx.LIGHT_GREY)
else:
self.grid.SetCellBackgroundColour(row, col, wx.WHITE)
self.Refresh()
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
Upvotes: 3