在StaticText上的wxPython自定义画图事件将擦除StaticText标签

问题描述

我正在尝试使用paint事件在静态文本周围绘制边框。我认为效果很好,唯一的问题是当我绘制边框时,静态文本的标签被擦除了。有什么办法可以防止这种情况发生?我想我可以在做油漆之前先存储标签,然后再重新涂油漆???但是我需要能够在paint事件之后以编程方式访问静态文本的标签。如果我在执行绘制事件后尝试使用SetLabel,如以下代码所示,它将擦除我刚刚绘制的边框。

任何有关如何保存标签的帮助将不胜感激。谢谢。

import wx

class MyStaticText(wx.StaticText): 
        
    def __init__(self,parent): 
        
        super(MyStaticText,self).__init__(parent,id=wx.ID_ANY,label="Static Text",pos=wx.DefaultPosition,size=wx.Size(100,100))  
        
        self.if_border = True
        self.Bind(wx.EVT_PAINT,self.OnPaint) 
        
    def OnPaint(self,e): 
        
        if not self.if_border:
            return
        
        dc = wx.PaintDC(self) 
        
        # get current size of static text
        curr_size = self.GetSize()
        curr_width = curr_size[0]
        curr_height = curr_size[1]

        # NOTE: pen_width needs to be an odd number
        pen_width = 3
        pen_cushion = ( pen_width - 1 ) / 2
                
        pen = wx.Pen(wx.Colour(0,255)) 
        pen.SetWidth(pen_width)
        dc.SetPen(pen) 
        
        print("curr_width=" + str(curr_width))
        print("curr_height=" + str(curr_height))
        print("pen_width=" + str(pen_width))
        print("pen_cushion=" + str(pen_cushion))
        
        # ok so we need to draw a rectangle
        # in other words 4 lines
        # x1,y1,x2,y2
        
        # a. left side
        start_x = 0 + pen_cushion
        end_x = 0 + pen_cushion
        start_y = 0
        end_y = curr_height
        dc.DrawLine(start_x,start_y,end_x,end_y) 
        
        # b. right side
        start_x = curr_width - pen_cushion
        end_x = curr_width - pen_cushion
        start_y = 0
        end_y = curr_height
        dc.DrawLine(start_x,end_y) 
        
        # c. top side
        start_x = 0
        end_x = curr_width
        start_y = 0 + pen_cushion
        end_y = 0 + pen_cushion
        dc.DrawLine(start_x,end_y) 
        
        # c. bottom side
        start_x = 0
        end_x = curr_width
        start_y = curr_height - pen_cushion
        end_y = curr_height - pen_cushion
        dc.DrawLine(start_x,end_y) 
        

        # the label get's overwritten on paint event,have to re-insert it?
        # this completely undoes the paint event
        self.SetLabel("EHHH!")

        
        

解决方法

不要在OnPaint方法中使用self.SetLabel()。设备上下文提供了一种绘制文本的方法。

请参见wx.DC.DrawText

在OnPaint()方法末尾更改此内容:

替换为:

self.SetLabel("EHHH!")

那样:

text = 'Hello World!'
text_w,text_h = dc.GetTextExtent(text)
dc.DrawText("Hello World",curr_height / 2 - text_w / 2,curr_width / 2 - text_h / 2)