wxpython 表格控件

本文介绍了一个使用Python wxPython库实现的费用管理系统GUI应用。该应用具备添加、删除费用项及保存的功能,并能自动计算费用总额。此外,应用还支持将费用数据导出到Word文档。
# -*- coding: utf-8 -*-

import wx
import wx.xrc
import wx.grid
import pandas as pd
from docx import Document

class MyFrame1 ( wx.Frame ):

	def __init__( self, parent ):
		wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"费用系统", pos = wx.DefaultPosition, size = wx.Size( 665,806 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

		self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )

		self.m_toolBar1 = self.CreateToolBar( wx.TB_HORIZONTAL, wx.ID_ANY )
		self.m_button1 = wx.Button( self.m_toolBar1, wx.ID_ANY, u"添加费用项", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_toolBar1.AddControl( self.m_button1 )
		self.m_button2 = wx.Button(self.m_toolBar1, wx.ID_ANY, u"删除费用项", wx.DefaultPosition, wx.DefaultSize, 0)
		self.m_toolBar1.AddControl(self.m_button2)
		self.m_button3 = wx.Button(self.m_toolBar1, wx.ID_ANY, u"保存", wx.DefaultPosition, wx.DefaultSize, 0)
		self.m_toolBar1.AddControl(self.m_button3)
		m_comboBox3Choices = [row for row in list(self.datas()['费用项']) if type(row) != float]
		self.m_comboBox3 = wx.ComboBox(self.m_toolBar1, wx.ID_ANY, u"选择费用项", wx.DefaultPosition, wx.DefaultSize,
									   m_comboBox3Choices, 0)
		self.m_toolBar1.AddControl(self.m_comboBox3)
		m_choice1Choices = ["USD","CNY"]
		self.m_choice1 = wx.Choice(self.m_toolBar1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, m_choice1Choices, 0)
		self.m_choice1.SetSelection(0)
		self.m_toolBar1.AddControl(self.m_choice1)
		self.m_toolBar1.Realize()

		bSizer2 = wx.BoxSizer( wx.VERTICAL )

		self.m_grid2 = wx.grid.Grid( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 )

		# Grid
		self.m_grid2.CreateGrid( 0, 5 )
		self.m_grid2.EnableEditing( True )
		self.m_grid2.EnableGridLines( True )
		self.m_grid2.EnableDragGridSize( False )
		self.m_grid2.SetMargins( 80, 806 )
		cols = ["费用项\n(Item)","单价\n(Unit Price)","数量\n(QTY)","币种\n(Currency)","金额\n(Amount)"]
		for i in range(5):
			self.m_grid2.SetColLabelValue(i,cols[i])
		# Columns
		self.m_grid2.SetColSize(0,300)
		self.m_grid2.SetLabelBackgroundColour("GOLDENROD")
		self.m_grid2.EnableDragColMove( False )
		self.m_grid2.EnableDragColSize( True )
		self.m_grid2.SetColLabelAlignment( wx.ALIGN_CENTER, wx.ALIGN_CENTER )
		self.m_grid2.SetColLabelSize(50)

		# Rows
		self.m_grid2.EnableDragRowSize( True )
		self.m_grid2.SetRowLabelAlignment( wx.ALIGN_CENTER, wx.ALIGN_CENTER )
		self.m_grid2.SetRowLabelSize(0)

		# Label Appearance
		# Cell Defaults
		self.m_grid2.SetDefaultCellAlignment( wx.ALIGN_LEFT, wx.ALIGN_TOP )
		bSizer2.Add( self.m_grid2, 0, wx.ALL, 5 )

		attr = wx.grid.GridCellAttr()
		attr.SetReadOnly(True)
		self.m_grid2.SetColAttr(0,attr)
		self.m_grid2.SetColAttr(3, attr)
		self.m_grid2.SetColAttr(4, attr)

		self.SetSizer( bSizer2 )
		self.Layout()

		self.Centre( wx.BOTH )

		# Connect Events
		self.m_button1.Bind( wx.EVT_BUTTON, self.add )
		self.m_button2.Bind(wx.EVT_BUTTON, self.delete)
		self.m_button3.Bind(wx.EVT_BUTTON, self.save)
		self.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.cellChanged)
		#self.m_grid2.SetCellValue()

	def __del__( self ):
		pass
	def datas(self):
		dt = pd.read_csv("Z:\\工作\\Database\\charges.csv")
		# print(reader)
		return dt
	def cellChanged(self, event):
		pos = self.m_grid2.GetGridCursorCoords()[0]
		# print(pos)
		total_amount = int(self.m_grid2.GetCellValue(pos,1))*int(self.m_grid2.GetCellValue(pos,2))
		self.m_grid2.SetCellValue(pos,4,str(total_amount))

	# Virtual event handlers, override them in your derived class
	def add( self, event ):
		self.m_grid2.AppendRows(1)
		aa = self.m_grid2.GetNumberRows()
		self.m_grid2.SetCellValue(aa-1,0,self.m_comboBox3.Value)
		self.m_grid2.SetCellValue(aa-1,3, self.m_choice1.GetStringSelection())


	def delete(self,event):
		#GetGridCursorCoords()
		pos = self.m_grid2.GetGridCursorCoords()[0]
		#print(pos)
		self.m_grid2.DeleteRows(pos,1)

	def save(self,evt):

		rows = self.m_grid2.GetNumberRows()
		cols = self.m_grid2.GetNumberCols()
		self.m_grid2.AppendRows(3)  # 添加2行
		data = []
		USD = []
		CNY = []
		for row in range(rows):
			data.append([self.m_grid2.GetCellValue(row,col) for col in range(cols)])
			if self.m_grid2.GetCellValue(row,3) == "USD":
				USD.append(self.m_grid2.GetCellValue(row,4))
			elif self.m_grid2.GetCellValue(row,3) == "CNY":
				CNY.append(self.m_grid2.GetCellValue(row,4))

		print(USD,CNY)
		# 汇总,保存
		t_USD = 0
		t_CNY =0
		for u in range(len(USD)):
			t_USD = t_USD + int(USD[u])
		for u in range(len(CNY)):
			t_CNY = t_CNY + int(CNY[u])
		data.append(["", "", "", "", ""])
		data.append(["","","Total:","USD",str(t_USD)])
		data.append(["", "", "Total:", "CNY", str(t_CNY)])
		self.m_grid2.SetCellValue(rows+1 , 2, "Total:")
		self.m_grid2.SetCellValue(rows+1 , 3, "USD:")
		self.m_grid2.SetCellValue(rows +1, 4, str(t_USD))
		self.m_grid2.SetCellValue(rows + 2, 3, "CNY:")
		self.m_grid2.SetCellValue(rows + 2, 4, str(t_CNY))

		print(tuple(data))
		# save to the word
		doc = Document(r'Z:\工作\Database\费用模版.docx')

		tables = doc.tables

		bl_table = tables[0]
		charge_table = tables[1]

		print(len(charge_table.rows))
		# charges = [["OCEAN FREIGHT", "18000", "2", "USD"], ["Local charge", "3212", "2", "CNY"]]
		charges = data
		for c in range(len(charges)-1):
			charge_table.add_row()
		print(len(charge_table.rows))
		for i, row in enumerate(charge_table.rows):
			if i > 0:
				for j in range(5):
					row.cells[j].text = charges[i - 1][j]

		doc.save(r'Z:\工作\Database\费用模版1.docx')





