我对使用wxPython和wx.richtext.RichTextCtrl的应用程序的内存泄漏有问题。该应用程序类似于此应用程序-窗框上的简单数字时钟。为了保持代码干净,我使用另一个模块来更新“文本模块”(ModuleClock.py)。

任何人知道为什么会这样吗?

我也尝试过:


用StaticText对象(wx.StaticText)替换RTF。结果:不消耗内存。
根本没有调用ModuleClock.py。结果:不消耗内存。
编辑1:使用命令rto。Freeze(),rto。Thaw()和rto。BeginSupressUndo()
编辑2:将代码从ModuleClock.py移到Main.py(在MainWindow.update方法内部)


主程序

import wx
import wx.richtext # as rt
import ModuleClock         #
from datetime import datetime
import os
import psutil

class MainWindow(wx.Frame):
    counter = 0
    lastcall = datetime.now()

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, size=(600, 500), pos=(0, 0))

        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour('Black')

        self.clock = wx.richtext.RichTextCtrl(self.panel, wx.ID_ANY, value="", size = (600,150), style=wx.VSCROLL | wx.HSCROLL | wx.NO_BORDER)
        self.clock.SetBackgroundColour('Black')

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update, self.timer)
        self.timer.Start(100)
        self.Show()

    def update(self, event):
        now = datetime.now()
        self.counter = self.counter + 1

        ModuleClock.update(self.clock)

        # Check memory use by process every 30 seconds
        if (now - self.lastcall).seconds > 30:
            process = psutil.Process(os.getpid())
            print('memory use =', process.memory_info().rss/1000, 'kb')
            self.lastcall = now


app = wx.App(False)
frame = MainWindow(None)
app.MainLoop()


ModuleClock.py

from datetime import datetime


def update(rto):
    now = datetime.now()

    # default is black text
    rto.Clear()
    rto.BeginFontSize(16)
    rto.BeginTextColour("White")
    rto.WriteText(now.strftime("%A %d %B\n"))
    rto.BeginFontSize(36)
    rto.WriteText(now.strftime("%H:%M:%S"))


命令行输出

(venv) C:\Users\Danne\PycharmProjects\Leak>python Main.py
memory use = 31920.128 kb
memory use = 32657.408 kb
memory use = 33492.992 kb
memory use = 34144.256 kb
memory use = 34975.744 kb
memory use = 35545.088 kb
memory use = 36376.576 kb
[30 records removed]
memory use = 58028.032 kb
memory use = 58871.808 kb
memory use = 59404.288 kb
memory use = 60268.544 kb
memory use = 60801.024 kb
memory use = 61607.936 kb

最佳答案

ModuleClock中,您永远不会取消对文本颜色或字体大小的更改,即,每个Begin都有一个End
ModuleClock更改为:

from datetime import datetime


def update(rto):
    now = datetime.now()

    # default is black text
    rto.Clear()
    rto.BeginFontSize(16)
    rto.WriteText(now.strftime("%A %d %B\n"))
    rto.EndFontSize()
    rto.BeginFontSize(36)
    rto.WriteText(now.strftime("%H:%M:%S"))
    rto.EndFontSize()


并在self.clock.BeginTextColour("White")中的self.clock.SetBackgroundColour('Black')之后添加Main.py

关于python - 使用richTextCtrl和wxPython的内存泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53582098/

10-12 20:22