对于使用 wxPython 和 wx.richtext.RichTextCtrl 的应用程序,我遇到了内存泄漏问题。该应用程序类似于此应用程序 -窗框上的简单数字时钟。为了保持代码干净,我使用不同的模块来更新“文本模块”(ModuleClock.py)。
有谁知道它为什么会这样?
我也试过:
- 用静态文本对象 (wx.StaticText) 替换富文本。结果:不消耗内存。
- 根本没有调用 ModuleClock.py。结果:不消耗内存。
- 编辑 1:使用命令 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()
模块时钟.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