Skip to main content
 首页 » 编程设计

python之wx.Python : How can I draw some lines into wx. 静态框

2024年11月01日10birdshome

你好,我想在静态框内绘制一些彩色线条,我使用了 onpaint 方法,但线条没有出现在静态框内,然后我尝试创建一条静态线,这有效但我无法更改静态线的颜色。有没有其他方法可以使用 onpaint 方法或其他方法来显示线条,我该怎么做?

这是一个示例代码:

import wx 
 
class MainPanel(wx.Panel): 
    def __init__(self, parent): 
        wx.Panel.__init__(self, parent=parent) 
        self.frame = parent 
 
        wx.StaticBox(self, -1, 'Example', (5, 30), size=(290, 185)) 
 
        self.Bind(wx.EVT_PAINT, self.OnPaint) 
 
        #self.line = wx.StaticLine(self,-1, (25, 150), (100,1)) 
        #self.line.SetForegroundColour(("blue")) 
 
    def OnPaint(self, event): 
        dc = wx.PaintDC(self) 
        dc.DrawLine(50, 10, 80, 10) 
        dc.DrawLine(50, 140, 80, 140) 
        dc.DrawLine(50, 300, 80, 300) 
 
class MainFrame(wx.Frame):  
 
    def __init__(self): 
        wx.Frame.__init__(self, None, wx.ID_ANY, "Window",size=(305,430)) 
        panel = MainPanel(self) 
        self.CenterOnParent() 
 
if __name__ == "__main__": 
    app = wx.App(False) 
    frame = MainFrame() 
    frame.Show() 
    app.MainLoop() 

请您参考如下方法:

问题是您是在面板而不是静态框上绘画。您可以创建一个自定义静态框并执行您喜欢的操作,然后像这样调用原始的 wx.StaticBox.OnPaint:

# custom StaticBox class 
class MyStaticBox(wx.StaticBox): 
  def __init__(self, *args, **kwargs): 
    super(MyStaticBox, self).__init__(*args, **kwargs) 
    self.Bind(wx.EVT_PAINT, self.OnPaint) 
 
  def OnPaint(self, event): 
    # do what you want here 
    width, height = self.GetSize() 
    dc = wx.PaintDC(self) 
    dc.Clear() 
    dc.SetPen(wx.Pen('#4285F4')) 
    dc.DrawLine(0, 0, width, height) 
    dc.DrawLine(width, 0, 0, height) 
    # after you finished, call the StaticBox OnPaint 
    super(MyStaticBox, self).OnPaint(event) 

例如:

import wx 
 
# custom StaticBox class 
class MyStaticBox(wx.StaticBox): 
  def __init__(self, *args, **kwargs): 
    super(MyStaticBox, self).__init__(*args, **kwargs) 
    self.Bind(wx.EVT_PAINT, self.OnPaint) 
 
  def OnPaint(self, event): 
    # do what you want here 
    width, height = self.GetSize() 
    dc = wx.PaintDC(self) 
    dc.Clear() 
    dc.SetPen(wx.Pen('#4285F4')) 
    dc.DrawLine(0, 0, width, height) 
    dc.DrawLine(width, 0, 0, height) 
    # after you finished, call the StaticBox OnPaint 
    super(MyStaticBox, self).OnPaint(event) 
 
class MainPanel(wx.Panel): 
    def __init__(self, parent): 
        wx.Panel.__init__(self, parent=parent) 
        self.frame = parent 
 
        MyStaticBox(self, -1, 'Example', (5, 30), size=(290, 185)) 
 
        #self.line = wx.StaticLine(self,-1, (25, 150), (100,1)) 
        #self.line.SetForegroundColour(("blue")) 
 
class MainFrame(wx.Frame):  
 
    def __init__(self): 
        wx.Frame.__init__(self, None, wx.ID_ANY, "Window",size=(305,430)) 
        panel = MainPanel(self) 
        self.CenterOnParent() 
 
if __name__ == "__main__": 
    app = wx.App(False) 
    frame = MainFrame() 
    frame.Show() 
    app.MainLoop()