wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl

时间:2022-09-17 07:13:08

wxPython各种控件用法官方手册 : http://xoomer.virgilio.it/infinity77/wxPython/widgets.html


(12)表格, wx.grid.Grid,构造函数:

自定义的Grdi控件:

xGridTable.py

#coding=utf-8
import wx.grid as grid

class StudentInfoGridTable(grid.PyGridTableBase):
def __init__(self, datas):
grid.PyGridTableBase.__init__(self)

self.datas = datas
self.colLabels = [u'试卷名', u'制卷人', u'制卷人账号', u'考试成绩', u'测试开始时间', u'测试结束时间', u'测试时长']

self.odd = grid.GridCellAttr()
self.odd.SetReadOnly(True)
self.odd.SetBackgroundColour('yellow')
self.even = grid.GridCellAttr()
self.even.SetReadOnly(True)
pass

def GetAttr(self, row, col, kind):
attr = [self.even, self.odd][row % 2]
attr.IncRef()
return attr
def GetNumberRows(self):
return len(self.datas)

def GetNumberCols(self):
return len(self.colLabels)

def GetColLabelValue(self, col):
return self.colLabels[col]

def GetRowLabelValue(self, row):
return str(row)

def GetValue(self, row, col):
return self.datas[row][col]

在需要使用该控件的时候,实例化:

from xGridTable import StudentInfoGridTable
gridDatas = [
[u'大仲马', u'', u'WUST', u'中文', u'研三'],
[u'牛顿', u'', u'HUST', u'物理', u'博一'],
[u'爱因斯坦', u'', u'HUST', u'物理', u'研一'],
[u'居里夫人', u'', u'WUST', u'化学', u'研一'],
]
self.gridTable = wx.grid.Grid(self, -1, pos=(5, 5), size=(600, 400), style=wx.WANTS_CHARS)
self.infoTable = StudentInfoGridTable(gridDatas)
self.gridTable.SetTable(self.infoTable, True)
效果:

wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl


(13)简单的列表,wx.ListBox,构造函数:

"""
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition,
Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray,
long style=0, Validator validator=DefaultValidator,
String name=ListBoxNameStr) -> ListBox
"""
panel = wx.Panel(self)
self.textFont = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)
listDatas = [u'ListBox是简单的列表', u'TreeCtrl是树状文件目录机构', u'ListCtrl复杂的列表',
u'RadioButton是单选项', u'CheckBox为多选项', u'StaticText显示静态文本',]
self.listBox = wx.ListBox(panel, -1, pos=(10, 10), size=(300, 120), choices=listDatas, style=wx.LB_SINGLE)
self.listBox.SetFont(self.textFont)
self.Bind(wx.EVT_LISTBOX, self.listCtrlSelectFunc, self.listBox)
效果:

wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl

ListBox的事件监听:

def listCtrlSelectFunc(self, event):    indexSelected = event.GetEventObject().GetSelection()    print '选中Item的下标:', indexSelected    pass
点击效果:

wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl


(14)复杂列表,wx.ListCtrl,自定义的列表

xListCtrl.py

#coding=utf-8
import wx

class CourseListCtrl(wx.ListCtrl):
def __init__(self, parent, subDatas, size, id=-1, pos=(0, 0), style=wx.LC_SMALL_ICON):
wx.ListCtrl.__init__(self, parent, id, pos, size, style)

self.subDatas = subDatas
self.InitUI()
pass
def InitUI(self):
il = wx.ImageList(45, 45, True)
logoBmp = wx.Bitmap(r"D:\book_icon.png", wx.BITMAP_TYPE_PNG)
il.Add(logoBmp)

self.AssignImageList(il, wx.IMAGE_LIST_SMALL)
self.ShowListDatas(self.subDatas)
pass
def ShowListDatas(self, datas):
self.subDatas = datas
for index in range(len(self.subDatas)):
subject = self.subDatas[index]
content = u"科目:{0} 科目介绍:{1}".format(subject.get('name', ''), subject.get('intro', ''))
self.InsertImageStringItem(index, content, 0)

def refreshDataShow(self, newDatas):
self.datas = newDatas
self.DeleteAllItems()
self.ShowListDatas(self.datas)
self.Refresh()

在使用ListCtrl的时候,导入并实例化:

from xListCtrl import CourseListCtrl

courseNames = [u'大学物理', u'计算机技术', u'微积分', u'电力电子']
courseDatas = []
for index in range(len(courseNames)):
obj = {}
obj['name'] = courseNames[index]
obj['intro'] = courseNames[index]+u'的简介......'
courseDatas.append(obj)

self.textFont = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)
self.courseListCtrl = CourseListCtrl(self, courseDatas, size=(300, 300), pos=(10, 10))
self.courseListCtrl.SetFont(self.textFont)
self.courseListCtrl.SetBackgroundColour('#ffffff')
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.courseListSelectFunc, self.courseListCtrl)
效果:

wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl

ListCtrl事件监听:

