1. 程式人生 > >wxpython 4 使用 grid 展示表格

wxpython 4 使用 grid 展示表格

文章導航

wx.grid.Grid

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)

SetCellValue 方法

可以使用SetCellValue 將指定行列的單元格內的值進行設定。

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

SetRowLabelValue 、 SetColLabelValue

可以用於改變行標籤、列標籤。樣例介面中,行標籤 1、2、3等, 列標籤A、B、C等。
SetRowLabelValue第一個引數代表的是當前第幾行
SetColLabelValue第一個引數代表的是當前第幾列

grid.SetRowLabelValue(0,"1") //第一行標籤 1
grid.SetColLabelValue(0,"A") //第一列標籤 A

以上幾個方法就可以做一個簡單的資料展示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)

第一個引數:事件
第二個引數:響應方法
第三個引數:事件物件

響應方法需要特別提示一下:
方法必須有一個event 引數 不然無法響應。

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

疑問

在文件中,有個說明,就是在大型資料展示的時候,可以使用setTable(),方法設定一個wx.grid.GridTableBase的自定義子類。這樣就可以做到資料與介面邏輯分離。

但是我寫了一個GridTableBase的子類,setTable後並沒有什麼反應。不知道是怎麼回事。只能是使用setCellValue 方法 迴圈將資料放置在grid上。

有大牛知道這個東西在 wxPython 4 中怎麼使用嗎。可以給小弟一個demo參考一下嗎?