Върната стойност от графичния интерфейс на Funcntion към Traits

Опитвам се да разработя GUI, използвайки Enthought. Малко съм объркан как да използвам Traits и да върна стойност от функция, която да се показва в GUI. По-долу написах прост GUI, показващ моите проблеми.

    from traits.api import HasTraits, Instance, String, Float, Enum, Button, Str, List, Bool, Int
    from traitsui.api import Handler, View, Item, Group, HSplit, NoButtons, VGroup, VGrid, HGroup, EnumEditor, Action, ProgressEditor, ButtonEditor
    from multiprocessing.pool import ThreadPool
    import simple_GUI_function

     class Input_Panel(HasTraits):

        Name = Str(name='Name', label="Name")
        Iterations = Str(name='Iterations',label="Iterations")

        #~ #Create the User Information panel
        User_Information_Panel = View(VGroup(
                                             VGrid(
                                                   Item('Name'), 
                                                   Item('Iterations'), 
                                                   ),
                                              show_border=True, label="Information"
                                            )
                                      )

        class Output_Panel(HasTraits):

             counter_out = Int(0)

             User_Output_Panel = View(VGrid(
                                             Item('counter_out', width=-10, style='readonly',resizable=False                    
                                                 ),
                                           )
                                      )



             class Program_Execute_Thread(Handler):

                  wants_abort = False

                  pool = ThreadPool(processes=1)


                 def process(self, iterations):
                      try:
                          if self.processing_job.isAlive():
                          return
                      except AttributeError:
                          pass
                      self.processing_job = Thread(target = process, args = (iterations))
                      self.processing_job.start()

                 def run(self):

                      while not self.wants_abort:

                           print("here")


                            async_result = pool.apply_async(simple_GUI_function.Gui_func.Func_test(simple_GUI_function.Gui_func(), iterations))

                            return_val = async_result.get()




              class Start_Panel(HasTraits):

                   Program_Execute = Instance(Program_Execute_Thread)


                   Start_Button = Button(name = 'Start', action='_Start_Button', tooltip = 'Start')    
                   Quit_Button = Button(name = 'Exit Program', action='_Quit_Button', tooltip = 'Quit')

                   Button_Panel = View(HGroup(
                                              Item('Start_Button', show_label = False),
                                              Item('Quit_Button', show_label = False),
                                              )
                                      )


                  def _Start_Button_fired(self):

                       if self.Program_Execute and self.Program_Execute.isAlive():
                           self.Program_Execute.wants_abort = True
                       else:
                           self.Program_Execute = Program_Execute_Thread()
                           self.Program_Execute.start()

                       print("Start Button pushed")


                 def _Quit_Button_fired(self):

                       print("Quit Button pushed")



              class MainWindowHandler(Handler):

                    def close(self, info, is_OK):


                    #~ if (info.object.button_panel.Program_Execute_Thread and \
                    #~ info.object.button_panel.Program_Execute_Thread.isAlive()):
                    #~ info.object.button_panel.Program_Execute_Thread.wants_abort = True
                    #~ while info.object.Program_Execute_Thread.isAlive():
                    #~ sleep(0.1)
                    #~ GUI.process_events()

                        return True


              class MainWindow(HasTraits):

                    user_input = Instance(Input_Panel, ())
                    user_output = Instance(Output_Panel, ())
                    button_panel = Instance(Start_Panel, ())


                    view = View(VGroup(Item('user_input', style = 'custom', show_label = False), 
                                       Item('user_output', style = 'custom', show_label = False),
                                       Item('button_panel', style = 'custom', show_label = False),
                                       show_labels = False),
                                       resizable = True, handler = MainWindowHandler(),
                                )



              if __name__ == '__main__':
                   MainWindow().configure_traits()

Ето простата функция, която кодът се опитва да извика:

    class Gui_func:


         def Func_test(self, iteration):

             import time

             print("Inside the function")

             time.sleep(2)

             print("Now leaving the function")

             p = iteration + 1

             return p

Кодът ще регистрира натискането на бутона "Старт", но продължава да генерира грешка "Program_Execute_Thread" обектът няма атрибут "start". Разгледах примера за резба на Camera.py, изграден с помощта на черти, и изградих кода си около този пример. Изглежда, че Python не разпознава моя Program_Execute_Thread като „нишка“. Някой има ли идеи?

Наздраве, Шивелс


person user3385386    schedule 19.03.2014    source източник


Отговори (1)


Реших собствения си проблем. Изглежда, че съм забравил да декларирам Program_Execute_Thread като "Program_Execute_Thread(Thread)" и също трябваше да стартирам нишката.

person user3385386    schedule 20.03.2014