def courseListSelectFunc(self, event):
index = event.GetIndex()
print u'选中的Item的下标:', index
pass

(15)树状文件结构,wx.TreeCtrl,自定义的树状图:

xTreeCtrl.py

#coding=utf-8import wximport wx.gizmos as gizmoscityNames = {    "Beijing": u"北京",    "Wuhan": u"武汉",    "Shanghai": u"上海",}def GetCityChinexeName(id):    return cityNames.get(id, '')class CollegeTreeListCtrl(wx.gizmos.TreeListCtrl):    def __init__(self, parent=None, id=-1, pos=(0,0), size=wx.DefaultSize, style=wx.TR_DEFAULT_STYLE|wx.TR_FULL_ROW_HIGHLIGHT):        wx.gizmos.TreeListCtrl.__init__(self, parent, id, pos, size, style)        self.root = None        self.InitUI()        pass def InitUI(self):        self.il = wx.ImageList(16, 16, True)        self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, (16, 16)))        self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, (16, 16)))        self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, (16, 16)))        self.SetImageList(self.il)        self.AddColumn(u'学校名称')        self.AddColumn(u'是否985')        self.AddColumn(u'学校类型')        pass def ShowItems(self, datas):        self.SetColumnWidth(0, 150)        self.SetColumnWidth(1, 40)        self.SetColumnWidth(2, 47)        self.root = self.AddRoot(u'中国大学')        self.SetItemText(self.root, "", 1)        self.SetItemText(self.root, "", 2)        # 填充整个树        cityIDs = datas.keys()        for cityID in cityIDs:            child = self.AppendItem(self.root, cityID)            lastList = datas.get(cityID, [])            childTitle = GetCityChinexeName(cityID)+u" ("+str(len(lastList))+u"所大学)"            self.SetItemText(child, childTitle, 0)            self.SetItemText(child, "", 1)            self.SetItemText(child, "", 2)            self.SetItemImage(child, 0, which=wx.TreeItemIcon_Normal)            self.SetItemImage(child, 1, which=wx.TreeItemIcon_Expanded)            for index in range(len(lastList)):                college = lastList[index]                # TreeItemData是每一个ChildItem的唯一标示                # 以便在点击事件中获得点击项的位置信息                data = wx.TreeItemData(cityID+"|"+str(index))                last = self.AppendItem(child, str(index), data=data)                self.SetItemText(last, college.get('collegeName', ''), 0)                self.SetItemText(last, college.get('if_985_type', ''), 1)                self.SetItemText(last, college.get('collegeType', ''), 2)                self.SetItemImage(last, 0, which=wx.TreeItemIcon_Normal)                self.SetItemImage(last, 1, which=wx.TreeItemIcon_Expanded)        self.Expand(self.root)        pass def refreshDataShow(self, newDatas):        if self.root != None:            self.DeleteAllItems()        if newDatas != None:            self.ShowItems(newDatas)    def DeleteSubjectItem(self, treeItemId):        self.Delete(treeItemId)        self.Refresh()        pass

在需要显示数据的地方导入并实例化:

from xTreeCtrl import CollegeTreeListCtrl

self.treeListCtrl = CollegeTreeListCtrl(parent=self, pos=(-1, 39), size=(300, 300))
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeListCtrlClickFunc, self.treeListCtrl)


self.colleges = {
u'Beijing': [
{'collegeName': u'北京大学', 'if_985_type':u'', 'collegeType':u'综合类'},
{'collegeName': u'清华大学', 'if_985_type': u'', 'collegeType': u'理工类'},
{'collegeName': u'北京邮电大学', 'if_985_type': u'', 'collegeType': u'理工类'}],
u'Wuhan':[
{'collegeName': u'武汉大学', 'if_985_type': u'', 'collegeType': u'综合类'},
{'collegeName': u'华中科技大学', 'if_985_type': u'', 'collegeType': u'理工类'}
],
u'Shanghai': [
{'collegeName': u'上海交通大学', 'if_985_type': u'', 'collegeType': u'理工类'},
{'collegeName': u'复旦大学', 'if_985_type': u'', 'collegeType': u'综合类'},
{'collegeName': u'同济大学', 'if_985_type': u'', 'collegeType': u'综合类'}
]
}

# TreeCtrl显示数据接口
self.treeListCtrl.refreshDataShow(self.colleges)

效果:

wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl

TreeCtrl的点击事件:

def OnTreeListCtrlClickFunc(self, event):
if self.treeListCtrl.GetItemData(event.GetItem()) != None:
# 当前选中的TreeItemId对象,方便进行删除等其他的操作
self.currentTreeItemId = event.GetItem()
cityName, collegeIndex = str(self.treeListCtrl.GetItemData(event.GetItem()).GetData()).split("|")

collegeObj = self.colleges.get(cityName, [])[int(collegeIndex)]
print '点击了:', cityName +u""+collegeObj.get('collegeName', '')
pass
wxPython常用控件--wx.Grid,wx.ListBox,wx.ListCtrl,wx.TreeCtrl