我编写了这个小应用程序,它可以在用户选择的两个点之间绘制线条并且它可以工作,但是当窗口最小化或被另一个打开的窗口覆盖时,如何防止我绘制的线条消失?
class SimpleDraw(wx.Frame):
def __init__(self, parent, id, title, size=(640, 480)):
self.points = []
wx.Frame.__init__(self, parent, id, title, size)
self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot)
self.SetBackgroundColour("WHITE")
self.Centre()
self.Show(True)
def DrawDot(self, event):
self.points.append(event.GetPosition())
if len(self.points) == 2:
dc = wx.ClientDC(self)
dc.SetPen(wx.Pen("#000000", 10, wx.SOLID))
x1, y1 = self.points[0]
x2, y2 = self.points[1]
dc.DrawLine(x1, y1, x2, y2)
# reset the list to empty
self.points = []
if __name__ == "__main__":
app = wx.App()
SimpleDraw(None, -1, "Title Here!")
app.MainLoop()
请您参考如下方法:
您的问题是您仅在用户点击时绘图。调整大小/删除(当另一个窗口覆盖您的窗口时)问题是因为您的窗口没有维护可以重绘的“缓冲区”。
在这里,我修改了你的示例,它似乎工作正常。
import wx
class SimpleDraw(wx.Frame):
def __init__(self, parent, id, title, size=(640, 480)):
self.points = []
wx.Frame.__init__(self, parent, id, title, size)
self.Bind(wx.EVT_LEFT_DOWN, self.DrawDot)
self.Bind(wx.EVT_PAINT, self.Paint)
self.SetBackgroundColour("WHITE")
self.Centre()
self.Show(True)
self.buffer = wx.EmptyBitmap(640, 480) # draw to this
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
dc.Clear() # black window otherwise
def DrawDot(self, event):
self.points.append(event.GetPosition())
if len(self.points) == 2:
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
dc.Clear()
dc.SetPen(wx.Pen("#000000", 10, wx.SOLID))
x1, y1 = self.points[0]
x2, y2 = self.points[1]
dc.DrawLine(x1, y1, x2, y2)
# reset the list to empty
self.points = []
def Paint(self, event):
wx.BufferedPaintDC(self, self.buffer)
if __name__ == "__main__":
app = wx.App(0)
SimpleDraw(None, -1, "Title Here!")
app.MainLoop()
