Working Snippet from @Rolf of Saxony's
wx grid SetCellBackGroundColor() is not working as expected
based on @interjay's and @jake77 above answers:
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_SELECT_CELL, 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.SetDefaultCellBackgroundColour(wx.Colour(wx.WHITE))
self.grid.SetLabelBackgroundColour(wx.Colour(wx.WHITE))
else:
self.grid.SetCellBackgroundColour(row, col, wx.GREEN)
self.Refresh()
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
And 2nd snippet only partially working — the headers and row labels display all right but not the cells (feel free to fix it if you will!):
From wxPython: Grid Tips and Tricks
import wx
import wx.grid as gridlib
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Grid Color Bg")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.grid = gridlib.Grid(panel)
self.grid.CreateGrid(7, 5)
self.grid.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.colorBg)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.grid, 1, wx.EXPAND, 5)
panel.SetSizer(sizer)
# ----------------------------------------------------------------------
def colorBg(self, event):
""""""
clr = self.grid.GetDefaultCellBackgroundColour()
clr1 = self.grid.GetLabelBackgroundColour()
if clr != wx.Colour(wx.WHITE):
self.grid.SetDefaultCellBackgroundColour(
self.grid.SetLabelBackgroundColour(wx.Colour(wx.WHITE))
)
if clr1 != wx.Colour(wx.WHITE):
self.grid.SetDefaultCellBackgroundColour(wx.Colour(wx.WHITE))
# Run the program
if __name__ == "__main__":
app = wx.App()
frame = MyForm().Show()
app.MainLoop()