46-wxpython 4 使用 grid 展示表格

时间:2023-03-09 17:17:25
46-wxpython 4 使用 grid 展示表格
2018年01月10日 16:01:14 迦蓝叶 阅读数:3399
 版权声明:本文为博主原创文章,如需转载请在文章中注明“转载”并在文章开头附上本博客链接。 https://blog.csdn.net/soslinken/article/details/79024938

文章导航

wx.grid.Grid

Grid这个控件主要是用于显示和编辑表格数据。 
46-wxpython 4 使用 grid 展示表格 
控件样式在OS X 系统下显示样式

使用样例

import wx
import wx.grid class GridFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent) # Create a wxGrid object
grid = wx.grid.Grid(self, -1) # Then we call CreateGrid to set the dimensions of the grid
# (100 rows and 10 columns in this example)
grid.CreateGrid(100, 10) # We can set the sizes of individual rows and columns
# in pixels
grid.SetRowSize(0, 60)
grid.SetColSize(0, 120) # And set grid cell contents as strings
grid.SetCellValue(0, 0, 'wxGrid is good') # We can specify that some cells are read.only
grid.SetCellValue(0, 3, 'This is read.only')
grid.SetReadOnly(0, 3) # Colours can be specified for grid cell contents
grid.SetCellValue(3, 3, 'green on grey')
grid.SetCellTextColour(3, 3, wx.GREEN)
grid.SetCellBackgroundColour(3, 3, wx.LIGHT_GREY) # We can specify the some cells will store numeric
# values rather than strings. Here we set grid column 5
# to hold floating point values displayed with width of 6
# and precision of 2
grid.SetColFormatFloat(5, 6, 2)
grid.SetCellValue(0, 6, '3.1415') self.Show() if __name__ == '__main__': app = wx.App(0)
frame = GridFrame(None)
app.MainLoop()

  

这个demo 是从官方文档中摘取的 
英语好的亲们 ,直接看代码上的注释就好了,在此只把一些关键方法提出来说明一下。

CreateGrid 方法

可以使用该方法初始化一个固定行数、列数的Grid界面。行列数创建后仍可以使用方法增加行列。

 grid.CreateGrid(100, 10)
  • 1

SetCellValue 方法

可以使用SetCellValue 将指定行列的单元格内的值进行设置。

grid.SetCellValue(0, 0, 'wxGrid is good')
  • 1

SetRowLabelValue 、 SetColLabelValue

可以用于改变行标签、列标签。样例界面中,行标签 1、2、3等, 列标签A、B、C等。 
SetRowLabelValue第一个参数代表的是当前第几行 
SetColLabelValue第一个参数代表的是当前第几列

grid.SetRowLabelValue(0,"1") //第一行标签 1
grid.SetColLabelValue(0,"A") //第一列标签 A
  • 1
  • 2

以上几个方法就可以做一个简单的数据展示grid了!

事件

关于grid有几个关键的事件说明一下

事件 说明
EVT_GRID_CELL_CHANGING 单元格内数据发生变化中
EVT_GRID_CELL_CHANGED 单元格内数据发生变化后
EVT_GRID_CELL_LEFT_CLICK 左键单击单元格
EVT_GRID_CELL_LEFT_DCLICK 左键双击单元格
EVT_GRID_CELL_RIGHT_CLICK 右键单击单元格
EVT_GRID_CELL_RIGHT_DCLICK 右键双击单元格
EVT_GRID_SELECT_CELL 选中单元格事件

绑定事件代码

self.Bind(wx.EVT_GRID_CELL_CHANGED,self.cellChanged,self.grid)
  • 1

第一个参数:事件 
第二个参数:响应方法 
第三个参数:事件对象

响应方法需要特别提示一下: 
方法必须有一个event 参数 不然无法响应。

def cellChanged(self , event) :
//todo write event response code
  • 1
  • 2

疑问

在文档中,有个说明,就是在大型数据展示的时候,可以使用setTable(),方法设置一个wx.grid.GridTableBase的自定义子类。这样就可以做到数据与界面逻辑分离。

但是我写了一个GridTableBase的子类,setTable后并没有什么反应。不知道是怎么回事。只能是使用setCellValue 方法 循环将数据放置在grid上。

有大牛知道这个东西在 wxPython 4 中怎么使用吗。可以给小弟一个demo参考一下吗?