观察OnPaint与OnIdle与OnSize事件
阅读原文时间:2023年07月10日阅读:1

import wx

class SketchWindow(wx.Window):
def __init__(self, parent, ID):
wx.Window.__init__(self, parent, ID)
self.SetBackgroundColour("White")
self.color = "Black"
self.thickness = 1
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
self.lines = []
self.curLine = []
self.pos = (0, 0)
self.InitBuffer()

    self.Bind(wx.EVT\_LEFT\_DOWN, self.OnLeftDown)  
    self.Bind(wx.EVT\_LEFT\_UP, self.OnLeftUp)  
    self.Bind(wx.EVT\_MOTION, self.OnMotion)  
    self.Bind(wx.EVT\_SIZE, self.OnSize)  
    self.Bind(wx.EVT\_IDLE, self.OnIdle)  
    self.Bind(wx.EVT\_PAINT, self.OnPaint)

def InitBuffer(self):  
    size = self.GetClientSize()  
    self.buffer = wx.EmptyBitmap(size.width, size.height)  
    dc = wx.BufferedDC(None, self.buffer)  
    dc.SetBackground(wx.Brush(self.GetBackgroundColour()))  
    dc.Clear()  
    self.DrawLines(dc)  
    self.reInitBuffer = False

def GetLinesData(self):  
    return self.lines\[:\]

def SetLinesData(self, lines):  
    self.lines = lines\[:\]  
    self.InitBuffer()  
    self.Refresh()

def OnLeftDown(self, event):  
    self.curLine = \[\]  
    self.pos = event.GetPositionTuple()  
    self.CaptureMouse()

def OnLeftUp(self, event):  
    if self.HasCapture():  
        self.lines.append((self.color,  
                           self.thickness,  
                           self.curLine))  
        self.curLine = \[\]  
        self.ReleaseMouse()

def OnMotion(self, event):  
    if event.Dragging() and event.LeftIsDown():  
        dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)  
        self.drawMotion(dc, event)  
    event.Skip()

def drawMotion(self, dc, event):  
    dc.SetPen(self.pen)  
    newPos = event.GetPositionTuple()  
    coords = self.pos + newPos  
print coords  
print "sss"  
    self.curLine.append(coords)  
    dc.DrawLine(\*coords)  
    self.pos = newPos

def OnSize(self, event):  
    self.reInitBuffer = True

def OnIdle(self, event):  
    if self.reInitBuffer:  
        self.InitBuffer()  
        self.Refresh(False)

def OnPaint(self, event):  
dc = wx.BufferedPaintDC(self, self.buffer) # 估计基本上不起作用,但是Python要求在OnPaint里必须创建一个dc  
print "fffff" # 只有被遮住后重新显现的时候才打印,否则移动窗口不会触发这里,甚至往下移动进一步遮住也不会触发这里

def DrawLines(self, dc):  
    for colour, thickness, line in self.lines:  
        pen = wx.Pen(colour, thickness, wx.SOLID)  
        dc.SetPen(pen)  
        for coords in line:  
            dc.DrawLine(\*coords)

def SetColor(self, color):  
    self.color = color  
    self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)

def SetThickness(self, num):  
    self.thickness = num  
    self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)

class SketchFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Sketch Frame",
size=(800,600))
self.sketch = SketchWindow(self, -1)

if __name__ == '__main__':
app = wx.PySimpleApp()
frame = SketchFrame(None)
frame.Show(True)
app.MainLoop()