您好我正在使用wxpython为项目绘制一个圆圈。请仔细查看代码并告诉我我做错了什么,它甚至没有显示任何错误,但也没有绘制圆圈。我只是一个空白的窗口。
import wx
class SketchFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(350,350))
self.sketch = SketchWindow(self, -1)
class SketchWindow(wx.Window):
def __init__ (self, parent,ID):
wx.Window.__init__(self, parent, ID)
self.panel =wx.Panel(self, size= (350,350))
self.InitBuffer()
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.Drawcircle(dc)
self.reInitBuffer=False
def Drawcircle(self,dc):
pen=wx.Pen('blue',4)
dc.SetPen(pen)
dc.DrawCircle(100,100,50)
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self, self.buffer)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=SketchFrame(None)
frame.Show(True)
app.MainLoop()
由于
答案 0 :(得分:6)
多个问题
您没有绑定到EVT_PAINT,例如 self.Bind(wx.EVT_PAINT,self.OnPaint)
在OnPaint中绘制,但是如果你想先绘制然后重用那个位图,onPaint就不需要BufferedPaintDC
使用wx.MemoryDC
您正在Window中创建一个面板,它将覆盖您在窗口中绘制的任何内容,因此请将其删除
您正在初始化初始化InitBuffer,其中大小可能不正确或非常少 您应该在调整大小或调用onPaint时执行此操作并检查大小是否已更改 所以在调整大小的窗口中心也能正确绘制圆圈
覆盖EVT_ERASE_BACKGROUND以避免闪烁
这是更新后的代码
import wx
class SketchFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(350,350))
self.sketch = SketchWindow(self, -1)
class SketchWindow(wx.Window):
def __init__ (self, parent,ID):
wx.Window.__init__(self, parent, ID)
self.Buffer = None
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBack)
def InitBuffer(self):
size=self.GetClientSize()
# if buffer exists and size hasn't changed do nothing
if self.Buffer is not None and self.Buffer.GetWidth() == size.width and self.Buffer.GetHeight() == size.height:
return False
self.Buffer=wx.EmptyBitmap(size.width,size.height)
dc=wx.MemoryDC()
dc.SelectObject(self.Buffer)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.Drawcircle(dc)
dc.SelectObject(wx.NullBitmap)
return True
def Drawcircle(self,dc):
size=self.GetClientSize()
pen=wx.Pen('blue',4)
dc.SetPen(pen)
dc.DrawCircle(size.width/2,size.height/2,50)
def OnEraseBack(self, event):
pass # do nothing to avoid flicker
def OnPaint(self, event):
if self.InitBuffer():
self.Refresh() # buffer changed paint in next event, this paint event may be old
return
dc = wx.PaintDC(self)
dc.DrawBitmap(self.Buffer, 0, 0)
self.Drawcircle(dc)
if __name__=='__main__':
app=wx.PySimpleApp()
frame=SketchFrame(None)
frame.Show(True)
app.MainLoop()
答案 1 :(得分:1)
wxPython演示对于这样的事情来说是一个很好的资源。例如,查看Miscellaneous下的演示 - > DrawXXXList。这个展示了如何在窗口中绘制一大堆椭圆。