import wx
import wx.grid
import pandas as pd
class GridTable(wx.grid.Grid):
def __init__(self, parent, nrow=30, ncol=20):
wx.grid.Grid.__init__(self, parent)
#默认30行20列
self.CreateGrid(nrow, ncol)
#自动行数
def AutoRowNums(self, cur_rows=0, to_rows=0):
if cur_rows < to_rows:
self.InsertRows(to_rows, to_rows - cur_rows, updateLabels=True)
elif cur_rows > to_rows:
self.DeleteRows(to_rows, cur_rows - to_rows, updateLabels=True)
else:
pass
#自动列数
def AutoColNums(self, cur_cols=0, to_cols=0):
if cur_cols < to_cols:
self.InsertCols(cur_cols, to_cols - cur_cols, updateLabels=True)
elif cur_cols > to_cols:
self.DeleteCols(to_cols, cur_cols - to_cols, updateLabels=True)
else:
pass
#删除所有行
def DeleteAllRows(self):
if self.GetNumberRows() > 0:
self.DeleteRows(0, self.GetNumberRows(), updateLabels=True)
def SetTable(self, df):
if df.empty != True:
self.ClearGrid()
self.list_columns = df.columns.tolist()
self.AutoRowNums(self.GetNumberRows(), df.shape[0])
self.AutoColNums(self.GetNumberCols(), df.shape[1])
for col, series in df.iteritems():
m = self.list_columns.index(col)
#设置列标签,m为列号
self.SetColLabelValue(m, col)
#给单元格循环赋值,n为行号
for n, val in enumerate(series):
self.SetCellValue(n, m, str(val))
self.AutoSizeColumn(m, True) # 自动调整列尺寸
class GridFrame(wx.Frame):
#继承自Frame
df = pd.read_excel('润灵环球.xlsx')
def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.SetTitle("表格演示")
self.SetIcon(wx.Icon('Bank-green.ico'))#定义图标
self.SetSize(900, 500)
self.Center()
# 初始化窗口UI
self.init_ui()
def init_ui(self):
#将面板置于窗口上
panel = wx.Panel(self, -1)
#将表格置于面板上
self.grid = GridTable(panel)
#水平布局管理器管理面板布局
h_box = wx.BoxSizer()
h_box.Add(self.grid, proportion=1, flag=wx.EXPAND)
panel.SetSizer(h_box)
#传入表格
self.grid.SetTable(self.df)
#绑定左单击函数
self.grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.left_click)
#绑定右双击函数
self.grid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_DCLICK, self.right_dbclick)
#左单击打印单元格内容
def left_click(self, e):
grid0 = e.GetEventObject()
cell_value = grid0.GetCellValue(e.GetRow(), e.GetCol())
print(cell_value)
#右双击删除所有行
def right_dbclick(self, e):
self.grid.DeleteAllRows()
if __name__ == "__main__":
app = wx.App()
frame = GridFrame(None)
frame.Show()
app.MainLoop()
运行结果如下: