17. TraitsUI与Mayavi应用实例
作者:互联网
文章目录
建立mayavi窗口步骤
- 建立从HasTraits继承的类
- 建立MlabSceneModel场景实例scene
- 建立View视图
- 定义__init__函数,生成数据
- 建立类的实例,调用configure_traits()方法
简单的mayavi窗口
from numpy import sqrt, sin, mgrid
from traits.api import HasTraits, Instance
from traitsui.api import View, Item
from tvtk.pyface.scene_editor import SceneEditor
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core.ui.mayavi_scene import MayaviScene
class ActorViewer(HasTraits):
# 场景模型
scene = Instance(MlabSceneModel, ()) # 建立场景实例
# 建立视图
view = View(Item(name='scene', # 提供Mayavi视图窗口
editor=SceneEditor(scene_class=MayaviScene),
show_label=False,
resizable=True,
height=500,
width=500),
resizable=True)
def __init__(self, **traits):
HasTraits.__init__(self, **traits)
self.generate_data()
def generate_data(self):
# 建立数据
X, Y = mgrid[-2:2:100j, -2:2:100j]
R = 10 * sqrt(X ** 2 + Y ** 2)
Z = sin(R) / R
# 绘制数据
self.scene.mlab.surf(X, Y, Z, colormap='cool')
if __name__ == '__main__':
a = ActorViewer()
a.configure_traits()
基于交互控制的Mayavi窗口
from traits.api import HasTraits, Range, Instance, on_trait_change
from traitsui.api import View, Item, Group
from mayavi.core.api import PipelineBase
from mayavi.core.ui.api import MayaviScene, SceneEditor, MlabSceneModel
from numpy import arange, pi, cos, sin
dphi = pi / 300.
phi = arange(0.0, 2 * pi + 0.5 * dphi, dphi, 'd')
def curve(n_mer, n_long):
mu = phi * n_mer
x = cos(mu) * (1 + cos(n_long * mu / n_mer) * 0.5)
y = sin(mu) * (1 + cos(n_long * mu / n_mer) * 0.5)
z = 0.5 * sin(n_long * mu / n_mer)
t = sin(mu)
return x, y, z, t
class MyModel(HasTraits):
n_meridional = Range(0, 30, 6)
n_longitudinal = Range(0, 30, 11)
# 场景模型实例
scene = Instance(MlabSceneModel, ())
# 管线实例
plot = Instance(PipelineBase)
# 当场景被激活,或者参数发生改变,更新图形
@on_trait_change('n_meridional,n_longitudinal,scene.activated')
def update_plot(self):
x, y, z, t = curve(self.n_meridional, self.n_longitudinal)
if self.plot is None: # 如果plot未绘制则生成plot3d
self.plot = self.scene.mlab.plot3d(x, y, z, t,
tube_radius=0.025, colormap='Spectral')
else: # 如果数据有变化,将数据更新即重新赋值
self.plot.mlab_source.set(x=x, y=y, z=z, scalars=t)
# 建立视图布局
view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene),
height=250, width=300, show_label=False),
Group('_', 'n_meridional', 'n_longitudinal'),
resizable=True)
if __name__ == '__main__':
model = MyModel()
model.configure_traits()
标签:__,17,traits,self,Mayavi,scene,TraitsUI,import,mayavi 来源: https://blog.csdn.net/Exupery_/article/details/77528907