Я пытаюсь разработать графический интерфейс с помощью Enthought. Я немного смущен тем, как использовать Traits и возвращать значение из функции, которое будет отображаться в графическом интерфейсе. Ниже я написал простой графический интерфейс, отображающий мои проблемы.
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», объект не имеет атрибута «старт». Я посмотрел пример потоковой обработки Camera.py, построенный с использованием Traits, и построил свой код на основе этого примера. Похоже, Python не распознает мой Program_Execute_Thread как «поток». У кого-нибудь есть идеи?
Привет, Шивелс