Close VTK window (Python)

心不动则不痛 提交于 2019-12-08 16:42:08

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15639762/close-vtk-window-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!