Python大佬手把手教你用wxPython模块编写界面程序( 四 )


基础按钮Button;
图形按钮BitmapButton;
切换按钮ToggleButton(有两种状态可以切换:按下和未按下);
静态文本框StaticText(展示一行或多行只读文本);
文本输入框TextCtrl;
富文本输入框RichTextCtrl可以加入图像、文字色彩等效果;
带格式文本输入框StyledTextCtrl;
超链接HyperLinkCtrl;
静态位图:StaticBitmap;
静态分割线StaticLine(可垂直可水平);
静态框StaticBox(为了装饰用,将多个组件组合在一起显示);
下拉列表框ComboBox;
可编辑的下拉列表框Choice;
复选框CheckBox(有两个状态:勾选或未勾选);
单选按钮RadioButton(单选按钮是从一组选项中只能选择一个,将多个单选按钮组合成一个选项组时,只需设定第一个单选按钮style为wx.RB_GROUP,后面跟着的那些单选按钮就自动跟它一组,如果想另开一组,只需再将另一组的第一个单选按钮的style设置为wx.RB_GROUP);
进度条Gauge;
滑动条Slider;
整数数值调节钮SpinCtrl;
浮点数数值调节钮SpinCtrlDouble;
滚动条ScrollBar 。
高级组件列表框ListBox:是对一组选项的展示和交互,它有两个主要的事件,一个是wx.EVT_COMMAND_LISTBOX_SELECTED,即鼠标单击某一项时产生;另一个是wx.EVT_COMMAND_LISTBOX_DOUBLE_CLICKED,即鼠标双击某一项时产生 。
列表视图ListCtrl:也是用来展示一组选项,与ListBox不同的是,ListBox仅能展示一列,而ListCtrl能展示多列 。ListCtrl有三种视图模式:list、report和icon 。向ListCtrl中插入数据需要使用两种方法:首先使用InsertItem()方法获得行号,然后再在当前行中使用SetItem()方法在列中插入数据 。
Mixins:Mixins增强了ListCtrl的功能,它们都在wx.lib.mixins.listctrl这个模块中,一共有六种Mixins:
(1)wx.ColumnSorterMixin:使得在report视图中对列进行排序;
(2)wx.ListCtrlAutoWidthMixin:自动调整最后一列的宽度来占据剩余的空间;
(3)wx.ListCtrlSelectionManagerMix:定义了与系统无关的选择策略;
(4)wx.TextEditMixin:使得可以编辑文本;
(5)wx.CheckListCtrlMixin:给每一行增加了一个复选框;
(6)wx.ListRowHighlighter:候选行自动背景高亮 。
wx.html.HtmlWindow:用来展示HTML页面 。
wx.SplitterWindow:包含两个子窗口(如果使用wxFormBuilder,注意手动添加上两个panel)
另外还有比如:
树状结构TreeCtrl;
表格Grid;
搜索框SearchCtrl;
调色板ColourPickerCtrl;
字体设置器FontPickerCtrl;
文件选择器FilePickerCtrl;
文件目录选择器DirPickerCtrl;
文件树选择器GenericDirCtrl;
日期选择器DatePickerCtrl;
日历CalenderCtrl 。
绘图wxPython的绘图之前写过,参见以下两篇:
ImagePy解析:6 — wxPython GDI绘图和FloatCanvas
ImagePy解析:11 — 使用wxPython设备上下文绘图
自定义组件如上,wxPython的常用组件已经有很多,但仍然不能涵盖真实情况下的千奇百怪的需求,这时候就要根据自己的需求自定义组件 。
自定义组件有两种方式:一种是在现有组件的基础上修改或增强,这种方式仍然有一定的限制;另一种是结合wxPython的GDI绘图,自己从头创建组件,这种方式就具有极大的灵活性 。
从头绘制组件一般都是在wx.Panel基础上进行创建 。
俄罗斯方块下面给了一个俄罗斯方块的游戏程序代码,可以说是一个使用wxPython编写GUI程序的集大成者:
#!/usr/bin/python"""ZetCode wxPython tutorialThis is Tetris game clone in wxPython.author: Jan Bodnarwebsite: www.zetcode.comlast modified: April 2018""" import wximport randomclass Tetris(wx.Frame):def __init__(self, parent):wx.Frame.__init__(self, parent, size=(180, 380),style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^ wx.MAXIMIZE_BOX)self.initFrame()def initFrame(self):self.statusbar = self.CreateStatusBar()self.statusbar.SetStatusText('0')self.board = Board(self)self.board.SetFocus()self.board.start()self.SetTitle("Tetris")self.Centre()class Board(wx.Panel):BoardWidth = 10BoardHeight = 22Speed = 300ID_TIMER = 1def __init__(self, *args, **kw):# wx.Panel.__init__(self, parent)super(Board, self).__init__(*args, **kw)self.initBoard()def initBoard(self):self.timer = wx.Timer(self, Board.ID_TIMER)self.isWaitingAfterLine = Falseself.curPiece = Shape()self.nextPiece = Shape()self.curX = 0self.curY = 0self.numLinesRemoved = 0self.board = []self.isStarted = Falseself.isPaused = Falseself.Bind(wx.EVT_PAINT, self.OnPaint)self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)self.Bind(wx.EVT_TIMER, self.OnTimer, id=Board.ID_TIMER)self.clearBoard()def shapeAt(self, x, y):return self.board[(y * Board.BoardWidth) + x]def setShapeAt(self, x, y, shape):self.board[(y * Board.BoardWidth) + x] = shapedef squareWidth(self):return self.GetClientSize().GetWidth() // Board.BoardWidthdef squareHeight(self):return self.GetClientSize().GetHeight() // Board.BoardHeightdef start(self):if self.isPaused:returnself.isStarted = Trueself.isWaitingAfterLine = Falseself.numLinesRemoved = 0self.clearBoard()self.newPiece()self.timer.Start(Board.Speed)def pause(self):if not self.isStarted:returnself.isPaused = not self.isPausedstatusbar = self.GetParent().statusbarif self.isPaused:self.timer.Stop()statusbar.SetStatusText('paused')else:self.timer.Start(Board.Speed)statusbar.SetStatusText(str(self.numLinesRemoved))self.Refresh()def clearBoard(self):for i in range(Board.BoardHeight * Board.BoardWidth):self.board.append(Tetrominoes.NoShape)def OnPaint(self, event):dc = wx.PaintDC(self)size = self.GetClientSize()boardTop = size.GetHeight() - Board.BoardHeight * self.squareHeight()for i in range(Board.BoardHeight):for j in range(Board.BoardWidth):shape = self.shapeAt(j, Board.BoardHeight - i - 1)if shape != Tetrominoes.NoShape:self.drawSquare(dc,0 + j * self.squareWidth(),boardTop + i * self.squareHeight(), shape)if self.curPiece.shape() != Tetrominoes.NoShape:for i in range(4):x = self.curX + self.curPiece.x(i)y = self.curY - self.curPiece.y(i)self.drawSquare(dc, 0 + x * self.squareWidth(),boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),self.curPiece.shape())def OnKeyDown(self, event):if not self.isStarted or self.curPiece.shape() == Tetrominoes.NoShape:event.Skip()returnkeycode = event.GetKeyCode()if keycode == ord('P') or keycode == ord('p'):self.pause()returnif self.isPaused:returnelif keycode == wx.WXK_LEFT:self.tryMove(self.curPiece, self.curX - 1, self.curY)elif keycode == wx.WXK_RIGHT:self.tryMove(self.curPiece, self.curX + 1, self.curY)elif keycode == wx.WXK_DOWN:self.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY)elif keycode == wx.WXK_UP:self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)elif keycode == wx.WXK_SPACE:self.dropDown()elif keycode == ord('D') or keycode == ord('d'):self.oneLineDown()else:event.Skip()def OnTimer(self, event):if event.GetId() == Board.ID_TIMER:if self.isWaitingAfterLine:self.isWaitingAfterLine = Falseself.newPiece()else:self.oneLineDown()else:event.Skip()def dropDown(self):newY = self.curYwhile newY > 0:if not self.tryMove(self.curPiece, self.curX, newY - 1):breaknewY -= 1self.pieceDropped()def oneLineDown(self):if not self.tryMove(self.curPiece, self.curX, self.curY - 1):self.pieceDropped()def pieceDropped(self):for i in range(4):x = self.curX + self.curPiece.x(i)y = self.curY - self.curPiece.y(i)self.setShapeAt(x, y, self.curPiece.shape())self.removeFullLines()if not self.isWaitingAfterLine:self.newPiece()def removeFullLines(self):numFullLines = 0statusbar = self.GetParent().statusbarrowsToRemove = []for i in range(Board.BoardHeight):n = 0for j in range(Board.BoardWidth):if not self.shapeAt(j, i) == Tetrominoes.NoShape:n = n + 1if n == 10:rowsToRemove.append(i)rowsToRemove.reverse()for m in rowsToRemove:for k in range(m, Board.BoardHeight):for l in range(Board.BoardWidth):self.setShapeAt(l, k, self.shapeAt(l, k + 1))numFullLines = numFullLines + len(rowsToRemove)if numFullLines > 0:self.numLinesRemoved = self.numLinesRemoved + numFullLinesstatusbar.SetStatusText(str(self.numLinesRemoved))self.isWaitingAfterLine = Trueself.curPiece.setShape(Tetrominoes.NoShape)self.Refresh()def newPiece(self):self.curPiece = self.nextPiecestatusbar = self.GetParent().statusbarself.nextPiece.setRandomShape()self.curX = Board.BoardWidth // 2 + 1self.curY = Board.BoardHeight - 1 + self.curPiece.minY()if not self.tryMove(self.curPiece, self.curX, self.curY):self.curPiece.setShape(Tetrominoes.NoShape)self.timer.Stop()self.isStarted = Falsestatusbar.SetStatusText('Game over')def tryMove(self, newPiece, newX, newY):for i in range(4):x = newX + newPiece.x(i)y = newY - newPiece.y(i)if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:return Falseif self.shapeAt(x, y) != Tetrominoes.NoShape:return Falseself.curPiece = newPieceself.curX = newXself.curY = newYself.Refresh()return Truedef drawSquare(self, dc, x, y, shape):colors = ['#000000', '#CC6666', '#66CC66', '#6666CC','#CCCC66', '#CC66CC', '#66CCCC', '#DAAA00']light = ['#000000', '#F89FAB', '#79FC79', '#7979FC','#FCFC79', '#FC79FC', '#79FCFC', '#FCC600']dark = ['#000000', '#803C3B', '#3B803B', '#3B3B80','#80803B', '#803B80', '#3B8080', '#806200']pen = wx.Pen(light[shape])pen.SetCap(wx.CAP_PROJECTING)dc.SetPen(pen)dc.DrawLine(x, y + self.squareHeight() - 1, x, y)dc.DrawLine(x, y, x + self.squareWidth() - 1, y)darkpen = wx.Pen(dark[shape])darkpen.SetCap(wx.CAP_PROJECTING)dc.SetPen(darkpen)dc.DrawLine(x + 1, y + self.squareHeight() - 1,x + self.squareWidth() - 1, y + self.squareHeight() - 1)dc.DrawLine(x + self.squareWidth() - 1,y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)dc.SetPen(wx.TRANSPARENT_PEN)dc.SetBrush(wx.Brush(colors[shape]))dc.DrawRectangle(x + 1, y + 1, self.squareWidth() - 2,self.squareHeight() - 2)class Tetrominoes(object):NoShape = 0ZShape = 1SShape = 2LineShape = 3TShape = 4SquareShape = 5LShape = 6MirroredLShape = 7class Shape(object):coordsTable = (((0, 0),(0, 0),(0, 0),(0, 0)),((0, -1),(0, 0),(-1, 0),(-1, 1)),((0, -1),(0, 0),(1, 0),(1, 1)),((0, -1),(0, 0),(0, 1),(0, 2)),((-1, 0),(0, 0),(1, 0),(0, 1)),((0, 0),(1, 0),(0, 1),(1, 1)),((-1, -1),(0, -1),(0, 0),(0, 1)),((1, -1),(0, -1),(0, 0),(0, 1)))def __init__(self):self.coords = [[0,0] for i in range(4)]self.pieceShape = Tetrominoes.NoShapeself.setShape(Tetrominoes.NoShape)def shape(self):return self.pieceShapedef setShape(self, shape):table = Shape.coordsTable[shape]for i in range(4):for j in range(2):self.coords[i][j] = table[i][j]self.pieceShape = shapedef setRandomShape(self):self.setShape(random.randint(1, 7))def x(self, index):return self.coords[index][0]def y(self, index):return self.coords[index][1]def setX(self, index, x):self.coords[index][0] = xdef setY(self, index, y):self.coords[index][1] = ydef minX(self):m = self.coords[0][0]for i in range(4):m = min(m, self.coords[i][0])return mdef maxX(self):m = self.coords[0][0]for i in range(4):m = max(m, self.coords[i][0])return mdef minY(self):m = self.coords[0][1]for i in range(4):m = min(m, self.coords[i][1])return mdef maxY(self):m = self.coords[0][1]for i in range(4):m = max(m, self.coords[i][1])return mdef rotatedLeft(self):if self.pieceShape == Tetrominoes.SquareShape:return selfresult = Shape()result.pieceShape = self.pieceShapefor i in range(4):result.setX(i, self.y(i))result.setY(i, -self.x(i))return resultdef rotatedRight(self):if self.pieceShape == Tetrominoes.SquareShape:return selfresult = Shape()result.pieceShape = self.pieceShapefor i in range(4):result.setX(i, -self.y(i))result.setY(i, self.x(i))return resultdef main():app = wx.App()ex = Tetris(None)ex.Show()app.MainLoop()if __name__ == '__main__':main()


推荐阅读