2010-02-13 204 views
2
dc.SetPen(wx.Pen(wx.BLACK, 0)) 
dc.SetBrush(wx.Brush("C0C0C0")) 
dc.DrawRectangle(50,50,50,50) 

这是我最好的尝试绘制无边框的50x50灰色框。但是,将笔宽设置为0似乎不能完成任何操作,并且设置笔刷只会将填充从纯白色更改为纯黑色。wxPython - 使用DC绘制未填充的矩形

下面是它在一个面板的情况下,在情况下,它是问题的一部分:

class DrawRect(wx.Panel): 
    def __init__(self,parent=None,id=-1,pos=(-1,-1),size=(-1,-1),style=0): 
     wx.Panel.__init__(self,parent,id,size,pos,style) 
     self.SetBackgroundColour("#D18B47") 
     self.Bind(wx.EVT_PAINT,self.onPaint) 

    def onPaint(self, event): 
     event.Skip() 
     dc = wx.PaintDC(event.GetEventObject()) 
     self.drawRect(dc) 

    def drawRect(self,dc): 
     dc.SetPen(wx.Pen("FFCE8A", 0)) 
     dc.SetBrush(wx.Brush("C0C0C0")) 
     dc.DrawRectangle(50,50,50,50) 

回答

3

这使得一个灰色的矩形:

import wx 

class MyPanel(wx.Panel): 
    """ class MyPanel creates a panel to draw on, inherits wx.Panel """ 
    def __init__(self, parent, id): 
     # create a panel 
     wx.Panel.__init__(self, parent, id) 
     self.SetBackgroundColour("white") 
     self.Bind(wx.EVT_PAINT, self.OnPaint) 

    def OnPaint(self, evt): 
     """set up the device context (DC) for painting""" 
     self.dc = wx.PaintDC(self) 
     self.dc.BeginDrawing() 
     self.dc.SetPen(wx.Pen("grey",style=wx.TRANSPARENT)) 
     self.dc.SetBrush(wx.Brush("grey", wx.SOLID)) 
     # set x, y, w, h for rectangle 
     self.dc.DrawRectangle(250,250,50, 50) 
     self.dc.EndDrawing() 
     del self.dc 

app = wx.PySimpleApp() 
# create a window/frame, no parent, -1 is default ID 
frame = wx.Frame(None, -1, "Drawing A Rectangle...", size = (500, 500)) 
# call the derived class, -1 is default ID 
MyPanel(frame,-1) 
# show the frame 
frame.Show(True) 
# start the event loop 
app.MainLoop() 
+6

小记:对于较小的代码,您可以执行dc.SetPen(wx.TRANSPARENT_PEN),并且不需要删除DC。实际上,最好不要将它存储为类属性。 – 2010-02-13 15:37:50

+1

“wx.DC.BeginDrawing和EndDrawing已被弃用...”自2006年10月18日以来 Barton 2013-09-09 08:33:35

+0

现在不起作用。仍然绘制一个填充矩形 – obayhan 2016-03-04 13:25:45

1

为了绘制的非填充的矩形您需要将笔刷设置为透明,因为笔刷是填充物和笔画出轮廓。下面的例子绘制了一个蓝色的非填充矩形,旁边是一个红色的填充矩形。

import wx 

class MyPanel(wx.Panel): 
    """ class MyPanel creates a panel to draw on, inherits wx.Panel """ 

    def __init__(self, parent, id): 
     wx.Panel.__init__(self, parent, id) 

     self.SetBackgroundColour("white") 
     self.Bind(wx.EVT_PAINT, self.OnPaint) 

    def OnPaint(self, event): 
     """set up the device context (DC) for painting""" 
     dc = wx.PaintDC(self) 

     #blue non-filled rectangle 
     dc.SetPen(wx.Pen("blue")) 
     dc.SetBrush(wx.Brush("blue", wx.TRANSPARENT)) #set brush transparent for non-filled rectangle 
     dc.DrawRectangle(10,10,200,200) 

     #red filled rectangle 
     dc.SetPen(wx.Pen("red")) 
     dc.SetBrush(wx.Brush("red")) 
     dc.DrawRectangle(220,10,200,200) 

app = wx.App() 
frame = wx.Frame(None, -1, "Drawing A Rectangle...", size=(460, 300)) 
MyPanel(frame,-1) 
frame.Show()   
frame.Centre() 
app.MainLoop()