python vtk 通过回调函数监测键盘”Up”键动作,每按一次方向上键,actor变换一种颜色
import vtk
class KeyPressInteractorStyle(vtk.vtkInteractorStyleTrackballCamera):
def __init__(self, parent=None):
self.parent = vtk.vtkRenderWindowInteractor()
if (parent is not None):
self.parent = parent
self.AddObserver("KeyPressEvent", self.keyPress)
def keyPress(self, obj, event):
key = self.parent.GetKeySym()
if key == 'Up':
r = vtk.vtkMath.Random()
g = vtk.vtkMath.Random()
b = vtk.vtkMath.Random()
actor.GetProperty().SetColor(r, g, b)
renWin.Render()
cube = vtk.vtkCubeSource()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(cube.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor(1.0, 1.0, 1.0)
actor.RotateX(30.0)
actor.RotateY(-45.0)
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.SetInteractorStyle(KeyPressInteractorStyle(parent=iren))
ren.AddActor(actor)
ren.SetBackground(0.1, 0.2, 0.3)
renWin.SetSize(300, 300)
iren.Initialize()
ren.ResetCamera()
ren.GetActiveCamera().Zoom(1.5)
renWin.Render()
iren.Start()