if __name__ == "__main__":
    app = wx.App()
    main = MyFrame1(None)
    main.Show()
    app.MainLoop()

wxPython 中实现表格功能,通常使用 `wx.grid.Grid` 控件。这是一个功能强大的控件,可以用于展示和编辑表格数据。下面是一个完整的示例代码,展示了如何创建一个基本的表格界面,并设置列标题、行标题以及填充表格数据: ```python import wx import wx.grid class MyFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Grid Example') panel = wx.Panel(self) # 创建一个表格 self.grid = wx.grid.Grid(panel) self.grid.CreateGrid(5, 3) # 创建一个 5 行 3 列的表格 # 设置表格的列标题 self.grid.SetColLabelValue(0, "Column A") self.grid.SetColLabelValue(1, "Column B") self.grid.SetColLabelValue(2, "Column C") # 设置表格的行标题 self.grid.SetRowLabelValue(0, "Row 1") self.grid.SetRowLabelValue(1, "Row 2") self.grid.SetRowLabelValue(2, "Row 3") # 向表格中添加数据 self.grid.SetCellValue(0, 0, "Data 1-1") self.grid.SetCellValue(0, 1, "Data 1-2") self.grid.SetCellValue(0, 2, "Data 1-3") self.grid.SetCellValue(1, 0, "Data 2-1") self.grid.SetCellValue(1, 1, "Data 2-2") self.grid.SetCellValue(1, 2, "Data 2-3") # 使用 sizer 来管理布局 sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.grid, 1, wx.EXPAND | wx.ALL, 5) panel.SetSizer(sizer) if __name__ == '__main__': app = wx.App() frame = MyFrame() frame.Show() app.MainLoop() ``` 此外,还可以通过继承 `wx.grid.Grid` 来创建自定义的表格类,以便更好地控制表格的行为和外观: ```python import wx.grid class MyGrid(wx.grid.Grid): def __init__(self, parent): super().__init__(parent) # 调用父类构造函数 self.CreateGrid(5, 3) # 创建一个5行3列的表格 # 设置列标题 self.SetColLabelValue(0, "名字") self.SetColLabelValue(1, "年龄") self.SetColLabelValue(2, "城市") ``` 以上代码展示了如何创建一个简单的表格,并设置了列标题和行标题,以及如何向表格中添加数据[^2]。对于更复杂的需求,如显示 Excel 文件中的数据,可以进一步扩展这些基础功能[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值