我在下面的代码中看到内存泄漏。我在不同的模块中创建和处理我的数据,但这并没有导致我所看到的数据泄漏。我相信这是因为我每次更改比例时都会调用一个新的绘图类实例,尽管我不确定如何更正这个问题。我读过this thread,但是当我尝试在代码上实现self.canvas.destroy()
方法时,我收到一个错误。我想知道什么方法可以应用到下面的代码来解决我的问题?在
代码片段:
from Tkinter import *
class Interface_On:
def Interface_Elements(self, master):
self.master=master
self.master.title( "My Canvas")
self.c=Canvas(self.master, width=1000, height=1000, bg='black')
self.c.grid(row=0, column=0)
menubar = Menu(master)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=self.Edit_New)
menubar.add_cascade(label="File", menu=filemenu)
master.config(menu=menubar)
drawing_utility_run=Drawing_Utility()
drawing_utility_run.drawer(self.c)
def Edit_New(self):
Export_Poscar = self.Export_Poscar = Toplevel(self.master)
self.Export_Poscar.title('New Ribbon...')
self.Export_Poscar.geometry('300x400')
self.scale_Label= Label(Export_Poscar, width=15, text='scale:')
self.scale_Label.grid(row=2, column=0)
self.scale_Label= Label(Export_Poscar, width=15, text='scale:')
scale_var = StringVar()
self.scale_Spin= Spinbox(Export_Poscar, from_=1, to=1000, increment=1, width=15, command=self.execute_request_immediate, textvariable=scale_var)
self.scale_Spin.grid(row=2, column=2)
def execute_request_immediate(self):
global scale
User_Set_Scale=float(self.scale_Spin.get())
scale=User_Set_Scale
drawing_utility_run=Drawing_Utility()
drawing_utility_run.drawer(self.c)
class Drawing_Utility:
def drawer(self, canvas):
self.canvas=canvas
self.canvas.delete('all')
import Generator #generates my data (imports 'scale' from above where possible)
Generator_run=Generator.Generator()
Generator_run.generator_go()
from Generator import coordinates_x_comp, coordinates_y_comp #imports necessary lists
import Processor #Imports coordinates_x_comp, coordinates_y_comp, cleans and analyses
Process_xy_Data=Processor.Data_Processor()
Process_xy_Data.Process_Data()
from Processor import p_1, p_2
for Line in xrange(len(p_1)):
self.canvas.create_line(p_1[Line],p_2[Line], fill='red', activefill='blue', width=1)
root=Tk()
run_it_canvas=Interface_On()
run_it_canvas.Interface_Elements(root)
root.mainloop()
我不确定这些东西是否能修复您所说的您所观察到的内存泄漏问题,但有几个问题我需要解决,可能会有所帮助:
1。您正在使用一个局部变量(
drawing_utility_run
)来存储您的Drawing_Utility
实例。现在还不完全清楚为什么这些实例在出口中创建方法后没有被垃圾回收,但不管怎样,似乎您希望该对象保持不变,因此您应该将引用存储在实例命名空间中,如下所示:2。当您用
self.canvas.delete('all')
删除所有画布对象时,您依赖于这样一个事实:您的Tkinter版本将字符串'all'
实现为可识别的常量,这可能是事实,但不能保证。Canvas.delete
函数将接受任何参数,无论它是否表示已识别的常量或标记/ID,而不会引发错误-例如,请尝试self.canvas.delete('blah blah blah')
。一、 你指望着self.canvas.delete('all')
删除所有对象,但我不清楚它会这么做。使用Tkinter
常量ALL
,而不是字符串'all'
。在3。除非您有很好的理由让导入的模块只存在于
Drawing_Utility
实例命名空间中,否则您应该将所有import
语句移到模块级命名空间的顶部。在4。导入语句是多余的:
^{pr2}$您不需要同时使用}。只要
import Generator
和{import Generator
然后参考Generator.coordinates_x_comp
。通过使用这两个import语句,可以双重导入Generator.coordinates_x_comp
,Processor.p_1
等相关问题 更多 >
编程相关推荐