VTK——通过回调函数监测键盘

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)
            # 下面这一行是关键,实现了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(300, 300)

iren.Initialize()

ren.ResetCamera()
ren.GetActiveCamera().Zoom(1.5)
renWin.Render()

iren.Start()

VTK——通过回调函数监测键盘_第1张图片

你可能感兴趣的:(vtk,python)