创建自截断椭圆文本ctrl:如何强制绘制偶数

2024-04-24 22:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一个静态文本,如果太长的尺寸,将截断自己与一个椭圆,只是显示文本将适合。在

当你改变窗口的大小时,我所写的似乎可以正常工作,但是当你设置标签文本时,我想一个绘制事件不会被触发。在

我尝试过调用Refresh和Update来处理所有我能处理的事情(Frame、panel、文本本身)以及将paint事件发送到Frame,但我无法使其正常工作。在

我做了一个快速演示,用一个按钮来更改文本标签。在

编辑:已解决

import wx
from wx.lib.stattext import GenStaticText as StaticText

class EllipticStaticText2(StaticText):
    def __init__(self,parent,id=wx.ID_ANY,label='',width=None,pos=wx.DefaultPosition,size=wx.DefaultSize,style=0,name="ellipticstatictext2"):
        self.actual_label= label
        self.parent= parent
        self.width= width
        StaticText.__init__(self,parent,id,label,pos,size,style,name)
        self.Bind(wx.EVT_PAINT, self.OnPaint2)

    def SetLabel(self,label):
        self.actual_label= label
        StaticText.SetLabel(self,label)
        self.parent.Layout()

    def SetLabelText(self,label):
        self.actual_label= label
        StaticText.SetLabelText(self,label)
        self.parent.Layout()

    def OnPaint2(self,event):
        dc= wx.PaintDC(self)
        displaylabel= self.actual_label
        x,y= dc.GetTextExtent(displaylabel)
        self.w,self.h= self.GetSize()
        if x>self.w:
            while x>self.w:
                displaylabel= displaylabel[:-1]
                x,y= dc.GetTextExtent(displaylabel+"...")
            StaticText.SetLabel(self,displaylabel+"...")
        else:
            StaticText.SetLabel(self,displaylabel)
        event.Skip()


class CustomFrame(wx.Frame):
    def __init__(self,parent,id,name,size):
        wx.Frame.__init__(self,parent,id,name,size)

        self.panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.index= 35

        self.elliptic = EllipticStaticText2(self.panel, -1, r"long string."*20)
        whitePanel = wx.Panel(self.panel, -1)
        whitePanel.SetBackgroundColour(wx.WHITE)

        sizer.Add(self.elliptic, 0, wx.ALL|wx.EXPAND, 10)
        btn= wx.Button(self.panel,-1,"change")
        sizer.Add(btn,0,wx.ALL|wx.EXPAND, 10)
        sizer.Add(whitePanel, 1, wx.ALL|wx.EXPAND, 10)

        btn.Bind(wx.EVT_BUTTON,self.button)

        self.panel.SetSizer(sizer)
        sizer.Layout()

    def button(self,event):
        self.elliptic.SetLabel(chr(self.index)*100)
        self.index+=1
        self.Refresh()
        self.panel.Refresh()
        self.elliptic.Refresh()

if __name__ == "__main__":
    app = wx.PySimpleApp()

    frame = CustomFrame(None, -1, "EllipticStaticText", size=(700, 300))

    frame.CenterOnScreen()
    frame.Show()

    app.MainLoop()

Tags: name文本selfsizedefframerefreshlabel