【问题标题】:Need help working with self.MemoryDC in wxPython在 wxPython 中使用 self.MemoryDC 需要帮助
【发布时间】:2023-03-17 15:09:02
【问题描述】:

我正在尝试制作一个双缓冲的自定义文本小部件(为了避免闪烁)。 但是,我希望能够做一些事情。但是,我不确定应该使用的确切方法。

前两个很简单,我只是想改变背景和前景色。

所以或多或少我希望能够在 self.Draw() 中更改 self.Text 的文本颜色。

片段:

self.Text = mdc.DrawText(self.TextString, 10, 0) 

作为 self.MemoryDC 的背景(填充)颜色出售。

接下来,有谁知道我如何将 self.Text 居中?最后,self.Text创建后如何配置呢?

到目前为止的小部件:

class DynamicText (wx.Panel):
    def __init__(self, par):
        self.Par = par

        wx.Panel.__init__(self, self.Par)


        self.Time = Time(self, func=self.SetTime)



        self.Dim = self.Par.GetClientSize()
        self.SetSize(self.Dim)

        self.Bind(wx.EVT_SIZE, self.Resize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.Erase)
        self.Bind(wx.EVT_PAINT, self.Paint)

    def Set (self, text) :
        self.TextString = text

    def SetTime (self, time) :
        self.Set(str(time))
        self.Resize(None)

    def Resize(self, event):

        self.Width, self.Height = self.GetSize()

        bitmap = wx.EmptyBitmap(self.Width, self.Height)

        self.MemoryDC = wx.MemoryDC(bitmap)

        ''' Redraws **self.MemoryDC** '''
        mdc = self.MemoryDC

        ''' Deletes everything from widget. '''
        mdc.Clear()


        fs = 11
        font = wx.Font( fs, wx.DEFAULT, wx.NORMAL, wx.NORMAL)
        mdc.SetFont(font)

        self.Draw()

        self.Refresh()



    def Draw (self) :
        mdc = self.MemoryDC
        self.Text = mdc.DrawText(self.TextString, 10, 0)

    def Erase(self, event):
        ''' Does nothing, as to avoid flicker. '''
        pass

    def Paint(self, event):
        pdc = wx.PaintDC(self)
        w, h = self.MemoryDC.GetSize()
        pdc.Blit(0, 0, w, h, self.MemoryDC, 0, 0)

【问题讨论】:

    标签: python widget wxpython doublebuffered


    【解决方案1】:

    我不明白你在创建后配置 self.Text 是什么意思。如果你想在绘制后更改文本 - 你不能。一旦你把它画到 DC 上,它就在那里,而改变它的唯一方法就是清除 DC 并重新粉刷它。在您的情况下,似乎在更新文本时您需要做的就是再次调用 Resize() ,强制重绘。请注意DrawText() 不会返回任何内容,因此您的self.Text 的值将是None。您绝对不能使用 that 来引用绘制的文本。 :D

    至于其余部分,这里有一个 Draw() 方法的示例,它使文本居中并将其涂成蓝色:

    def Draw(self) :
        mdc = self.MemoryDC
        dc_width, dc_height = mdc.GetSizeTuple()
        text_width, text_height, descent, externalLeading = mdc.GetFullTextExtent(self.TextString)
        x = (dc_width  - text_width)  / 2
        y = (dc_height - text_height) / 2
        mdc.SetTextForeground('Blue')
        mdc.DrawText(self.TextString, x, y)
    

    【讨论】:

    • 是的,我的意思是能够在将文本绘制为配置后更改文本。我是 wxPython 的新手,所以我仍在尝试了解它的来龙去脉。据我了解 wx.MemoryDC() 可以像 Tkinter Canvas 小部件一样运行。您可以在该特定小部件上配置文本,而无需重新绘制它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多