class BulbGUI(HasTraits): w_excit = Button('Weights Excit.') w_inhib = Button('Weights Inhib.') w_clean = Button('Weights Clean') t_stop = Float t_win = Float max_freqs = Float view = View(Item(name='w_excit'), Item(name='w_inhib'), Item(name='w_clean')) def __init__(self, mbp): self.edit_traits() self.mbp = mbp def _w_excit_fired(self): self.mbp.show_weights(True) fig.scene.render() def _w_inhib_fired(self): self.mbp.show_weights(False) fig.scene.render() def _w_clean_fired(self): self.mbp.clean_weights() fig.scene.render()
class ViewerGUI(HasTraits): scene = Instance(MlabSceneModel, ()) has_several_steps = Bool(False) viewer = Instance(Viewer) set_step = Instance(SetStep) button_reload = Button('reload') button_view = Button('print view') button_make_animation = Button('make animation') button_make_snapshots = Button('make snapshots') @on_trait_change('scene.activated') def _post_init(self, name, old, new): viewer = self.viewer viewer.render_scene(self.scene, viewer.options) viewer.reset_view() viewer.show_scalar_bars(viewer.scalar_bars) def __init__(self, fgcolor=(0.0, 0.0, 0.0), bgcolor=(1.0, 1.0, 1.0), **traits): HasTraits.__init__(self, **traits) scene = self.scene.scene scene.foreground = fgcolor scene.background = bgcolor def _button_reload_fired(self): self.viewer.reload_source.reload_source = True def _button_view_fired(self): self.scene.camera.print_traits() view = mlab.view() roll = mlab.roll() print 'view:', view print 'roll:', roll print 'as args: --view=%.2e,%.2e,%.2e,%.2e,%.2e,%.2e --roll=%.2e' \ % (view[:3] + tuple(view[3]) + (roll,)) def _button_make_animation_fired(self): view = mlab.view() roll = mlab.roll() make_animation(self.viewer.filename, view, roll, 'avi', Struct(**self.viewer.options), self.viewer) def _button_make_snapshots_fired(self): view = mlab.view() roll = mlab.roll() make_animation(self.viewer.filename, view, roll, 'png', Struct(**self.viewer.options), self.viewer)
class BulbCutGUI(HasTraits): startcut = Button('Start cut') cut = Button('Cut') uncut = Button('Clean cut') depth = Int view = View(Item(name='depth'), Item(name='startcut'), \ Item(name='cut'), Item(name='uncut')) def __init__(self): self.edit_traits() self.bulbvis = bulb self.cutplane = None self.depth = 50 xmin = bv.bulbdef.bulb_center[0] - bv.bulbdef.bulb_axis[0] / 2 xmax = bv.bulbdef.bulb_center[0] + bv.bulbdef.bulb_axis[0] / 2 ymin = bv.bulbdef.bulb_center[1] - bv.bulbdef.bulb_axis[1] / 2 ymax = bv.bulbdef.bulb_center[1] + bv.bulbdef.bulb_axis[1] / 2 zmin = bv.bulbdef.bulb_center[2] - bv.bulbdef.bulb_axis[2] / 2 zmax = bv.bulbdef.bulb_center[2] + bv.bulbdef.bulb_axis[2] / 2 self.__nihl = mlab.points3d([xmin, xmax], [ymin, ymax], [zmin, zmax], opacity=0) def _startcut_fired(self): if self.cutplane == None: dw() self.cutplane = mlab.pipeline.scalar_cut_plane(self.__nihl) up() def _cut_fired(self): if self.cutplane: dw() self.bulbvis.cut(self.cutplane.implicit_plane.normal, \ self.cutplane.implicit_plane.origin, \ self.depth) print '\n\ncutplane\n\t', \ self.cutplane.implicit_plane.normal, \ self.cutplane.implicit_plane.origin, \ self.depth, '\n' self.cutplane.remove() self.cutplane = None up() def _uncut_fired(self): dw() self.bulbvis.uncut() up()
class SpringDemo(HasTraits): ignore = Button('Ignore') view = View(VGroup( HGroup(button, spring, button, show_border=True, label='Left and right justified'), HGroup(button, button, spring, button, button, spring, button, button, show_border=True, label='Left, center and right justified'), HGroup(spring, button, button, show_border=True, label='Right justified'), HGroup(button, button, show_border=True, label='Left justified (no springs)'), ), title='Spring Demo', buttons=['OK'])
class ThreadDemo ( HasTraits ): # The button used to start a new thread running: create = Button( 'Create Thread' ) # The set of counter objects currently running: counters = List( Counter ) view = View( Item( 'create', show_label = False, width = -100 ), '_', Item( 'counters', style = 'custom', show_label = False, editor = ListEditor( use_notebook = True, dock_style = 'tab' ) ), resizable=True ) def __init__ ( self, **traits ): super( HasTraits, self ).__init__( **traits ) # Set up the notification handler for the 'Create Thread' button so # that it is run on a new thread: self.on_trait_change( self.count, 'create', dispatch = 'new' ) def count ( self ): """ This method is dispatched on a new thread each time the 'Create Thread' button is pressed. """ counter = Counter() self.counters.append( counter ) for i in range( 1000 ): counter.count += 1 sleep( 0.030 ) self.counters.remove( counter )
class PersonHandler ( Handler ): # The UIInfo object associated with the view: info = Instance( UIInfo ) # The cancel button used to revert an unintentional gender change: cancel = Button( 'Cancel' ) # The pop-up customization view: view = View( HGroup( spring, Item( 'cancel', show_label = False ), ), kind = 'popup' ) # Event handlers: def object_gender_changed ( self, info ): if info.initialized: self.info = info self._ui = self.edit_traits( parent = info.gender.control ) def _cancel_changed ( self ): object = self.info.object object.gender = [ 'Male', 'Female' ][ object.gender == 'Male' ] self._ui.dispose()
class FileDialogDemo ( HasTraits ): # The name of the selected file: file_name = File # The button used to display the file dialog: open = Button( 'Open...' ) #-- Traits View Definitions ------------------------------------------------ view = View( HGroup( Item( 'open', show_label = False ), '_', Item( 'file_name', style = 'readonly', springy = True ) ), width = 0.5 ) #-- Traits Event Handlers -------------------------------------------------- def _open_changed ( self ): """ Handles the user clicking the 'Open...' button. """ file_name = open_file( extensions = FileInfo(), id = demo_id ) if file_name != '': self.file_name = file_name
class RecorderWithUI(Recorder): """ This class represents a Recorder but with a simple user interface. """ # The code to display code = Code(editor=CodeEditor(line='current_line')) # Button to save script to file. save_script = Button('Save Script') # The current line to show, used by the editor. current_line = Int # The root object which is being recorded. root = Any ######################################## # Traits View. view = View(Group( HGroup( Item('recording', show_label=True), spring, Item('save_script', show_label=False), ), Group(Item('code', show_label=False)), ), width=600, height=360, id='enthought.scripting.recorder_with_ui', buttons=['Cancel'], resizable=True, handler=CloseHandler()) ###################################################################### # RecorderWithUI interface. ###################################################################### def on_ui_close(self): """Called from the CloseHandler when the UI is closed. This method basically stops the recording. """ from util import stop_recording from package_globals import get_recorder if get_recorder() is self: stop_recording(self.root, save=False) else: self.recording = False self.unregister(self.root) ###################################################################### # Non-public interface. ###################################################################### @on_trait_change('lines[]') def _update_code(self): self.code = self.get_code() self.current_line = len(self.lines) + 1 def _save_script_fired(self): self.ui_save()
class StopShow(HasTraits): ######################################## # Traits stop = Button('Stop interaction', desc='if the UI interaction is to be stopped') # Private traits. # Stores a reference to the UI object so it can be disposed when the # interaction is stopped. _ui = Any view = View(Group(Item('stop'), show_labels=False), buttons=[], title='Control Show') ###################################################################### # `object` interface. ###################################################################### def __init__(self, **traits): super(StopShow, self).__init__(**traits) self._ui = self.edit_traits() ###################################################################### # Non-public interface. ###################################################################### def _stop_fired(self): _gui.stop_event_loop() self._ui.dispose()
class ButtonEditorDemo ( HasTraits ): """ Defines the main ButtonEditor demo class. """ # Define a Button trait: fire_event = Button( 'Click Me' ) def _fire_event_fired ( self ): print 'Button clicked!' # ButtonEditor display: # (Note that Text and ReadOnly versions are not applicable) event_group = Group( Item( 'fire_event', style = 'simple', label = 'Simple' ), Item( '_' ), Item( 'fire_event', style = 'custom', label = 'Custom' ), Item( '_' ), Item( label = '[text style unavailable]' ), Item( '_' ), Item( label = '[read only style unavailable]' ) ) # Demo view: view = View( event_group, title = 'ButtonEditor', buttons = [ 'OK' ], resizable = True )
class Demo(HasTraits): count = Int(0) button = Button("Click Me") view = View(Item("button"), Item("count")) def _button_fired(self): self.count += 1
class Company(HasTraits): employees = List(Employee) employee = Instance(Employee) increase = Float give_raise = Button('Give raise') view = View(Item('employees', show_label=False, editor=TabularEditor(adapter=EmployeeAdapter(), selected='employee', auto_update=True)), HGroup( spring, Item('increase'), Item('give_raise', show_label=False, enabled_when='employee is not None')), title='Auto Update Tabular Editor demo', height=0.25, width=0.30, resizable=True) def _give_raise_changed(self): self.employee.salary += self.increase self.employee = None
class Flip(SingletonHasTraits): flippen = Button(desc="flip the mirror", label="flip mirror") def __init__(self, TriggerChannels): self._trigger_task = DOTask(TriggerChannels) SingletonHasTraits.__init__(self) def _flippen_changed(self): self._change_mirror() def _change_mirror(self): self._trigger_task.Write(numpy.array((1, ), dtype=numpy.uint8)) time.sleep(0.001) self._trigger_task.Write(numpy.array((0, ), dtype=numpy.uint8)) view = View(Item('flippen', show_label=False), menubar=MenuBar( Menu(Action(action='_on_close', name='Quit'), name='File')), title='Flip mirror', width=100, height=100, buttons=[], resizable=True, handler=CloseHandler)
class TextView(HasTraits): text = Str save = Button() def __init__(self, text, title): self.text = text self.trait_view().title = title traits_view = View( Item('text', style="readonly", show_label=False, editor=CodeEditor()), HGroup(Item('save'), show_labels=False), resizable=True, width=1024, height=600, ) def _save_changed(self): from window import save_dialog fn = save_dialog() if fn: try: f = open(fn, "w") f.write(self.text) f.close() except: print "unable to write file..."
class Counter(HasTraits): value = Int() add_one = Button() def _add_one_fired(self): self.value += 1 view = View('value', Item('add_one', show_label=False))
class Hotel(HasPrivateTraits): # The season of the year: season = Enum('Winter', 'Spring', 'Summer', 'Fall') # The current cost of heating fuel (in dollars/gallon): fuel_cost = Range(2.00, 10.00, 4.00) # The current minimum temparature allowed by the hotel: min_temperature = Property(depends_on='season, fuel_cost') # The guests currently staying at the hotel: guests = List # ( Instance( 'Guest' ) ) # Add a new guest to the hotel: add_guest = Button('Add Guest') # The view of the hotel: view = View(VGroup( HGroup(Item('season'), '20', Item('fuel_cost', width=300), spring, Item('add_guest', show_label=False), show_border=True, label='Hotel Information'), VGroup(Item('guests', style='custom', editor=ListEditor(use_notebook=True, deletable=True, dock_style='tab', page_name='.name')), show_labels=False, show_border=True, label='Guests')), title='The Belmont Hotel Dashboard', width=0.6, height=0.2, resizable=True) # Property implementations: @cached_property def _get_min_temperature(self): return ({ 'Winter': 32, 'Spring': 40, 'Summer': 45, 'Fall': 40 }[self.season] + min(int(60.00 / self.fuel_cost), 15)) # Event handlers: @on_trait_change('guests[]') def _guests_modified(self, removed, added): for guest in added: guest.hotel = self def _add_guest_changed(self): self.guests.append(Guest())
class Test(HasTraits): p = Instance(tvtk.VolumeProperty, ()) b = Button('Click me') view = View(Item(name='p', style='custom', resizable=True, editor=CustomEditor(gradient_editor_factory)), Item('b') )
class Controller(HasTraits): run_calculation = Button('Run calculation') data = Instance(ArraySource) view = View(Item(name='run_calculation')) def _run_calculation_changed(self, value): action = ThreadedAction(self.data) action.start()
class ILoadMiniDriver(IODriver): """ Input driver for the iLoad Mini from Loadstar. """ name = Str('iLoad Mini Driver') view = View(Item(name='serial_port', label='Serial port'), Item(name='connect', label='Connect'), Item(name='disconnect', label='Disconnect'), Item(name='tare', label='Tare'), title='iLoad Mini input driver') serial_port = Str() connect = Button() disconnect = Button() tare = Button() _sp = Any() @on_trait_change('serial_port') @on_trait_change('connect') def do_connect(self): print 'iLoad Mini Connecting' self.close() try: self._sp = serial.Serial(self.serial_port, 9600, timeout=1) self._sp.write('O0W0\r') except IOError: self._sp = None @on_trait_change('disconnect') def do_disconnect(self): print 'iLoad Mini Disconnecting' if self._sp: self._sp.close() self._sp = None def receive(self): if self._sp: return self._sp.readline() else: return None
class DLS_DataSelector(HasTraits): filenames = Instance(Filenames) bad_data = Set(Str) next_btn = Button('>') prev_btn = Button('<') good_btn = Button('Good') bad_btn = Button('Bad') correlation = Instance(ArrayData) count_rate = Instance(ArrayData) view = View( HGroup(Item('filenames', show_label=True), 'correlation', 'count_rate', HGroup(*items_from_names(BTNS, show_label=False)))) def _selected_changed(self, name): header, self.correlation.data, self.count_rate.data = open_dls(name) def _next_btn_fired(self): try: self.filenames.index += 1 except IndexError: pass def _prev_btn_fired(self): if self.filenames.index > 0: self.filenames.index -= 1 def _good_btn_fired(self): try: self.bad_data.remove(self.filenames.selected) except: pass finally: self.filenames.index += 1 def _bad_btn_fired(self): self.bad_data.add(self.filenames.selected) self.filenames.index += 1
class WebPage ( HasTraits ): # The URL to display: url = Str( 'http://code.enthought.com' ) # The page title: title = Str # The page status: status = Str # The browser navigation buttons: back = Button( '<--' ) forward = Button( '-->' ) home = Button( 'Home' ) stop = Button( 'Stop' ) refresh = Button( 'Refresh' ) search = Button( 'Search' ) # The view to display: view = View( HGroup( 'back', 'forward', 'home', 'stop', 'refresh', 'search', '_', Item( 'status', style = 'readonly' ), show_labels = False ), Item( 'url', show_label = False, editor = IEHTMLEditor( home = 'home', back = 'back', forward = 'forward', stop = 'stop', refresh = 'refresh', search = 'search', title = 'title', status = 'status' ) ) )
class FooDemo(HasTraits): """ Defines a class to run the demo. """ foo = Instance(DerivedFoo, ()) configure = Button('Configure') view = View( Label("Try configuring several times, each time changing the items " "on the 'Parents?' tab."), '_', HGroup(spring, Item('configure', show_label=False))) def _configure_changed(self): self.foo.configure_traits()
class aboutBox(HasTraits): program = Str("pytimechart: linux traces exploration and visualization") author = Str("Pierre Tardy <*****@*****.**>") version = Str(__version__) doc = Button(__doc__) traits_view = View(Item("program", show_label=False, style="readonly"), Item("author", style="readonly"), Item("version", style="readonly"), Item("doc"), width=500, title="about") def _doc_changed(self, ign): browse_doc()
class CSVGrapher(HasTraits): """ 主界面包括绘图列表,数据源,文件选择器和添加绘图按钮 """ graph_list = List(Instance(Graph)) # 绘图列表 data_source = Instance(DataSource) # 数据源 csv_file_name = File(filter=[u"*.csv"]) # 文件选择 add_graph_button = Button(u"添加绘图") # 添加绘图按钮 view = View( # 整个窗口分为上下两个部分 VGroup( # 上部分横向放置控件,因此用HGroup HGroup( # 文件选择控件 Item("csv_file_name", label=u"选择CSV文件", width=400), # 添加绘图按钮 Item("add_graph_button", show_label=False) ), # 下部分是绘图列表,采用ListEditor编辑器显示 Item("graph_list", style="custom", show_label=False, editor=ListEditor( use_notebook=True, # 是用多标签页格式显示 deletable=True, # 可以删除标签页 dock_style="tab", # 标签dock样式 page_name=".name") # 标题页的文本使用Graph对象的name属性 ) ), resizable = True, height = 0.8, width = 0.8, title = u"CSV数据绘图器" ) def _csv_file_name_changed(self): """ 打开新文件时的处理,根据文件创建一个DataSource """ self.data_source = DataSource() self.data_source.load_csv(self.csv_file_name) del self.graph_list[:] def _add_graph_button_changed(self): """ 添加绘图按钮的事件处理 """ if self.data_source != None: self.graph_list.append( Graph(data_source = self.data_source) )
class OutputVariablesViewer(HasTraits): runoutput = Instance(RunOutput) save_data = Button('') def _save_data_fired(self): filename = get_file_from_user() if filename: f = open(filename, 'w') self.runoutput.save_variables(f) f.close() view = View(Item('save_data', show_label=False), Item('object.runoutput.variable_values', editor=TabularEditor(adapter=OutputVariablesAdapter(), operations=[], editable=False), show_label=False), resizable=True)
class SceneAdderNode(AdderNode): """ Subclass for adding Scene nodes to a Mayavi Engine node. """ # String to be shown in the TreeEditor. label = Str('Add a new scene') # Button for the View. add_scene = Button('Add a new scene', image=ImageResource('add_scene.png')) # Trait view to show in the Mayavi current object panel. view = View( Group(Item('add_scene', show_label=False, style='custom'), label='Add a scene')) def _add_scene_fired(self): """ Trait handler for when the add_scene button is clicked. """ self.object.new_scene()
class Model(HasTraits): a = Code("print 'hello'") b = Button("click me") traits_view = View(HSplit( VGroup( Tabbed( Item('a'), Item('a'), Item('a')), Item('b')), VSplit( VGroup('b','b','b'), HGroup('a', show_border=True, label="traits is great")), dock="horizontal" ), resizable=True, id="my.test.program.id")
class ButtonEditorDemo(HasTraits): """ This class specifies the details of the ButtonEditor demo. """ # To demonstrate any given Trait editor, an appropriate Trait is required. fire_event = Button('Click Me') def _fire_event_fired(): message("Button clicked!") # ButtonEditor display # (Note that Text and ReadOnly versions are not applicable) event_group = Group(Item('fire_event', style='simple', label='Simple'), Item('_'), Item('fire_event', style='custom', label='Custom'), Item('_'), Item(label='[text style unavailable]'), Item('_'), Item(label='[read only style unavailable]')) # Demo view view1 = View(event_group, title='ButtonEditor', buttons=['OK'], width=250)
class KBCodeExample(HasPrivateTraits): code = Code status = Str kb = Button(label='Edit Key Bindings') view = View(Group( Item('code', style='custom', resizable=True), Item('status', style='readonly'), 'kb', orientation='vertical', show_labels=False, ), id='KBCodeExample', key_bindings=key_bindings, title='Code Editor With Key Bindings', resizable=True, handler=CodeHandler()) def _kb_fired(self, event): key_bindings.edit_traits()
class DemoApp(HasTraits): plotbutton = Button("绘图") # mayavi场景 scene = Instance(MlabSceneModel, ()) view = View( VGroup( # 设置mayavi的编辑器 Item(name='scene', editor=SceneEditor(scene_class=MayaviScene), resizable=True, height=250, width=400), 'plotbutton', show_labels=False), title="在TraitsUI中嵌入Mayavi") def _plotbutton_fired(self): self.plot() def plot(self): mlab.test_mesh()