wx grid SetCellBackGroundColor()不能按预期工作

问题描述 投票:0回答:1

我有以下程序创建一个wx网格,设置一个单元格的背景色,然后通过设置所单击的单元格的背景色来处理左键单击事件:

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()

self.grid.SetCellBackgroundColor(row, col, wx.LIGHT_GREY)语句外,其他所有操作均符合我的预期。该呼叫在我设置网格时有效,所以我认为我是正确的。我得到了打印语句,因此事件绑定正在工作。对于该方法,我还需要做什么才能将背景色放置在所单击的单元格上?

python wxpython
1个回答
0
投票

您只需要刷新窗口。我添加了颜色切换,因此单击时它将在灰色和白色之间切换。

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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.