今天我们为wxPython窗体设置鼠标点击事件,并在事件响应函数里画出黑白棋子。这里我们为窗体绑定wx.EVT_LEFT_UP这个事件码,来响应鼠标左键抬起事件。在事件处理函数里我们通过 event.GetPosition()函数来获取鼠标点击位置坐标,并将坐标点圆整,方便画圆形棋子时,棋子正好不偏不倚落在棋盘的交点处(后期可以加入随机数,对落子坐标进行处理,使棋子可以模拟现实落子,实现歪歪扭扭的效果)。我们采用wx.ClientDC容器来画棋子,wx.ClientDC不必设置在窗体事件中,可以随时作画,缺点是窗体重画之后会消失。
代码语言:javascript复制#在棋盘上画出棋子
import wx
class myFrame(wx.Frame):
def __init__(self):
self.unit = 30
self.pointNum = 15
self.pieceNum=0
self.bkCol=(220, 210, 0)
self.wht=(255,255,255)
self.blk=(0,0,0)
self.actColor=self.blk
super().__init__
(parent=None,pos=[100,100],
size=[self.unit*self.pointNum
self.unit 20,
self.unit*self.pointNum
self.unit 30 20],
title="商贾三国")
self.SetIcon(wx.Icon("WeatherBundle.ico"))
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(self.bkCol)
self.tip =
wx.TextCtrl(self.panel, -1, "",
pos=(self.unit*self.pointNum
self.unit-80, 0),
size=(80,25))
self.tip.SetBackgroundColour(self.bkCol)
self.panel.Bind(wx.EVT_PAINT,self.draw)
self.panel.Bind(wx.EVT_LEFT_UP, self.OnClick)
self.Show()
def draw(self,event):
mydc=wx.PaintDC(self.panel)
unit=self.unit
pointNum=self.pointNum
x=unit
y=unit
for i in range(1,pointNum 1):
mydc.DrawLine(x,y,x,unit*pointNum)
x=x unit
x=unit
for i in range(1,pointNum 1):
mydc.DrawLine(x, y, unit*pointNum, y)
y=y unit
def OnClick(self,event):
unit=self.unit
pos = event.GetPosition()
mydc=wx.ClientDC(self.panel)
if self.pieceNum%2==0:
self.actColor=self.blk
else:self.actColor=self.wht
mydc.SetBrush(wx.Brush(self.actColor))
x=round(pos.x/unit)*unit
y=round(pos.y/unit)*unit
mydc.DrawCircle(x,y,self.unit/2.5)
self.pieceNum = self.pieceNum 1
self.tip.SetValue('%s,%s' % (x,y))
myapp=wx.App()
myframe=myFrame()
myapp.MainLoop()
qizi.png