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(., 1.0)
g = vtk.vtkMath.Random(., 1.0)
b = vtk.vtkMath.Random(., 1.0)
actor.GetProperty().SetColor(r, g, b)
#下面这一行是关键,实现了actor的更新
renWin.Render() #在此处修改几何类型
cube = vtk.vtkCubeSource() mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(cube.GetOutputPort()) actor = vtk.vtkActor()
actor.SetMapper(mapper)
#修改actor初始颜色
actor.GetProperty().SetColor(1.0, 1.0, 1.0)
#修改actor初始状态旋转角度
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(, ) iren.Initialize() ren.ResetCamera()
ren.GetActiveCamera().Zoom(1.5)
renWin.Render() iren.Start()