Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close VTK window (Python)

Tags:

python

vtk

Consider the following script

import vtk

ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

an_actor = vtk....  # create an actor
ren.AddActor(an_actor)

iren.Initialize()
renWin.Render()
iren.Start()

If the script ends there, everything is alright and the created window will be closed and the resources freed up when the window is closed manually (click X) or an exit key is pressed (Q or E).

However, if there are more statements, you will notice the window is still there, which is quite understandable since we haven't called anything to give it up, just ended the interaction loop.

See for yourself by appending the following:

temp = raw_input('The window did not close, right? (press Enter)')

According to VTK/Examples/Cxx/Visualization/CloseWindow, this

iren.GetRenderWindow().Finalize()  # equivalent: renWin.Finalize()
iren.TerminateApp()

should get the job done but it doesn't.

What else do I have to do to close programatically the opened window?

like image 469
glarrain Avatar asked Mar 26 '13 14:03

glarrain


Video Answer


1 Answers

Short answer

Just one line is missing!

del renWin, iren

Long answer

You might be tempted to craft a function to deal with the window closing like this

def close_window(iren):
    render_window = iren.GetRenderWindow()
    render_window.Finalize()
    iren.TerminateApp()
    del render_window, iren

and then use it (consider the script in the question):

...
iren.Initialize()
renWin.Render()
iren.Start()

close_window(iren)

It won't work. The reason is that

del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero (__del__ documentation).

(__del__() fails (AttributeError) on iren (vtkRenderWindowInteractor) and renWin (vtkRenderWindow))

Remember that iren (and renWin too) is defined in your script thus it has a reference to the object being deleted (supposedly) in the function.

This would work (although the function wouldn't manage all the window closing stuff):

def close_window(iren):
    render_window = iren.GetRenderWindow()
    render_window.Finalize()
    iren.TerminateApp()

and then use it:

...
iren.Initialize()
renWin.Render()
iren.Start()

close_window(iren)
del renWin, iren
like image 183
glarrain Avatar answered Sep 27 '22 18:09

glarrain