예제 #1
0
 def __init__(self, master):
     Frame.__init__(self, master)
     scrollbar = Scrollbar(self, orient=VERTICAL)
     scrollbar.pack(side=RIGHT, fill=Y)
     self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=scrollbar.set)
     self.canvas.pack(side=LEFT, fill=BOTH, expand=1)
     scrollbar.config(command=self.canvas.yview)
     
     self.mainframe = Frame(self.canvas)
     self.mainframe_id = self.canvas.create_window((0, 0), window=self.mainframe, anchor=NW)
     self.mainframe.bind('<Configure>', self.config_mainframe)
     self.canvas.bind('<Configure>', self.config_canvas)
예제 #2
0
    def __init__(self, master):
        Frame.__init__(self, master)
        scrollbar = Scrollbar(self, orient=VERTICAL)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.canvas = Canvas(self,
                             bd=0,
                             highlightthickness=0,
                             yscrollcommand=scrollbar.set)
        self.canvas.pack(side=LEFT, fill=BOTH, expand=1)
        scrollbar.config(command=self.canvas.yview)

        self.mainframe = Frame(self.canvas)
        self.mainframe_id = self.canvas.create_window((0, 0),
                                                      window=self.mainframe,
                                                      anchor=NW)
        self.mainframe.bind('<Configure>', self.config_mainframe)
        self.canvas.bind('<Configure>', self.config_canvas)
예제 #3
0
    def __init__(self,parent,caller,**args):
        Frame.__init__(self,parent,**args)
        self.pack(side=TOP)

        self.canvas = Canvas(self,scrollregion=(0,0,1000,1000)
                             ,background='white',cursor='pencil')
        self.canvas.bind("<Button-1>",lambda event:caller.clickCell(event,1))
        self.canvas.bind("<B1-Motion>",lambda event:caller.clickCell(event,1))
        self.canvas.bind("<Control-Button-1>",lambda event:caller.clickCell(event,-1))
        self.canvas.bind("<Control-B1-Motion>",lambda event:caller.clickCell(event,-1))
        vScroll = Scrollbar(self, orient = VERTICAL)
        vScroll.pack(side = RIGHT, fill=Y)
        vScroll.config(command = self.canvas.yview)
        hScroll = Scrollbar(self, orient = HORIZONTAL)
        hScroll.pack(side = BOTTOM, fill=X)
        hScroll.config(command = self.canvas.xview)
        self.canvas.config(xscrollcommand = hScroll.set, yscrollcommand = vScroll.set)
        self.canvas.pack(side=LEFT)
예제 #4
0
 def create_scrollable_text_area(self):
     """ Creates main text area with scrollbars"""
     xscrollbar = Scrollbar(self, orient=HORIZONTAL)
     xscrollbar.grid(row=2, column=1, columnspan=5, sticky=E + W)
     yscrollbar = Scrollbar(self, orient=VERTICAL)
     yscrollbar.grid(row=1, column=6, sticky=N + S)
     self.textarea = Text(self,
                          wrap=NONE,
                          bd=0,
                          xscrollcommand=xscrollbar.set,
                          yscrollcommand=yscrollbar.set)
     self.textarea.grid(row=1,
                        column=1,
                        columnspan=5,
                        rowspan=1,
                        padx=0,
                        sticky=E + W + S + N)
     xscrollbar.config(command=self.textarea.xview)
     yscrollbar.config(command=self.textarea.yview)
예제 #5
0
파일: test.py 프로젝트: hjuinj/Typer
class TypingField(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        
        self.submit_tog = True
        self.initUI()
        self.text.bind_class("Text","<Control-a>", self.selectall)
        
    def initUI(self):
        self.parent.title("Text Field")
        self.pack(fill = BOTH, expand=True)
        
        frame1 = Frame(self, width = 50, height =25)
        frame1.pack(fill = X, expand=True)
        self.scroll = Scrollbar(frame1)
        self.scroll.pack(side = "right", fill = Y)
        self.text = Text(frame1)
        self.text.pack(fill=Y)
        self.scroll.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.scroll.set)
        
        
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=True)
        self.submit = Button(frame2,text="Start Test")
        self.submit.bind("<Button-1>", self.startPause)
        self.submit.pack(fill=X)
        
    def startPause(self, event):
        self.text.focus_set()
        if self.submit_tog:
            self.submit.configure(text = "Pause")
        else:
            self.submit.configure(text = "Start Test")
        self.submit_tog = not self.submit_tog
        
    def selectall(self, event):
        event.widget.tag_add("sel","1.0","end")
예제 #6
0
    def __init__(self, master, mixer):
        Frame.__init__(self, master)

        scrollbar_h = Scrollbar(self, orient='horizontal')
        scrollbar_v = Scrollbar(self, orient='vertical')
        self.canvas = Canvas(self,
                             background='gray',
                             scrollregion=(0, 0, (3 + len(mixer) * FADER_WIDTH), FADER_HEIGHT),
                             yscrollcommand=scrollbar_v.set,
                             xscrollcommand=scrollbar_h.set)

        scrollbar_v.config(command=self.canvas.yview)
        scrollbar_h.config(command=self.canvas.xview)

        master.bind("<MouseWheel>",
                         lambda e: self.canvas.yview_scroll(-e.delta, 'units'))
        master.bind("<Shift-MouseWheel>",
                         lambda e: self.canvas.xview_scroll(-e.delta, 'units'))

        Sizegrip(self).grid(column=2, row=1, sticky='se')
        self.canvas.grid(column=0, row=0, sticky='nwes')
        scrollbar_h.grid(column=0, row=1, sticky='we')
        scrollbar_v.grid(column=1, row=0, sticky='sn')

        master_fader = AudioFader(self, mixer.getVolume, mixer.setVolume, "Master")
        master_fader.grid(column=2, row=0, sticky='nwes')

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        for i, channel in enumerate(mixer):
            if channel.device.id_variable is not None:
                name = channel.device.id_variable
            else:
                name = channel.device.name_id

            fader = AudioFader(self.canvas, channel.get_gain, channel.set_gain, name)
            self.canvas.create_window(i * FADER_WIDTH, 0, anchor='nw', window=fader)
예제 #7
0
파일: test.py 프로젝트: hjuinj/Typer
class TypingField(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        self.submit_tog = True
        self.initUI()
        self.text.bind_class("Text", "<Control-a>", self.selectall)

    def initUI(self):
        self.parent.title("Text Field")
        self.pack(fill=BOTH, expand=True)

        frame1 = Frame(self, width=50, height=25)
        frame1.pack(fill=X, expand=True)
        self.scroll = Scrollbar(frame1)
        self.scroll.pack(side="right", fill=Y)
        self.text = Text(frame1)
        self.text.pack(fill=Y)
        self.scroll.config(command=self.text.yview)
        self.text.config(yscrollcommand=self.scroll.set)

        frame2 = Frame(self)
        frame2.pack(fill=X, expand=True)
        self.submit = Button(frame2, text="Start Test")
        self.submit.bind("<Button-1>", self.startPause)
        self.submit.pack(fill=X)

    def startPause(self, event):
        self.text.focus_set()
        if self.submit_tog:
            self.submit.configure(text="Pause")
        else:
            self.submit.configure(text="Start Test")
        self.submit_tog = not self.submit_tog

    def selectall(self, event):
        event.widget.tag_add("sel", "1.0", "end")
예제 #8
0
class Edit_save(object):

    def __init__(self):
        self.root = Tk()
        self.root.title('EditSave')
        self.root.geometry('+120+50')
        self.font_en = Font(self.root, size=12)
        self.font_text = Font(self.root,family="Helvetica",
                        size=12, weight='normal')

        self.menubar = Menu(self.root, bg='purple')
        self.filemenu = Menu(self.menubar)
        self.filemenu.add_command(label='Open', accelerator='Ctrl+o',
                command=self.__open, underline=0)
        self.filemenu.add_command(label='Save', accelerator='Ctrl+s',
                command=self.__save, underline=0)
        self.filemenu.add_command(label='Save As', accelerator='Ctrl+Shift+s',
                command=self.__save_as, underline=5)
        self.filemenu.add_separator()
        self.filemenu.add_command(label='Quit', accelerator='Alt+F4',
                command=self.root.destroy, underline=0)
        self.menubar.add_cascade(label='File', underline=0, menu=self.filemenu)
        self.helpmenu = Menu(self.menubar)
        self.helpmenu.add_command(label='About', underline=0,
                                  command=About_editsave)
        self.menubar.add_cascade(label='Help', underline=0, menu=self.helpmenu)
        self.editmenu = Menu(self.menubar, tearoff=False)
        self.editmenu.add_command(label='Refresh', accelerator='F5',
                command=self.root.update)
        self.editmenu.add_command(label='Copy', accelerator='Ctrl+C',
                command=lambda : self.text.event_generate('<<Copy>>'))
        self.editmenu.add_command(label='Paste', accelerator='Ctrl+V',
                command=lambda : self.text.event_generate('<<Paste>>'))
        self.editmenu.add_command(label='Cut', accelerator='Ctrl+X',
                command=lambda : self.text.event_generate('<<Cut>>'))
#       self.editmenu.add_command(label='Undo', accelerator='Ctrl+Z',
#               command=lambda : self.text.event_generate('<<Undo>>'))
#       self.editmenu.add_command(label='Redo', accelerator='Ctrl+Y',
#               command=lambda : self.text.event_generate('<<Redo>>'))
        self.editmenu.add_command(label='select_all', accelerator='Ctrl+A',
                command=lambda : self.text.tag_add('sel', '1.0', 'end'))

        self.fm_base = Frame(self.root)
        self.fm_up = Frame(self.fm_base)
        self.var = StringVar()
        self.en = Entry(self.fm_up, font=self.font_en,
                        textvariable=self.var, width=20)
        self.bt_open = Button(self.fm_up, text='Open',)
        self.bt_quit = Button(self.fm_up, text='Quit', underline=0)
        self.bt_quit.pack(side=RIGHT, padx=10)
        self.bt_open.pack(side=RIGHT, padx=5)
        self.en.pack(side=RIGHT, pady=5)
        self.bt_open.config(command=self.__open)
        self.bt_quit.config(command=self.root.destroy)
        self.fm_up.pack(fill=X)
        self.fm_base.pack(fill=X)

        self.fm_down =  Frame(self.root)
        self.text = Text(self.fm_down, font=self.font_text,
                        width=50, height=20)
        self.text.pack(side=LEFT, fill=BOTH, expand=True)
        self.scb = Scrollbar(self.fm_down)
        self.scb.pack(side=LEFT, fill=Y)
        self.text.config(yscrollcommand=self.scb.set)
        self.scb.config(command=self.text.yview)
        self.fm_down.pack(fill=BOTH, expand=True)

        self.root.bind('<Control-o>', self.__invoke_open)
        self.root.bind('<Control-O>', self.__invoke_open)
        self.root.bind('<Control-s>', self.__invoke_save)
        self.root.bind('<Control-S>', self.__invoke_save_as)
        self.root.bind('<Button-3>', self.__popupmenu)
        self.root.bind('Alt-F4', lambda event:  self.root.destroy)
        self.root.bind('<F5>', lambda event: self.root.update)
        self.root.bind('<Control-C>',
                        lambda event: self.text.event_generate('<<Copy>>'))
        self.root.bind('<Control-V>',
                        lambda event: self.text.event_generate('<<Paste>>'))
        self.root.bind('<Control-X>',
                        lambda event: self.text.event_generate('<<Cut>>'))
        for i in 'a', 'A':
            self.root.bind('<Control-%s>' % i,
                        lambda event: self.text.tag_add('sel', '1.0', 'end'))
#       for i in 'z', 'Z':
#           self.root.bind('<Control-%s>' % i,
#                       lambda event: self.text.event_generate('<<Undo>>'))
#       for i in 'y', 'Y':
#           self.root.bind('<Control-%s>' % i,
#                       lambda event: self.text.event_generate('<<Redo>>'))

        self.root.config(menu=self.menubar)
        self.root.mainloop()

    def __open(self):
        filetypes = [
                ("All Files", '*'),
                ("Python Files", '*.py', 'TEXT'),
                ("Text Files", '*.txt', 'TEXT'),
                ("Config Files", '*.conf', 'TEXT')]
        fobj = askopenfile(filetypes=filetypes)
        if fobj:
            self.text.delete('1.0', END)
            self.text.insert('1.0', fobj.read())
            self.en.delete(0, END)
            self.en.insert(0, fobj.name)

    def __save(self):
        value = self.var.get().strip()
        if value:
            f = open(value, 'w')
            f.write(self.text.get('1.0', END).strip() + '\n')
            f.close()
        else:
            self.__save_as()

    def __save_as(self):
        text_value = self.text.get('1.0', END).strip()
        if text_value:
            fobj = asksaveasfile()
            if fobj:
                fobj.write(text_value + '\n')

    def __invoke_open(self, event):
        self.__open()

    def __invoke_save(self, event):
        self.__save()

    def __invoke_save_as(self, event):
        self.__save_as()

    def __popupmenu(self, event):
        self.editmenu.post(event.x_root, event.y_root)
예제 #9
0
파일: view.py 프로젝트: oguntli/bugjar
class MainWindow(object):
    def __init__(self, root, debugger):
        '''
        -----------------------------------------------------
        | main button toolbar                               |
        -----------------------------------------------------
        |       < ma | in content area >      |             |
        |            |                        |             |
        | File list  | File name              | Inspector   |
        | (stack/    | Code area              |             |
        | breakpnts) |                        |             |
        |            |                        |             |
        |            |                        |             |
        -----------------------------------------------------
        |     status bar area                               |
        -----------------------------------------------------

        '''

        # Obtain and expand the current working directory.
        base_path = os.path.abspath(os.getcwd())
        base_path = os.path.normcase(base_path) + '/'

        # Create a filename normalizer based on the CWD.
        self.filename_normalizer = filename_normalizer(base_path)

        self.debugger = debugger
        # Associate the debugger with this view.
        self.debugger.view = self

        # Root window
        self.root = root
        self.root.title('Bugjar')
        self.root.geometry('1024x768')

        # Prevent the menus from having the empty tearoff entry
        self.root.option_add('*tearOff', False)
        # Catch the close button
        self.root.protocol("WM_DELETE_WINDOW", self.cmd_quit)
        # Catch the "quit" event.
        self.root.createcommand('exit', self.cmd_quit)

        # Setup the menu
        self._setup_menubar()

        # Set up the main content for the window.
        self._setup_button_toolbar()
        self._setup_main_content()
        self._setup_status_bar()

        # Now configure the weights for the root frame
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=0)
        self.root.rowconfigure(1, weight=1)
        self.root.rowconfigure(2, weight=0)

        debugger.start()

    ######################################################
    # Internal GUI layout methods.
    ######################################################

    def _setup_menubar(self):
        # Menubar
        self.menubar = Menu(self.root)

        # self.menu_Apple = Menu(self.menubar, name='Apple')
        # self.menubar.add_cascade(menu=self.menu_Apple)

        self.menu_file = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_file, label='File')

        self.menu_program = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_program, label='Program')

        self.menu_help = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_help, label='Help')

        # self.menu_Apple.add_command(label='Test', command=self.cmd_dummy)

        # self.menu_file.add_command(label='New', command=self.cmd_dummy, accelerator="Command-N")
        self.menu_file.add_command(label='Open...',
                                   command=self.cmd_open_file,
                                   accelerator="Command-O")
        self.root.bind('<Command-o>', self.cmd_open_file)
        # self.menu_file.add_command(label='Close', command=self.cmd_dummy)

        self.menu_program.add_command(label='Run',
                                      command=self.cmd_run,
                                      accelerator="R")
        self.root.bind('<r>', self.cmd_run)
        self.menu_program.add_command(label='Step',
                                      command=self.cmd_step,
                                      accelerator="S")
        self.root.bind('<s>', self.cmd_step)
        self.menu_program.add_command(label='Next',
                                      command=self.cmd_next,
                                      accelerator="N")
        self.root.bind('<n>', self.cmd_next)
        self.menu_program.add_command(label='Return',
                                      command=self.cmd_return,
                                      accelerator="BackSpace")
        self.root.bind('<BackSpace>', self.cmd_return)

        self.menu_help.add_command(label='Open Documentation',
                                   command=self.cmd_bugjar_docs)
        self.menu_help.add_command(label='Open Bugjar project page',
                                   command=self.cmd_bugjar_page)
        self.menu_help.add_command(label='Open Bugjar on GitHub',
                                   command=self.cmd_bugjar_github)
        self.menu_help.add_command(label='Open BeeWare project page',
                                   command=self.cmd_beeware_page)

        # last step - configure the menubar
        self.root['menu'] = self.menubar

    def _setup_button_toolbar(self):
        '''
        The button toolbar runs as a horizontal area at the top of the GUI.
        It is a persistent GUI component
        '''

        # Main toolbar
        self.toolbar = Frame(self.root)
        self.toolbar.grid(column=0, row=0, sticky=(W, E))

        # Buttons on the toolbar
        self.run_button = Button(self.toolbar,
                                 text='Run',
                                 command=self.cmd_run)
        self.run_button.grid(column=0, row=0)

        self.step_button = Button(self.toolbar,
                                  text='Step',
                                  command=self.cmd_step)
        self.step_button.grid(column=1, row=0)

        self.next_button = Button(self.toolbar,
                                  text='Next',
                                  command=self.cmd_next)
        self.next_button.grid(column=2, row=0)

        self.return_button = Button(self.toolbar,
                                    text='Return',
                                    command=self.cmd_return)
        self.return_button.grid(column=3, row=0)

        self.toolbar.columnconfigure(0, weight=0)
        self.toolbar.rowconfigure(0, weight=0)

    def _setup_main_content(self):
        '''
        Sets up the main content area. It is a persistent GUI component
        '''

        # Main content area
        self.content = PanedWindow(self.root, orient=HORIZONTAL)
        self.content.grid(column=0, row=1, sticky=(N, S, E, W))

        # Create subregions of the content
        self._setup_file_lists()
        self._setup_code_area()
        self._setup_inspector()

        # Set up weights for the left frame's content
        self.content.columnconfigure(0, weight=1)
        self.content.rowconfigure(0, weight=1)

        self.content.pane(0, weight=1)
        self.content.pane(1, weight=2)
        self.content.pane(2, weight=1)

    def _setup_file_lists(self):

        self.file_notebook = Notebook(self.content, padding=(0, 5, 0, 5))
        self.content.add(self.file_notebook)

        self._setup_stack_frame_list()
        self._setup_breakpoint_list()

    def _setup_stack_frame_list(self):
        self.stack_frame = Frame(self.content)
        self.stack_frame.grid(column=0, row=0, sticky=(N, S, E, W))
        self.file_notebook.add(self.stack_frame, text='Stack')

        self.stack = StackView(self.stack_frame,
                               normalizer=self.filename_normalizer)
        self.stack.grid(column=0, row=0, sticky=(N, S, E, W))

        # # The tree's vertical scrollbar
        self.stack_scrollbar = Scrollbar(self.stack_frame, orient=VERTICAL)
        self.stack_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # # Tie the scrollbar to the text views, and the text views
        # # to each other.
        self.stack.config(yscrollcommand=self.stack_scrollbar.set)
        self.stack_scrollbar.config(command=self.stack.yview)

        # Setup weights for the "stack" tree
        self.stack_frame.columnconfigure(0, weight=1)
        self.stack_frame.columnconfigure(1, weight=0)
        self.stack_frame.rowconfigure(0, weight=1)

        # Handlers for GUI events
        self.stack.bind('<<TreeviewSelect>>', self.on_stack_frame_selected)

    def _setup_breakpoint_list(self):
        self.breakpoints_frame = Frame(self.content)
        self.breakpoints_frame.grid(column=0, row=0, sticky=(N, S, E, W))
        self.file_notebook.add(self.breakpoints_frame, text='Breakpoints')

        self.breakpoints = BreakpointView(self.breakpoints_frame,
                                          normalizer=self.filename_normalizer)
        self.breakpoints.grid(column=0, row=0, sticky=(N, S, E, W))

        # The tree's vertical scrollbar
        self.breakpoints_scrollbar = Scrollbar(self.breakpoints_frame,
                                               orient=VERTICAL)
        self.breakpoints_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # Tie the scrollbar to the text views, and the text views
        # to each other.
        self.breakpoints.config(yscrollcommand=self.breakpoints_scrollbar.set)
        self.breakpoints_scrollbar.config(command=self.breakpoints.yview)

        # Setup weights for the "breakpoint list" tree
        self.breakpoints_frame.columnconfigure(0, weight=1)
        self.breakpoints_frame.columnconfigure(1, weight=0)
        self.breakpoints_frame.rowconfigure(0, weight=1)

        # Handlers for GUI events
        self.breakpoints.tag_bind('breakpoint', '<Double-Button-1>',
                                  self.on_breakpoint_double_clicked)
        self.breakpoints.tag_bind('breakpoint', '<<TreeviewSelect>>',
                                  self.on_breakpoint_selected)
        self.breakpoints.tag_bind('file', '<<TreeviewSelect>>',
                                  self.on_breakpoint_file_selected)

    def _setup_code_area(self):
        self.code_frame = Frame(self.content)
        self.code_frame.grid(column=1, row=0, sticky=(N, S, E, W))

        # Label for current file
        self.current_file = StringVar()
        self.current_file_label = Label(self.code_frame,
                                        textvariable=self.current_file)
        self.current_file_label.grid(column=0, row=0, sticky=(W, E))

        # Code display area
        self.code = DebuggerCode(self.code_frame, debugger=self.debugger)
        self.code.grid(column=0, row=1, sticky=(N, S, E, W))

        # Set up weights for the code frame's content
        self.code_frame.columnconfigure(0, weight=1)
        self.code_frame.rowconfigure(0, weight=0)
        self.code_frame.rowconfigure(1, weight=1)

        self.content.add(self.code_frame)

    def _setup_inspector(self):
        self.inspector_frame = Frame(self.content)
        self.inspector_frame.grid(column=2, row=0, sticky=(N, S, E, W))

        self.inspector = InspectorView(self.inspector_frame)
        self.inspector.grid(column=0, row=0, sticky=(N, S, E, W))

        # The tree's vertical scrollbar
        self.inspector_scrollbar = Scrollbar(self.inspector_frame,
                                             orient=VERTICAL)
        self.inspector_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # Tie the scrollbar to the text views, and the text views
        # to each other.
        self.inspector.config(yscrollcommand=self.inspector_scrollbar.set)
        self.inspector_scrollbar.config(command=self.inspector.yview)

        # Setup weights for the "breakpoint list" tree
        self.inspector_frame.columnconfigure(0, weight=1)
        self.inspector_frame.columnconfigure(1, weight=0)
        self.inspector_frame.rowconfigure(0, weight=1)

        self.content.add(self.inspector_frame)

    def _setup_status_bar(self):
        # Status bar
        self.statusbar = Frame(self.root)
        self.statusbar.grid(column=0, row=2, sticky=(W, E))

        # Current status
        self.run_status = StringVar()
        self.run_status_label = Label(self.statusbar,
                                      textvariable=self.run_status)
        self.run_status_label.grid(column=0, row=0, sticky=(W, E))
        self.run_status.set('Not running')

        # Main window resize handle
        self.grip = Sizegrip(self.statusbar)
        self.grip.grid(column=1, row=0, sticky=(S, E))

        # Set up weights for status bar frame
        self.statusbar.columnconfigure(0, weight=1)
        self.statusbar.columnconfigure(1, weight=0)
        self.statusbar.rowconfigure(0, weight=0)

    ######################################################
    # Utility methods for controlling content
    ######################################################

    def show_file(self, filename, line=None, breakpoints=None):
        """Show the content of the nominated file.

        If specified, line is the current line number to highlight. If the
        line isn't currently visible, the window will be scrolled until it is.

        breakpoints is a list of line numbers that have current breakpoints.

        If refresh is true, the file will be reloaded and redrawn.
        """
        # Set the filename label for the current file
        self.current_file.set(self.filename_normalizer(filename))

        # Update the code view; this means changing the displayed file
        # if necessary, and updating the current line.
        if filename != self.code.filename:
            self.code.filename = filename
            for bp in self.debugger.breakpoints(filename).values():
                if bp.enabled:
                    self.code.enable_breakpoint(bp.line)
                else:
                    self.code.disable_breakpoint(bp.line)

        self.code.line = line

    ######################################################
    # TK Main loop
    ######################################################

    def mainloop(self):
        self.root.mainloop()

    ######################################################
    # TK Command handlers
    ######################################################

    def cmd_quit(self):
        "Quit the debugger"
        self.debugger.stop()
        self.root.quit()

    def cmd_run(self, event=None):
        "Run until the next breakpoint, or end of execution"
        self.debugger.do_run()

    def cmd_step(self, event=None):
        "Step into the next line of code"
        self.debugger.do_step()

    def cmd_next(self, event=None):
        "Run the next line of code in the current frame"
        self.debugger.do_next()

    def cmd_return(self, event=None):
        "Return to the previous frame"
        self.debugger.do_return()

    def cmd_open_file(self, event=None):
        "Open a file in the breakpoint pane"
        filename = tkFileDialog.askopenfilename(
            initialdir=os.path.abspath(os.getcwd()))

        if filename:
            # Convert to canonical form
            filename = os.path.abspath(filename)
            filename = os.path.normcase(filename)

            # Show the file contents
            self.code.filename = filename

            # Ensure the file appears on the breakpoint list
            self.breakpoints.insert_filename(filename)

            # Show the breakpoint panel
            self.file_notebook.select(self.breakpoints_frame)

            # ... select the new filename
            self.breakpoints.selection_set(filename)

            # .. and clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def cmd_bugjar_page(self):
        "Show the Bugjar project page"
        webbrowser.open_new('http://pybee.org/bugjar')

    def cmd_bugjar_github(self):
        "Show the Bugjar GitHub repo"
        webbrowser.open_new('http://github.com/pybee/bugjar')

    def cmd_bugjar_docs(self):
        "Show the Bugjar documentation"
        # If this is a formal release, show the docs for that
        # version. otherwise, just show the head docs.
        if len(NUM_VERSION) == 3:
            webbrowser.open_new('http://bugjar.readthedocs.org/en/v%s/' %
                                VERSION)
        else:
            webbrowser.open_new('http://bugjar.readthedocs.org/')

    def cmd_beeware_page(self):
        "Show the BeeWare project page"
        webbrowser.open_new('http://pybee.org/')

    ######################################################
    # Handlers for GUI actions
    ######################################################

    def on_stack_frame_selected(self, event):
        "When a stack frame is selected, highlight the file and line"
        if event.widget.selection():
            _, index = event.widget.selection()[0].split(':')
            line, frame = self.debugger.stack[int(index)]

            # Display the file in the code view
            self.show_file(filename=frame['filename'], line=line)

            # Display the contents of the selected frame in the inspector
            self.inspector.show_frame(frame)

            # Clear any currently selected item on the breakpoint tree
            self.breakpoints.selection_remove(self.breakpoints.selection())

    def on_breakpoint_selected(self, event):
        "When a breakpoint on the tree has been selected, show the breakpoint"
        if event.widget.selection():
            parts = event.widget.focus().split(':')
            bp = self.debugger.breakpoint((parts[0], int(parts[1])))
            self.show_file(filename=bp.filename, line=bp.line)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def on_breakpoint_file_selected(self, event):
        "When a file is selected on the breakpoint tree, show the file"
        if event.widget.selection():
            filename = event.widget.focus()
            self.show_file(filename=filename)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def on_breakpoint_double_clicked(self, event):
        "When a breakpoint on the tree is double clicked, toggle it's status"
        if event.widget.selection():
            parts = event.widget.focus().split(':')
            bp = self.debugger.breakpoint((parts[0], int(parts[1])))
            if bp.enabled:
                self.debugger.disable_breakpoint(bp)
            else:
                self.debugger.enable_breakpoint(bp)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    ######################################################
    # Handlers for debugger responses
    ######################################################

    def on_stack(self, stack):
        "A report of a new stack"
        # Make sure the stack frame list is displayed
        self.file_notebook.select(self.stack_frame)

        # Update the stack list
        self.stack.update_stack(stack)

        if len(stack) > 0:
            # Update the display of the current file
            line = stack[-1][0]
            filename = stack[-1][1]['filename']
            self.show_file(filename=filename, line=line)

            # Select the current stack frame in the frame list
            self.stack.selection_set('frame:%s' % (len(stack) - 1))
        else:
            # No current frame (probably end of execution),
            # so clear the current line marker
            self.code.line = None

    def on_line(self, filename, line):
        "A single line of code has been executed"
        self.run_status.set('Line (%s:%s)' % (filename, line))

    def on_call(self, args):
        "A callable has been invoked"
        self.run_status.set('Call: %s' % args)

    def on_return(self, retval):
        "A callable has returned"
        self.run_status.set('Return: %s' % retval)

    def on_exception(self, name, value):
        "An exception has been raised"
        self.run_status.set('Exception: %s - %s' % (name, value))
        tkMessageBox.showwarning(message='%s: %s' % (name, value))

    def on_postmortem(self):
        "An exception has been raised"
        self.run_status.set('Post mortem mode')
        tkMessageBox.showerror(
            message='Entering post mortem mode. Step/Next will restart')

    def on_restart(self):
        "The code has finished running, and will start again"
        self.run_status.set('Not running')
        tkMessageBox.showinfo(
            message='Program has finished, and will restart.')

    def on_info(self, message):
        "The debugger needs to inform the user of something"
        tkMessageBox.showinfo(message=message)

    def on_warning(self, message):
        "The debugger needs to warn the user of something"
        tkMessageBox.showwarning(message=message)

    def on_error(self, message):
        "The debugger needs to report an error"
        tkMessageBox.showerror(message=message)

    def on_breakpoint_enable(self, bp):
        "A breakpoint has been enabled in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.enable_breakpoint(bp.line, temporary=bp.temporary)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_disable(self, bp):
        "A breakpoint has been disabled in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.disable_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_ignore(self, bp, count):
        "A breakpoint has been ignored by the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.ignore_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_clear(self, bp):
        "A breakpoint has been cleared in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.clear_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)
예제 #10
0
파일: updater.py 프로젝트: Bakterija/iSPTC
## Tkinter below
root = Tk()
root.title("Updater ver: "+str(v))
root.minsize(280,300)

frame = Frame(root, height=210,width=600, relief=SUNKEN)
frame.pack_propagate(0)
frame.pack(anchor=NE,side=TOP,padx=20,pady=20)

S = Scrollbar(frame)
T = Text(frame, height=46, width=80,wrap=WORD)
        
S.pack(side=RIGHT, fill=Y)
T.pack(side=BOTTOM,fill=BOTH,expand=1)
S.config(command=T.yview)
T.tag_configure('redcol', foreground='red')
T.tag_configure('blackcol', foreground='black')
T.tag_configure('greencol', background='#c8d9ea',foreground='#009900')
T.tag_configure('failed', background='#c8d9ea',foreground='red')

button = Button(root, text='Reopen client', command=lambda: {restart_client(),root.destroy()})
button.place(x=180,y=250)
button2 = Button(root, text='Close', command=lambda: {root.destroy()})
button2.place(x=360,y=250)

## Create download link list 
tlist = []
tfile = readf('load/upd_filelist')

def worker_thread():
예제 #11
0
class GuiFrame():
  
    ## The constructor
    #
    #  @param  self          [in]   Object reference
    #  @param  parent        [in]   Root object reference
    #  @param  rulesFile     [in]   Rules file name
    #  @param  outDir        [in]   Location of output directory
    #  @return None
    def __init__(self, parent, rulesFile, outDir):
        self.exit = False
        self.parent = parent
        self.rulesFile = rulesFile
        self.outDir = outDir
        self.bgndFrm = None
        self.scrollbar = None
        self.log = None
        
        # Create the outdir if it doesn't exist
        if not os.path.exists(outDir):
            os.makedirs(outDir)
        
        self.initUI()
        self.parseRules = ParseRules(self)
        self.parseRules.verifyParameters()            
    
    ## Close button press
    #
    #  Called when the close button is pressed.  
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def closeBtnPress(self):
        self.exit = True
        
    ## Init UI
    #
    #  Initialize the user interface.  Create the cmd panel at the
    #  top which contains the status and column headings.  Walk
    #  through the cardType array and create a panel for each card.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def initUI(self):
        self.parent.wm_title("Generate Python Code GUI")
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(0, weight=1)
        self.bgndFrm = Frame(self.parent)
        self.bgndFrm.grid()
        
        self.cmdPanel()
        self.consolePanel()
        
    ## Create command panel
    #
    #  Create the command panel.  It contains the close button.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def cmdPanel(self):
        tmpFrm = Frame(self.bgndFrm, borderwidth = 5, relief=RAISED)
        tmpFrm.grid()
        tmpFrm.grid(column = 0, row = 0)
        tmpBtn = Button(tmpFrm, width = 12, text="Close", command=self.closeBtnPress)
        tmpBtn.grid(column = 0, row = 0, padx=4, pady=8)
        
    ## Create console panel
    #
    #  Create the console panel.  It the console text box.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def consolePanel(self):
        tmpFrm = Frame(self.bgndFrm, borderwidth = 5, relief=RAISED)
        tmpFrm.grid()
        tmpFrm.grid(column = 0, row = 1)
        self.scrollbar = Scrollbar(tmpFrm)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.log = Text(tmpFrm, wrap=WORD, yscrollcommand=self.scrollbar.set)
        self.log.pack()
        self.scrollbar.config(command=self.log.yview)
        
    ## Update console
    #
    #  Update the console window with new text
    #
    #  @param  self          [in]   Object reference
    #  @param  text          [in]   Text to be added to the console window
    #  @return None
    def updateConsole(self, text):
        self.log['state'] = 'normal'
        self.log.insert('end', text + "\n")
        self.log['state'] = 'disabled'
        self.log.see(END)
        
    ## GUI exit
    #
    #  Set the exit flag.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def gui_exit(self):
        self.exit = True
예제 #12
0
class Scrolling_Area(Frame, object):

    def __init__(self, master, width=None, height=None, mousewheel_speed = 2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, outer_background=None, inner_frame=Frame, **kw):
        super(Scrolling_Area, self).__init__(master, **kw)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self._clipper = Frame(self, background=outer_background, width=width, height=height)
        self._clipper.grid(row=0, column=0, sticky=N+E+W+S)
        
        self._width = width
        self._height = height

        self.innerframe = inner_frame(self._clipper, padx=0, pady=0, highlightthickness=0)
        self.innerframe.place(in_=self._clipper, x=0, y=0)

        if scroll_vertically:
            if yscrollbar is not None:
                self.yscrollbar = yscrollbar
            else:
                self.yscrollbar = Scrollbar(self, orient=VERTICAL)
                self.yscrollbar.grid(row=0, column=1,sticky=N+S)
                
            self.yscrollbar.set(0.0, 1.0)
            self.yscrollbar.config(command=self.yview)
        else:
            self.yscrollbar = None
            
        self._scroll_vertically = scroll_vertically

        if scroll_horizontally:
            if xscrollbar is not None:
                self.xscrollbar = xscrollbar
            else:
                self.xscrollbar = Scrollbar(self, orient=HORIZONTAL)
                self.xscrollbar.grid(row=1, column=0, sticky=E+W)
            
            self.xscrollbar.set(0.0, 1.0)
            self.xscrollbar.config(command=self.xview)
        else:
            self.xscrollbar = None
            
        self._scroll_horizontally = scroll_horizontally

        self._jfraction=0.05
        self._startX = 0
        self._startY = 0       

        # Whenever the clipping window or scrolled frame change size,
        # update the scrollbars.
        self.innerframe.bind('<Configure>', self._on_configure)
        self._clipper.bind('<Configure>',  self._on_configure)
        
        self.innerframe.xview = self.xview
        self.innerframe.yview = self.yview

        Mousewheel_Support(self).add_support_to(self.innerframe, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar)

    def update_viewport(self):
        # compute new height and width
        self.update()
        frameHeight = float(self.innerframe.winfo_reqheight())
        frameWidth = float(self.innerframe.winfo_reqwidth())
        
        if self._width is not None:
            width = min(self._width, frameWidth)
        else:
            width = self._frameWidth

        if self._height is not None:
            height = min(self._height, frameHeight)
        else:
            height = self._frameHeight
        
        self._clipper.configure(width=width, height=height)

    def _on_configure(self, event):
        self._frameHeight = float(self.innerframe.winfo_reqheight())
        self._frameWidth = float(self.innerframe.winfo_reqwidth())

        # resize the visible part
        if self._scroll_horizontally:
            self.xview("scroll", 0, "unit")
            
        if self._scroll_vertically:
            self.yview("scroll", 0, "unit")       

    def xview(self, mode = None, value = None, units = None):
        value = float(value)

        clipperWidth = self._clipper.winfo_width()
        frameWidth = self._frameWidth 
        
        _startX = self._startX

        if mode is None:
            return self.xscrollbar.get()
        elif mode == 'moveto':
            # absolute movement
            self._startX = int(value * frameWidth)
        else: 
            # mode == 'scroll'
            # relative movement
            if units == 'units':
                jump = int(clipperWidth * self._jfraction)
            else:
                jump = clipperWidth
            self._startX = self._startX + value * jump

        if frameWidth <= clipperWidth:
            # The scrolled frame is smaller than the clipping window.

            self._startX = 0
            hi = 1.0
            #use expand by default
            relwidth = 1
        else:
            # The scrolled frame is larger than the clipping window.
            #use expand by default
            if self._startX + clipperWidth > frameWidth:
                self._startX = frameWidth - clipperWidth
                hi = 1.0
            else:
                if self._startX < 0:
                    self._startX = 0
                hi = (self._startX + clipperWidth) / frameWidth
            relwidth = ''

        if self._startX != _startX:
            # Position frame relative to clipper.
            self.innerframe.place(x = -self._startX, relwidth = relwidth)
        
        lo = self._startX / frameWidth
        self.xscrollbar.set(lo, hi)

    def yview(self, mode = None, value = None, units = None):
        value = float(value)
        clipperHeight = self._clipper.winfo_height()
        frameHeight = self._frameHeight
        
        _startY = self._startY

        if mode is None:
            return self.yscrollbar.get()
        elif mode == 'moveto':
            self._startY = value * frameHeight
        else: # mode == 'scroll'
            if units == 'units':
                jump = int(clipperHeight * self._jfraction)
            else:
                jump = clipperHeight
            self._startY = self._startY + value * jump

        if frameHeight <= clipperHeight:
            # The scrolled frame is smaller than the clipping window.

            self._startY = 0
            hi = 1.0
            # use expand by default
            relheight = 1
        else:
            # The scrolled frame is larger than the clipping window.
            # use expand by default 
            if self._startY + clipperHeight > frameHeight:
                self._startY = frameHeight - clipperHeight
                hi = 1.0
            else:
                if self._startY < 0:
                    self._startY = 0
                hi = (self._startY + clipperHeight) / frameHeight
            relheight = ''

        if self._startY != _startY:
            # Position frame relative to clipper.
            self.innerframe.place(y = -self._startY, relheight = relheight)

        lo = self._startY / frameHeight
        self.yscrollbar.set(lo, hi)
예제 #13
0
    class Monitor(Frame):
        def __init__(self, parent, port, baud_rate, ser, toolchain, bii):
            '''
            Params:
                parent: The parent Frame
                port: string
                baud_rate:
                ser: serial
            '''

            Frame.__init__(self, parent)
            self.parent = parent
            self.port = port
            self.baud_rate = baud_rate
            self.ser = ser
            self.toolchain = toolchain
            self.bii = bii
            self.initUI()

        def initUI(self):
            self.parent.title("Biicode serial monitor %s" % self.port)
            self.style = Style(
            )  # We need to define a style, otherwhise seems flat whit in macos
            self.style.theme_use(get_style())
            for x in range(1):
                Grid.columnconfigure(self, x, weight=1)
            for y in [1, 2]:
                Grid.rowconfigure(self, y, weight=1)

            self._make_top_bar()
            self._make_user_input()
            self._make_rcv_log()
            self._make_button_bar()

            self.pack(fill=BOTH, expand=1)

            self.serial_buffer = ""
            self.count = 0
            self.running = True
            self.after(50, self.read_serial)  # check serial again soon

        def _make_top_bar(self):
            menubar = Menu(self.parent)
            filemenu = Menu(menubar, tearoff=0)
            biimenu = Menu(menubar, tearoff=0)
            editmenu = Menu(menubar, tearoff=0)

            biimenu.add_command(label="Work (Save and process)",
                                command=self.bii.work)
            biimenu.add_command(label="Find", command=self.bii.find)
            menubar.add_cascade(label="bii", menu=biimenu)

            filemenu.add_command(label="Flash code", command=self.upload)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.parent.quit)
            menubar.add_cascade(label="File", menu=filemenu)

            editmenu.add_command(label="Clear", command=self.clear)
            # editmenu.add_separator()
            menubar.add_cascade(label="Edit", menu=editmenu)
            self.parent.config(menu=menubar)

        def _make_button_bar(self):
            self.button_upload = Button(self,
                                        text="Flash code",
                                        command=self.upload)
            self.button_upload.style = self.style
            self.button_upload.grid(row=0, column=0, padx=2, pady=2)

            self.baud_rate = 9600
            self.button_combobox = Combobox(self)
            self.button_combobox.bind("<<ComboboxSelected>>",
                                      self._update_baud_rate)
            bauds = (300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400,
                     57600, 115200)
            self.button_combobox['values'] = bauds
            self.button_combobox.current(4)
            self.button_combobox.grid(row=3, column=1, padx=2, pady=2)

        def _make_user_input(self):
            # make user input
            self.user_input = Text(self,
                                   width=52,
                                   height=3,
                                   takefocus=1,
                                   borderwidth=1,
                                   relief='ridge')
            self.user_input.grid(row=1,
                                 column=0,
                                 padx=2,
                                 pady=2,
                                 sticky=N + S + E + W)

            # make send button
            self.button_send = Button(self,
                                      text="Send",
                                      command=self.send_clicked)
            self.button_send.style = self.style
            self.button_send.grid(row=1,
                                  column=1,
                                  padx=2,
                                  pady=2,
                                  sticky=N + S + E + W)

        def _make_rcv_log(self):
            # make receive log
            recvLogFrame = Frame(self, width=400, height=200)
            recvLogFrame.style = self.style
            recvLogFrame.grid(row=2,
                              column=0,
                              padx=2,
                              pady=2,
                              sticky=N + S + E + W)
            self.start_stop_button = Button(self,
                                            text="Stop",
                                            command=self.start_stop_clicked)
            self.start_stop_button.style = self.style
            self.start_stop_button.grid(row=2,
                                        column=1,
                                        padx=2,
                                        pady=2,
                                        sticky=N + S + E + W)

            # make a scrollbar
            self.scrollbar = Scrollbar(recvLogFrame)
            self.scrollbar.pack(side=RIGHT, fill=Y)

            # make a text box to put the serial output
            self.log = Text(recvLogFrame,
                            width=50,
                            height=30,
                            takefocus=0,
                            borderwidth=1,
                            relief='ridge')
            self.log.pack(fill=BOTH, expand=True)

            # attach text box to scrollbar
            self.log.config(yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.log.yview)

        def send_clicked(self):
            data = str(self.user_input.get(1.0, "end-1c") + '\0')
            self.ser.write(data)
            self._log(data)
            self.user_input.delete(1.0, END)

        def _log(self, msg):
            # if platform.system() == 'Darwin':
            #    print '>> %s' % msg
            # else:
            self.log.insert(END, '\n>> %s' % msg)
            self.log.yview(END)
            self.update_idletasks()

        def clear(self):
            self.log.delete(1.0, END)
            self.update_idletasks()

        def start_stop_clicked(self):
            if self.running:
                self.running = False
                self.start_stop_button['text'] = 'Start'
            else:
                self.running = True
                self.start_stop_button['text'] = 'Stop'
                self.read_serial()  # check serial again soon

        def upload(self):
            self.bii.work()
            try:
                if platform.system() == 'Darwin':
                    self.toolchain.upload()
                else:
                    self.ser.close()
                    self.toolchain.upload()
                    self.ser.open()
                self._log('** Code uploaded **')
            except BiiException:
                self._log('** Code upload failed **')

        def _update_baud_rate(self, event=None):
            new_rate = self.button_combobox.get()
            if new_rate != self.baud_rate:
                self.baud_rate = new_rate
                self.ser.setBaudrate(new_rate)
                logger.debug('Updated serial speed to %s' % new_rate)
                self.update_idletasks()

        def read_serial(self):
            self.log.update()  # display input text

            self._read_character()
            if self.running:
                self.after(100, self.read_serial)  # check serial again soon
            self.after(100, self.update_idletasks)

        def _read_character(self):
            try:
                c = self.ser.read()  # attempt to read a character from Serial
            except SerialException as e:
                logger.error("Couldn't read serial port: %s" % str(e))
                return

            # was anything read?
            while len(c) > 0 and c != '\r':
                # get the buffer from outside of this function
                # check if character is a delimeter
                if c == '\r':
                    c = ''  # don't want returns. chuck it
                if c == '\n':
                    # self.serial_buffer += "\n"  # add the newline to the buffer
                    self.log.insert(END, "\n")
                    self.log.insert(END, self.serial_buffer)
                    self.log.yview(END)
                    self.update_idletasks()
                    self.serial_buffer = ""  # empty the buffer
                else:
                    self.serial_buffer += c  # add to the buffer
                c = self.ser.read()
예제 #14
0
파일: form.py 프로젝트: Sheldan/screenPaper
    def create_gui_elements(self):
        top_frame = Frame(self)
        top_frame.grid(row=0, column=0, columnspan=9, rowspan=6)
        # top_frame.pack(fill=X)
        # image display
        photo2 = ImageTk.PhotoImage(Image.open('back.png'))
        image_display = Label(top_frame)
        image_display.configure(image=photo2)
        image_display.image = photo2
        image_display.grid(row=0, columnspan=9, column=1, rowspan=6)
        # image_lb.pack(side=TOP)
        self.add_gui_element(GUI_ELEMENT.IMAGE_DISPLAY_LABEL, image_display)
        close_button = Button(self, text='Close', command=close)
        close_button.grid(row=9, column=9)
        # close_button.pack(side=RIGHT, padx=5, pady=5)
        self.add_gui_element(GUI_ELEMENT.CLOSE_BTN, close_button)

        bottom_frame = Frame(self)
        bottom_frame.grid(row=5, column=0, columnspan=9, rowspan=3)
        # bottom_frame.pack(fill=X)
        config_frame = Frame(bottom_frame)
        config_frame.grid(row=5, column=6, columnspan=3, rowspan=3)
        # config_frame.pack(fill=X)

        list_box_frame = Frame(config_frame)
        list_box_frame.grid(row=5, column=6, columnspan=3, rowspan=3)
        # list_box_frame.pack(side=RIGHT)
        scrollbar = Scrollbar(list_box_frame)
        # scrollbar.pack(side=RIGHT, fill=Y)
        resolution_lb = Listbox(list_box_frame, selectmode=SINGLE, height=4, yscrollcommand=scrollbar.set)
        i = 0
        for resolution in ScreenPaper.get_resolution():
            resolution_lb.insert(i, '%dx%d' % (resolution[0], resolution[1]))
            i += 1
        scrollbar.grid(row=5, column=9, rowspan=9)
        resolution_lb.grid(row=5, column=6, rowspan=4, columnspan=3)
        scrollbar.config(command=resolution_lb.yview)
        # resolution_lb.pack(side=RIGHT)

        self.add_gui_element(GUI_ELEMENT.RESOLUTION_LB, resolution_lb)
        ok_btn = Button(self, text='Create', command=self.create_pape)
        ok_btn.grid(row=9, column=7)
        # ok_btn.pack(side=RIGHT)
        self.add_gui_element(GUI_ELEMENT.OK_BTN, ok_btn)
        save_btn = Button(self, text='Save', command=self.save_image_as)
        save_btn.grid(row=9, column=8)
        # save_btn.pack(side=RIGHT)
        self.add_gui_element(GUI_ELEMENT.SAVE_BTN, save_btn)

        checkbox_frame = Frame(config_frame)
        checkbox_frame.grid(row=5, column=0, rowspan=3, columnspan=6)
        auto_save_var = IntVar()
        auto_save_chk = Checkbutton(checkbox_frame, text="Save automatically", variable=auto_save_var, onvalue=1, offvalue=0)
        auto_save_chk.grid(row=5, column=1)
        # auto_save_chk.pack(side=BOTTOM)
        self.add_gui_element(GUI_ELEMENT.AUTOMATICALLY_SAVE_CK, {'element':auto_save_chk, 'var': auto_save_var})

        auto_upload_var = IntVar()
        auto_upload_chk = Checkbutton(checkbox_frame, text="Upload to imgur automatically", variable=auto_upload_var, onvalue=1, offvalue=0)
        auto_upload_chk.grid(row=6, column=1)
        # auto_upload_chk.pack(side=BOTTOM)
        self.add_gui_element(GUI_ELEMENT.AUTOMATICALLY_UPLOAD_CK, {'element': auto_upload_chk, 'var': auto_upload_var})
        # checkbox_frame.pack(side=RIGHT)
        message_lb = Label(self)
        message_lb.grid(row=7, column=1)
        # message_lb.pack(side=BOTTOM)
        self.add_gui_element(GUI_ELEMENT.MESSAGE_LABEL, message_lb)
예제 #15
0
    def StartGui(self):
        self.tkRoot = Tk(baseName="")
        self.tkRoot.geometry("350x300+0+0")
        self.tkRoot.title("Engine SAPI GUI")
        self.GUIVisible = True

        frame = Frame(self.tkRoot)
        frame.style = Style()
        frame.style.theme_use("alt")
        frame.pack(fill=BOTH, expand=1)

        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(7, pad=7)
        frame.rowconfigure(13, weight=1)
        frame.rowconfigure(13, pad=7)
        
        Label(frame, text="Start:").grid(row = 0, column=0)
        self.labelStart = Label(frame, text="0")
        self.labelStart.grid(row = 1, column=0)

        Label(frame, text="Length:").grid(row = 0, column=1)
        self.labelLength = Label(frame, text="0")
        self.labelLength.grid(row = 1, column=1)

        Label(frame, text="Total:").grid(row = 0, column=2)
        self.labelTotal = Label(frame, text="0")
        self.labelTotal.grid(row = 1, column=2)
        
        self.labelSentenceLeft = Label(frame, text="...")
        self.labelSentenceLeft.grid(row = 2, column=0, sticky=E)
        self.labelSentenceSpoken = Label(frame, text="...", foreground="red")
        self.labelSentenceSpoken.grid(row = 2, column=1)
        self.labelSentenceRight = Label(frame, text="...")
        self.labelSentenceRight.grid(row = 2, column=2, sticky=W, columnspan=2)   

        scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.labelQueueToSpeak = Label(frame, text="Queue to speak:").grid(row = 3, column=0, pady=4, padx=5, sticky=W)
        self.listboxQueueToSpeak = Listbox(frame, width=50, height=3, yscrollcommand=scrollbar.set)
        
        scrollbar.config(command=self.listboxQueueToSpeak.yview)
        self.listboxQueueToSpeak.grid( sticky=N+S+E+W, row = 4, column = 0, columnspan = 2 ,rowspan = 3, padx=3)
        scrollbar.grid(sticky=N+S+W, row = 4, column = 2, rowspan = 3)

        self.buttonPauze = Button(frame, text="Pauze", command=self.communicationProtocal.handlePauze)
        self.buttonPauze.grid(row = 4, column=3)

        self.buttonStop = Button(frame, text="Stop", command=self.communicationProtocal.restartProcess)
        self.buttonStop.grid(row = 5, column=3)

        self.buttonResume = Button(frame, text="Resume", command=self.communicationProtocal.handleResume)
        self.buttonResume.grid(row = 6, column=3)

        Label(frame, text="Text to say:").grid(row = 7, column=0, padx=3, sticky=W)

        self.stringVarTextToSay = StringVar()
        self.entryTextToSay = Entry(frame, textvariable=self.stringVarTextToSay, width=500)
        self.entryTextToSay.grid(row=8, column=0, columnspan=3, padx=3, sticky=W)
        self.stringVarTextToSay.set("Hello SAPI Speak Engine")
        self.entryTextToSay.bind('<Return>', self.CallBackReturnSay)

        self.buttonSay = Button(frame, text="Say", command=self.CallBackButtonSay)
        self.buttonSay.grid(row = 8, column=3)

        Label(frame, text="Recover action:").grid(row = 9, column=0, padx=3, sticky=W)
        self.recoverActionLabelText = "None"
        self.labelRecoverAction = Label(frame, text=self.recoverActionLabelText, foreground="blue")
        self.labelRecoverAction.grid(row = 10, column=0)   

        Label(frame, text="Voice speed:").grid(row = 9, column=1, sticky=W)
        self.buttonSpeedDown = Button(frame, text="Speed down", command=self.communicationProtocal.handleSpeedDown)
        self.buttonSpeedDown.grid(row = 10, column=1, padx=3, sticky=E)

        self.speedValue = 0
        self.intVarSpeed = IntVar()
        vcmd = (self.tkRoot.register(self.OnValidateEntrySpeakSpeed), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entrySpeakSpeed = Entry(frame, textvariable=self.intVarSpeed, validate="key", validatecommand=vcmd, width=5)
        self.entrySpeakSpeed.grid(row=10,column=2)
        self.entrySpeakSpeed.bind('<Return>', self.CallBackSetSpeed)

        self.buttonSpeedUp = Button(frame, text="Speed up", command=self.communicationProtocal.handleSpeedUp)
        self.buttonSpeedUp.grid(row = 10, column=3)

        Label(frame, text="voice:").grid(row = 11, column=0, padx=3, sticky=W)
        self.buttonPrevVoice = Button(frame, text="Prev voice", command=self.communicationProtocal.handlePrevVoice)
        self.buttonPrevVoice.grid(row = 12, column=0, padx=3, sticky=W)

        self.buttonNextVoice = Button(frame, text="Next voice", command=self.communicationProtocal.handleNextVoice)
        self.buttonNextVoice.grid(row = 12, column=3)

        self.currentVoice = StringVar(self.tkRoot)
        self.currentVoice.set(self.communicationProtocal.CurrentVoiceName)

        engine = pyttsx.init()
        voices = engine.getProperty("voices")
        voiceNames = list()
        for x in xrange(0, len(voices)):
            voiceNames.append(voices[x].name)
        self.optionMenuVoices = OptionMenu(frame, self.currentVoice, *tuple(voiceNames), command=self.CallBackOptionMenuVoices)
        self.optionMenuVoices.config(width=500)
        self.optionMenuVoices.grid(sticky=W, row = 12, column = 1)
     
        #hide if close button is clicked
        self.tkRoot.protocol("WM_DELETE_WINDOW", self.HideGui)
        self.tkRoot.after(1000/32, self.Update)
        self.tkRoot.mainloop()  
예제 #16
0
class GuiFrame():

    ## The constructor
    #
    #  @param  self          [in]   Object reference
    #  @param  parent        [in]   Root object reference
    #  @param  rulesFile     [in]   Rules file name
    #  @param  outDir        [in]   Location of output directory
    #  @return None
    def __init__(self, parent, rulesFile, outDir):
        self.exit = False
        self.parent = parent
        self.rulesFile = rulesFile
        self.outDir = outDir
        self.bgndFrm = None
        self.scrollbar = None
        self.log = None

        # Create the outdir if it doesn't exist
        if not os.path.exists(outDir):
            os.makedirs(outDir)

        self.initUI()
        self.parseRules = ParseRules(self)
        self.parseRules.verifyParameters()

    ## Close button press
    #
    #  Called when the close button is pressed.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def closeBtnPress(self):
        self.exit = True

    ## Init UI
    #
    #  Initialize the user interface.  Create the cmd panel at the
    #  top which contains the status and column headings.  Walk
    #  through the cardType array and create a panel for each card.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def initUI(self):
        self.parent.wm_title("Generate Python Code GUI")
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(0, weight=1)
        self.bgndFrm = Frame(self.parent)
        self.bgndFrm.grid()

        self.cmdPanel()
        self.consolePanel()

    ## Create command panel
    #
    #  Create the command panel.  It contains the close button.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def cmdPanel(self):
        tmpFrm = Frame(self.bgndFrm, borderwidth=5, relief=RAISED)
        tmpFrm.grid()
        tmpFrm.grid(column=0, row=0)
        tmpBtn = Button(tmpFrm,
                        width=12,
                        text="Close",
                        command=self.closeBtnPress)
        tmpBtn.grid(column=0, row=0, padx=4, pady=8)

    ## Create console panel
    #
    #  Create the console panel.  It the console text box.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def consolePanel(self):
        tmpFrm = Frame(self.bgndFrm, borderwidth=5, relief=RAISED)
        tmpFrm.grid()
        tmpFrm.grid(column=0, row=1)
        self.scrollbar = Scrollbar(tmpFrm)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.log = Text(tmpFrm, wrap=WORD, yscrollcommand=self.scrollbar.set)
        self.log.pack()
        self.scrollbar.config(command=self.log.yview)

    ## Update console
    #
    #  Update the console window with new text
    #
    #  @param  self          [in]   Object reference
    #  @param  text          [in]   Text to be added to the console window
    #  @return None
    def updateConsole(self, text):
        self.log['state'] = 'normal'
        self.log.insert('end', text + "\n")
        self.log['state'] = 'disabled'
        self.log.see(END)

    ## GUI exit
    #
    #  Set the exit flag.
    #
    #  @param  self          [in]   Object reference
    #  @return None
    def gui_exit(self):
        self.exit = True
예제 #17
0
파일: gui.py 프로젝트: ojobabs/ML
    def initUI(self):

        # Configures the GUI
        self.parent.title("Neural Networks for Handwritten Digit Recognition")
        self.style = Style()
        self.pack(fill=BOTH, expand=1)

        # Creates a grid 5x4 in to which we will place elements.
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=0)
        self.columnconfigure(3, weight=0)
        self.columnconfigure(4, weight=0)
        self.columnconfigure(5, weight=0)
        self.columnconfigure(6, weight=0)
        self.columnconfigure(7, weight=0)
        self.columnconfigure(8, weight=0)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=0)
        self.rowconfigure(3, weight=0)
        self.rowconfigure(4, weight=0)

        # Create explanation text for app
        explanation = """
        "This program is capable of utilizing different learning algorithms as a mean to achieve a +90% accuracy in recognizing MNIST
    	digits based on Neural Networks as a way of detecting the different numbers and classifying them correctly" \n
        Select the checkboxes that you wish to utilize ([ ] Learn from starting random values, [X] Learn from preexisting data / [ ] Do not
        save the results [X] Save the final values of the Weights and Biases), Press the Run button to start the Neural Network\n"""

        self.exp = Label(self, text=explanation)
        self.exp.grid(
            row=2,
            column=1,
            columnspan=4,
            padx=2,
            pady=2,
        )

        # Creates the Y scrollbar that is spawned through the whole grid
        yscrollbar = Scrollbar(self, orient=VERTICAL)
        yscrollbar.grid(row=1, column=8, sticky=N + S)

        # Creates the text area and spawns it through the whole window
        self.textarea = Text(self,
                             wrap=NONE,
                             bd=0,
                             yscrollcommand=yscrollbar.set)

        self.textarea.grid(row=1,
                           column=1,
                           columnspan=4,
                           rowspan=1,
                           padx=0,
                           sticky=E + W + S + N)

        yscrollbar.config(command=self.textarea.yview)

        # Creates the run button in the lower row
        self.runButton = Button(self, text="Run Neural Network")
        self.runButton.grid(row=4, column=1, padx=5, pady=5, sticky=W)
        self.runButton.bind("<ButtonRelease-1>", self.runNN)

        # Creates the variable initialization checkbox in the lower row
        self.initvalVar = StringVar()
        initvalCheck = Checkbutton(self,
                                   text="Learn from Initial Values",
                                   variable=self.initvalVar,
                                   onvalue="-l",
                                   offvalue="")
        initvalCheck.grid(row=4, column=2, padx=5, pady=5)

        # Creates the save variables checkbox in the lower row
        self.saveValVar = StringVar()
        saveVal = Checkbutton(self,
                              text="Save final Weights & Biases",
                              variable=self.saveValVar,
                              onvalue="-s",
                              offvalue="")
        saveVal.grid(row=4, column=3, padx=5, pady=5)

        # Creates the clear button for the textbox
        self.clearButton = Button(self, text="Clear")
        self.clearButton.grid(row=4, column=4, padx=5, pady=5)
        self.clearButton.bind("<ButtonRelease-1>", self.clearText)

        # Defines the tags that are used to colorise the text added to the text widget.
        self.textarea.tag_config("errorstring",
                                 foreground="#CC0000")  # Red Color
        self.textarea.tag_config("infostring",
                                 foreground="#008800")  # Green Color
예제 #18
0
파일: gui.py 프로젝트: kelliott121/Octopod
class MacroFrame(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.numStates = 0
        self.initUI()

    def initUI(self):
        self.columnconfigure(0, weight=0)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        self.rowconfigure(0, weight=1)

        self.commandFrame = Frame(self, background="white")
        self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W+E)
        self.commandFrame.columnconfigure(1, weight=1)

        self.btnCommand = Button(self.commandFrame, text="Run")
        self.btnCommand.grid(row=0, column=0)

        self.strCommand = StringVar()
        self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand)
        self.entCommand.grid(row=0, column=1, sticky=W+E)
        
        self.lstMacro = Listbox(self)
        self.lstMacro.grid(row=1, column=0, sticky=N+S+W+E)
        
        self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse")
        self.treeview.grid(row=1, column=1, columnspan=4, sticky=N+S+W+E)
        self.treeScrollbar = Scrollbar(self)
        self.treeScrollbar.grid(row=1, column=5, sticky=N+S)
        self.treeview.config(yscrollcommand=self.treeScrollbar.set)
        self.treeScrollbar.config(command=self.treeview.yview)

        self.btnFrame = Frame(self, background="white")
        self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W+E)

        self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro)
        self.btnRun.grid(row=0, column=0)
        
        self.btnStop = Button(self.btnFrame, text="Stop")
        self.btnStop.grid(row=0, column=1)

        self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro)
        self.btnSaveMacro.grid(row=0, column=2)

        self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro")
        self.btnDeleteMacro.grid(row=0, column=3)

        self.btnDeleteState = Button(self.btnFrame, text="Delete State")
        self.btnDeleteState.grid(row=0, column=4)

    def addState(self, robot):
        stateName = "state" + str(self.numStates)
        self.treeview.insert("", END, iid=stateName, text=stateName)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            self.treeview.insert(stateName, END, iid=stateName + "_" + limbName, text=limbName)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    self.treeview.insert(stateName + "_" + limbName,
                                         END,
                                         iid=stateName + "_" + limbName + "_" + partName,
                                         text=partName,
                                         values=[part.angle])
                    partNum += 1
            limbNum += 1
        self.numStates += 1

    def getState(self, stateNum, robot):
        stateName = "state" + str(stateNum)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    part.setAngle(int(self.treeview.item(stateName + "_" + limbName + "_" + partName, "values")[0]))
                    partNum += 1
            limbNum += 1

    def runMacro(self):
        thread = threading.Thread(target=self.updateState)
        thread.start()
            
    def updateState(self):
        for i in range(self.numStates):
            self.getState(i, self.parent.robotFrame.robot)
            time.sleep(.1)

    def saveMacro(self):
        pass
예제 #19
0
파일: gui.py 프로젝트: demetraux/Octopod
class MacroFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.numStates = 0
        self.initUI()

    def initUI(self):
        self.columnconfigure(0, weight=0)
        self.columnconfigure(1, weight=0)
        self.columnconfigure(2, weight=1)
        self.columnconfigure(3, weight=1)

        self.rowconfigure(0, weight=1)

        self.commandFrame = Frame(self, background="white")
        self.commandFrame.grid(row=0, column=0, columnspan=5, sticky=W + E)
        self.commandFrame.columnconfigure(1, weight=1)

        self.btnCommand = Button(self.commandFrame, text="Run")
        self.btnCommand.grid(row=0, column=0)

        self.strCommand = StringVar()
        self.entCommand = Entry(self.commandFrame, textvariable=self.strCommand)
        self.entCommand.grid(row=0, column=1, sticky=W + E)

        self.lstMacro = Listbox(self)
        self.lstMacro.grid(row=1, column=0, sticky=N + S + W + E)

        self.treeview = Treeview(self, columns=("Angle"), displaycolumns="#all", selectmode="browse")
        self.treeview.grid(row=1, column=1, columnspan=4, sticky=N + S + W + E)
        self.treeScrollbar = Scrollbar(self)
        self.treeScrollbar.grid(row=1, column=5, sticky=N + S)
        self.treeview.config(yscrollcommand=self.treeScrollbar.set)
        self.treeScrollbar.config(command=self.treeview.yview)

        self.btnFrame = Frame(self, background="white")
        self.btnFrame.grid(row=2, column=0, columnspan=5, sticky=W + E)

        self.btnRun = Button(self.btnFrame, text="Run", command=self.runMacro)
        self.btnRun.grid(row=0, column=0)

        self.btnStop = Button(self.btnFrame, text="Stop")
        self.btnStop.grid(row=0, column=1)

        self.btnSaveMacro = Button(self.btnFrame, text="Save Macro", command=self.saveMacro)
        self.btnSaveMacro.grid(row=0, column=2)

        self.btnDeleteMacro = Button(self.btnFrame, text="Delete Macro")
        self.btnDeleteMacro.grid(row=0, column=3)

        self.btnDeleteState = Button(self.btnFrame, text="Delete State")
        self.btnDeleteState.grid(row=0, column=4)

    def addState(self, robot):
        stateName = "state" + str(self.numStates)
        self.treeview.insert("", END, iid=stateName, text=stateName)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            self.treeview.insert(stateName, END, iid=stateName + "_" + limbName, text=limbName)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    self.treeview.insert(
                        stateName + "_" + limbName,
                        END,
                        iid=stateName + "_" + limbName + "_" + partName,
                        text=partName,
                        values=[part.angle],
                    )
                    partNum += 1
            limbNum += 1
        self.numStates += 1

    def getState(self, stateNum, robot):
        stateName = "state" + str(stateNum)
        limbNum = 0
        for limb in robot.getLimbs():
            limbName = "limb" + str(limbNum)
            partNum = 0
            for part in limb.getComponents():
                partName = "joint" + str(partNum)
                if isinstance(part, Joint):
                    part.setAngle(int(self.treeview.item(stateName + "_" + limbName + "_" + partName, "values")[0]))
                    partNum += 1
            limbNum += 1

    def runMacro(self):
        thread = threading.Thread(target=self.updateState)
        thread.start()

    def updateState(self):
        for i in range(self.numStates):
            self.getState(i, self.parent.robotFrame.robot)
            time.sleep(0.1)

    def saveMacro(self):
        pass
예제 #20
0
파일: view.py 프로젝트: adamchainz/bugjar
class MainWindow(object):
    def __init__(self, root, debugger):
        '''
        -----------------------------------------------------
        | main button toolbar                               |
        -----------------------------------------------------
        |       < ma | in content area >      |             |
        |            |                        |             |
        | File list  | File name              | Inspector   |
        | (stack/    | Code area              |             |
        | breakpnts) |                        |             |
        |            |                        |             |
        |            |                        |             |
        -----------------------------------------------------
        |     status bar area                               |
        -----------------------------------------------------

        '''

        # Obtain and expand the current working directory.
        base_path = os.path.abspath(os.getcwd())
        base_path = os.path.normcase(base_path) + '/'

        # Create a filename normalizer based on the CWD.
        self.filename_normalizer = filename_normalizer(base_path)

        self.debugger = debugger
        # Associate the debugger with this view.
        self.debugger.view = self

        # Root window
        self.root = root
        self.root.title('Bugjar')
        self.root.geometry('1024x768')

        # Prevent the menus from having the empty tearoff entry
        self.root.option_add('*tearOff', False)
        # Catch the close button
        self.root.protocol("WM_DELETE_WINDOW", self.cmd_quit)
        # Catch the "quit" event.
        self.root.createcommand('exit', self.cmd_quit)

        # Setup the menu
        self._setup_menubar()

        # Set up the main content for the window.
        self._setup_button_toolbar()
        self._setup_main_content()
        self._setup_status_bar()

        # Now configure the weights for the root frame
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=0)
        self.root.rowconfigure(1, weight=1)
        self.root.rowconfigure(2, weight=0)

        debugger.start()

    ######################################################
    # Internal GUI layout methods.
    ######################################################

    def _setup_menubar(self):
        # Menubar
        self.menubar = Menu(self.root)

        # self.menu_Apple = Menu(self.menubar, name='Apple')
        # self.menubar.add_cascade(menu=self.menu_Apple)

        self.menu_file = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_file, label='File')

        self.menu_program = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_program, label='Program')

        self.menu_help = Menu(self.menubar)
        self.menubar.add_cascade(menu=self.menu_help, label='Help')

        # self.menu_Apple.add_command(label='Test', command=self.cmd_dummy)

        # self.menu_file.add_command(label='New', command=self.cmd_dummy, accelerator="Command-N")
        self.menu_file.add_command(label='Open...', command=self.cmd_open_file, accelerator="Command-O")
        self.root.bind('<Command-o>', self.cmd_open_file)
        # self.menu_file.add_command(label='Close', command=self.cmd_dummy)

        self.menu_program.add_command(label='Run', command=self.cmd_run, accelerator="R")
        self.root.bind('<r>', self.cmd_run)
        self.menu_program.add_command(label='Step', command=self.cmd_step, accelerator="S")
        self.root.bind('<s>', self.cmd_step)
        self.menu_program.add_command(label='Next', command=self.cmd_next, accelerator="N")
        self.root.bind('<n>', self.cmd_next)
        self.menu_program.add_command(label='Return', command=self.cmd_return, accelerator="BackSpace")
        self.root.bind('<BackSpace>', self.cmd_return)

        self.menu_help.add_command(label='Open Documentation', command=self.cmd_bugjar_docs)
        self.menu_help.add_command(label='Open Bugjar project page', command=self.cmd_bugjar_page)
        self.menu_help.add_command(label='Open Bugjar on GitHub', command=self.cmd_bugjar_github)
        self.menu_help.add_command(label='Open BeeWare project page', command=self.cmd_beeware_page)

        # last step - configure the menubar
        self.root['menu'] = self.menubar

    def _setup_button_toolbar(self):
        '''
        The button toolbar runs as a horizontal area at the top of the GUI.
        It is a persistent GUI component
        '''

        # Main toolbar
        self.toolbar = Frame(self.root)
        self.toolbar.grid(column=0, row=0, sticky=(W, E))

        # Buttons on the toolbar
        self.run_button = Button(self.toolbar, text='Run', command=self.cmd_run)
        self.run_button.grid(column=0, row=0)

        self.step_button = Button(self.toolbar, text='Step', command=self.cmd_step)
        self.step_button.grid(column=1, row=0)

        self.next_button = Button(self.toolbar, text='Next', command=self.cmd_next)
        self.next_button.grid(column=2, row=0)

        self.return_button = Button(self.toolbar, text='Return', command=self.cmd_return)
        self.return_button.grid(column=3, row=0)

        self.toolbar.columnconfigure(0, weight=0)
        self.toolbar.rowconfigure(0, weight=0)

    def _setup_main_content(self):
        '''
        Sets up the main content area. It is a persistent GUI component
        '''

        # Main content area
        self.content = PanedWindow(self.root, orient=HORIZONTAL)
        self.content.grid(column=0, row=1, sticky=(N, S, E, W))

        # Create subregions of the content
        self._setup_file_lists()
        self._setup_code_area()
        self._setup_inspector()

        # Set up weights for the left frame's content
        self.content.columnconfigure(0, weight=1)
        self.content.rowconfigure(0, weight=1)

        self.content.pane(0, weight=1)
        self.content.pane(1, weight=2)
        self.content.pane(2, weight=1)

    def _setup_file_lists(self):

        self.file_notebook = Notebook(self.content, padding=(0, 5, 0, 5))
        self.content.add(self.file_notebook)

        self._setup_stack_frame_list()
        self._setup_breakpoint_list()

    def _setup_stack_frame_list(self):
        self.stack_frame = Frame(self.content)
        self.stack_frame.grid(column=0, row=0, sticky=(N, S, E, W))
        self.file_notebook.add(self.stack_frame, text='Stack')

        self.stack = StackView(self.stack_frame, normalizer=self.filename_normalizer)
        self.stack.grid(column=0, row=0, sticky=(N, S, E, W))

        # # The tree's vertical scrollbar
        self.stack_scrollbar = Scrollbar(self.stack_frame, orient=VERTICAL)
        self.stack_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # # Tie the scrollbar to the text views, and the text views
        # # to each other.
        self.stack.config(yscrollcommand=self.stack_scrollbar.set)
        self.stack_scrollbar.config(command=self.stack.yview)

        # Setup weights for the "stack" tree
        self.stack_frame.columnconfigure(0, weight=1)
        self.stack_frame.columnconfigure(1, weight=0)
        self.stack_frame.rowconfigure(0, weight=1)

        # Handlers for GUI events
        self.stack.bind('<<TreeviewSelect>>', self.on_stack_frame_selected)

    def _setup_breakpoint_list(self):
        self.breakpoints_frame = Frame(self.content)
        self.breakpoints_frame.grid(column=0, row=0, sticky=(N, S, E, W))
        self.file_notebook.add(self.breakpoints_frame, text='Breakpoints')

        self.breakpoints = BreakpointView(self.breakpoints_frame, normalizer=self.filename_normalizer)
        self.breakpoints.grid(column=0, row=0, sticky=(N, S, E, W))

        # The tree's vertical scrollbar
        self.breakpoints_scrollbar = Scrollbar(self.breakpoints_frame, orient=VERTICAL)
        self.breakpoints_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # Tie the scrollbar to the text views, and the text views
        # to each other.
        self.breakpoints.config(yscrollcommand=self.breakpoints_scrollbar.set)
        self.breakpoints_scrollbar.config(command=self.breakpoints.yview)

        # Setup weights for the "breakpoint list" tree
        self.breakpoints_frame.columnconfigure(0, weight=1)
        self.breakpoints_frame.columnconfigure(1, weight=0)
        self.breakpoints_frame.rowconfigure(0, weight=1)

        # Handlers for GUI events
        self.breakpoints.tag_bind('breakpoint', '<Double-Button-1>', self.on_breakpoint_double_clicked)
        self.breakpoints.tag_bind('breakpoint', '<<TreeviewSelect>>', self.on_breakpoint_selected)
        self.breakpoints.tag_bind('file', '<<TreeviewSelect>>', self.on_breakpoint_file_selected)

    def _setup_code_area(self):
        self.code_frame = Frame(self.content)
        self.code_frame.grid(column=1, row=0, sticky=(N, S, E, W))

        # Label for current file
        self.current_file = StringVar()
        self.current_file_label = Label(self.code_frame, textvariable=self.current_file)
        self.current_file_label.grid(column=0, row=0, sticky=(W, E))

        # Code display area
        self.code = DebuggerCode(self.code_frame, debugger=self.debugger)
        self.code.grid(column=0, row=1, sticky=(N, S, E, W))

        # Set up weights for the code frame's content
        self.code_frame.columnconfigure(0, weight=1)
        self.code_frame.rowconfigure(0, weight=0)
        self.code_frame.rowconfigure(1, weight=1)

        self.content.add(self.code_frame)

    def _setup_inspector(self):
        self.inspector_frame = Frame(self.content)
        self.inspector_frame.grid(column=2, row=0, sticky=(N, S, E, W))

        self.inspector = InspectorView(self.inspector_frame)
        self.inspector.grid(column=0, row=0, sticky=(N, S, E, W))

        # The tree's vertical scrollbar
        self.inspector_scrollbar = Scrollbar(self.inspector_frame, orient=VERTICAL)
        self.inspector_scrollbar.grid(column=1, row=0, sticky=(N, S))

        # Tie the scrollbar to the text views, and the text views
        # to each other.
        self.inspector.config(yscrollcommand=self.inspector_scrollbar.set)
        self.inspector_scrollbar.config(command=self.inspector.yview)

        # Setup weights for the "breakpoint list" tree
        self.inspector_frame.columnconfigure(0, weight=1)
        self.inspector_frame.columnconfigure(1, weight=0)
        self.inspector_frame.rowconfigure(0, weight=1)

        self.content.add(self.inspector_frame)

    def _setup_status_bar(self):
        # Status bar
        self.statusbar = Frame(self.root)
        self.statusbar.grid(column=0, row=2, sticky=(W, E))

        # Current status
        self.run_status = StringVar()
        self.run_status_label = Label(self.statusbar, textvariable=self.run_status)
        self.run_status_label.grid(column=0, row=0, sticky=(W, E))
        self.run_status.set('Not running')

        # Main window resize handle
        self.grip = Sizegrip(self.statusbar)
        self.grip.grid(column=1, row=0, sticky=(S, E))

        # Set up weights for status bar frame
        self.statusbar.columnconfigure(0, weight=1)
        self.statusbar.columnconfigure(1, weight=0)
        self.statusbar.rowconfigure(0, weight=0)

    ######################################################
    # Utility methods for controlling content
    ######################################################

    def show_file(self, filename, line=None, breakpoints=None):
        """Show the content of the nominated file.

        If specified, line is the current line number to highlight. If the
        line isn't currently visible, the window will be scrolled until it is.

        breakpoints is a list of line numbers that have current breakpoints.

        If refresh is true, the file will be reloaded and redrawn.
        """
        # Set the filename label for the current file
        self.current_file.set(self.filename_normalizer(filename))

        # Update the code view; this means changing the displayed file
        # if necessary, and updating the current line.
        if filename != self.code.filename:
            self.code.filename = filename
            for bp in self.debugger.breakpoints(filename).values():
                if bp.enabled:
                    self.code.enable_breakpoint(bp.line)
                else:
                    self.code.disable_breakpoint(bp.line)

        self.code.line = line

    ######################################################
    # TK Main loop
    ######################################################

    def mainloop(self):
        self.root.mainloop()

    ######################################################
    # TK Command handlers
    ######################################################

    def cmd_quit(self):
        "Quit the debugger"
        self.debugger.stop()
        self.root.quit()

    def cmd_run(self, event=None):
        "Run until the next breakpoint, or end of execution"
        self.debugger.do_run()

    def cmd_step(self, event=None):
        "Step into the next line of code"
        self.debugger.do_step()

    def cmd_next(self, event=None):
        "Run the next line of code in the current frame"
        self.debugger.do_next()

    def cmd_return(self, event=None):
        "Return to the previous frame"
        self.debugger.do_return()

    def cmd_open_file(self, event=None):
        "Open a file in the breakpoint pane"
        filename = tkFileDialog.askopenfilename(initialdir=os.path.abspath(os.getcwd()))

        if filename:
            # Convert to canonical form
            filename = os.path.abspath(filename)
            filename = os.path.normcase(filename)

            # Show the file contents
            self.code.filename = filename

            # Ensure the file appears on the breakpoint list
            self.breakpoints.insert_filename(filename)

            # Show the breakpoint panel
            self.file_notebook.select(self.breakpoints_frame)

            # ... select the new filename
            self.breakpoints.selection_set(filename)

            # .. and clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def cmd_bugjar_page(self):
        "Show the Bugjar project page"
        webbrowser.open_new('http://pybee.org/bugjar')

    def cmd_bugjar_github(self):
        "Show the Bugjar GitHub repo"
        webbrowser.open_new('http://github.com/pybee/bugjar')

    def cmd_bugjar_docs(self):
        "Show the Bugjar documentation"
        # If this is a formal release, show the docs for that
        # version. otherwise, just show the head docs.
        if len(NUM_VERSION) == 3:
            webbrowser.open_new('http://bugjar.readthedocs.org/en/v%s/' % VERSION)
        else:
            webbrowser.open_new('http://bugjar.readthedocs.org/')

    def cmd_beeware_page(self):
        "Show the BeeWare project page"
        webbrowser.open_new('http://pybee.org/')

    ######################################################
    # Handlers for GUI actions
    ######################################################

    def on_stack_frame_selected(self, event):
        "When a stack frame is selected, highlight the file and line"
        if event.widget.selection():
            _, index = event.widget.selection()[0].split(':')
            line, frame = self.debugger.stack[int(index)]

            # Display the file in the code view
            self.show_file(filename=frame['filename'], line=line)

            # Display the contents of the selected frame in the inspector
            self.inspector.show_frame(frame)

            # Clear any currently selected item on the breakpoint tree
            self.breakpoints.selection_remove(self.breakpoints.selection())

    def on_breakpoint_selected(self, event):
        "When a breakpoint on the tree has been selected, show the breakpoint"
        if event.widget.selection():
            parts = event.widget.focus().split(':')
            bp = self.debugger.breakpoint((parts[0], int(parts[1])))
            self.show_file(filename=bp.filename, line=bp.line)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def on_breakpoint_file_selected(self, event):
        "When a file is selected on the breakpoint tree, show the file"
        if event.widget.selection():
            filename = event.widget.focus()
            self.show_file(filename=filename)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    def on_breakpoint_double_clicked(self, event):
        "When a breakpoint on the tree is double clicked, toggle it's status"
        if event.widget.selection():
            parts = event.widget.focus().split(':')
            bp = self.debugger.breakpoint((parts[0], int(parts[1])))
            if bp.enabled:
                self.debugger.disable_breakpoint(bp)
            else:
                self.debugger.enable_breakpoint(bp)

            # Clear any currently selected item on the stack tree
            self.stack.selection_remove(self.stack.selection())

    ######################################################
    # Handlers for debugger responses
    ######################################################

    def on_stack(self, stack):
        "A report of a new stack"
        # Make sure the stack frame list is displayed
        self.file_notebook.select(self.stack_frame)

        # Update the stack list
        self.stack.update_stack(stack)

        if len(stack) > 0:
            # Update the display of the current file
            line = stack[-1][0]
            filename = stack[-1][1]['filename']
            self.show_file(filename=filename, line=line)

            # Select the current stack frame in the frame list
            self.stack.selection_set('frame:%s' % (len(stack) - 1))
        else:
            # No current frame (probably end of execution),
            # so clear the current line marker
            self.code.line = None

    def on_line(self, filename, line):
        "A single line of code has been executed"
        self.run_status.set('Line (%s:%s)' % (filename, line))

    def on_call(self, args):
        "A callable has been invoked"
        self.run_status.set('Call: %s' % args)

    def on_return(self, retval):
        "A callable has returned"
        self.run_status.set('Return: %s' % retval)

    def on_exception(self, name, value):
        "An exception has been raised"
        self.run_status.set('Exception: %s - %s' % (name, value))
        tkMessageBox.showwarning(message='%s: %s' % (name, value))

    def on_postmortem(self):
        "An exception has been raised"
        self.run_status.set('Post mortem mode')
        tkMessageBox.showerror(message='Entering post mortem mode. Step/Next will restart')

    def on_restart(self):
        "The code has finished running, and will start again"
        self.run_status.set('Not running')
        tkMessageBox.showinfo(message='Program has finished, and will restart.')

    def on_info(self, message):
        "The debugger needs to inform the user of something"
        tkMessageBox.showinfo(message=message)

    def on_warning(self, message):
        "The debugger needs to warn the user of something"
        tkMessageBox.showwarning(message=message)

    def on_error(self, message):
        "The debugger needs to report an error"
        tkMessageBox.showerror(message=message)

    def on_breakpoint_enable(self, bp):
        "A breakpoint has been enabled in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.enable_breakpoint(bp.line, temporary=bp.temporary)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_disable(self, bp):
        "A breakpoint has been disabled in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.disable_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_ignore(self, bp, count):
        "A breakpoint has been ignored by the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.ignore_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)

    def on_breakpoint_clear(self, bp):
        "A breakpoint has been cleared in the debugger"
        # If the breakpoint is in the currently displayed file, updated
        # the display of the breakpoint.
        if bp.filename == self.code.filename:
            self.code.clear_breakpoint(bp.line)

        # ... then update the display of the breakpoint on the tree
        self.breakpoints.update_breakpoint(bp)
예제 #21
0
파일: updater.py 프로젝트: KeyWeeUsr/iSPTC
## Tkinter below
root = Tk()
root.title("Updater ver: " + str(v))
root.minsize(280, 300)

frame = Frame(root, height=210, width=600, relief=SUNKEN)
frame.pack_propagate(0)
frame.pack(anchor=NE, side=TOP, padx=20, pady=20)

S = Scrollbar(frame)
T = Text(frame, height=46, width=80, wrap=WORD)

S.pack(side=RIGHT, fill=Y)
T.pack(side=BOTTOM, fill=BOTH, expand=1)
S.config(command=T.yview)
T.tag_configure('redcol', foreground='red')
T.tag_configure('blackcol', foreground='black')
T.tag_configure('greencol', background='#c8d9ea', foreground='#009900')
T.tag_configure('failed', background='#c8d9ea', foreground='red')

button = Button(
    root,
    text='Reopen client',
    command=lambda: {restart_client(), root.destroy()})
button.place(x=180, y=250)
button2 = Button(root, text='Close', command=lambda: {root.destroy()})
button2.place(x=360, y=250)

## Create download link list
tlist = []
예제 #22
0
class Scrolling_Area(Frame, object):
    def __init__(self,
                 master,
                 width=None,
                 height=None,
                 mousewheel_speed=2,
                 scroll_horizontally=True,
                 xscrollbar=None,
                 scroll_vertically=True,
                 yscrollbar=None,
                 outer_background=None,
                 inner_frame=Frame,
                 **kw):
        super(Scrolling_Area, self).__init__(master, **kw)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self._clipper = Frame(self,
                              background=outer_background,
                              width=width,
                              height=height)
        self._clipper.grid(row=0, column=0, sticky=N + E + W + S)

        self._width = width
        self._height = height

        self.innerframe = inner_frame(self._clipper,
                                      padx=0,
                                      pady=0,
                                      highlightthickness=0)
        self.innerframe.place(in_=self._clipper, x=0, y=0)

        if scroll_vertically:
            if yscrollbar is not None:
                self.yscrollbar = yscrollbar
            else:
                self.yscrollbar = Scrollbar(self, orient=VERTICAL)
                self.yscrollbar.grid(row=0, column=1, sticky=N + S)

            self.yscrollbar.set(0.0, 1.0)
            self.yscrollbar.config(command=self.yview)
        else:
            self.yscrollbar = None

        self._scroll_vertically = scroll_vertically

        if scroll_horizontally:
            if xscrollbar is not None:
                self.xscrollbar = xscrollbar
            else:
                self.xscrollbar = Scrollbar(self, orient=HORIZONTAL)
                self.xscrollbar.grid(row=1, column=0, sticky=E + W)

            self.xscrollbar.set(0.0, 1.0)
            self.xscrollbar.config(command=self.xview)
        else:
            self.xscrollbar = None

        self._scroll_horizontally = scroll_horizontally

        self._jfraction = 0.05
        self._startX = 0
        self._startY = 0

        # Whenever the clipping window or scrolled frame change size,
        # update the scrollbars.
        self.innerframe.bind('<Configure>', self._on_configure)
        self._clipper.bind('<Configure>', self._on_configure)

        self.innerframe.xview = self.xview
        self.innerframe.yview = self.yview

        Mousewheel_Support(self).add_support_to(self.innerframe,
                                                xscrollbar=self.xscrollbar,
                                                yscrollbar=self.yscrollbar)

    def update_viewport(self):
        # compute new height and width
        self.update()
        frameHeight = float(self.innerframe.winfo_reqheight())
        frameWidth = float(self.innerframe.winfo_reqwidth())

        if self._width is not None:
            width = min(self._width, frameWidth)
        else:
            width = self._frameWidth

        if self._height is not None:
            height = min(self._height, frameHeight)
        else:
            height = self._frameHeight

        self._clipper.configure(width=width, height=height)

    def _on_configure(self, event):
        self._frameHeight = float(self.innerframe.winfo_reqheight())
        self._frameWidth = float(self.innerframe.winfo_reqwidth())

        # resize the visible part
        if self._scroll_horizontally:
            self.xview("scroll", 0, "unit")

        if self._scroll_vertically:
            self.yview("scroll", 0, "unit")

    def xview(self, mode=None, value=None, units=None):
        value = float(value)

        clipperWidth = self._clipper.winfo_width()
        frameWidth = self._frameWidth

        _startX = self._startX

        if mode is None:
            return self.xscrollbar.get()
        elif mode == 'moveto':
            # absolute movement
            self._startX = int(value * frameWidth)
        else:
            # mode == 'scroll'
            # relative movement
            if units == 'units':
                jump = int(clipperWidth * self._jfraction)
            else:
                jump = clipperWidth
            self._startX = self._startX + value * jump

        if frameWidth <= clipperWidth:
            # The scrolled frame is smaller than the clipping window.

            self._startX = 0
            hi = 1.0
            #use expand by default
            relwidth = 1
        else:
            # The scrolled frame is larger than the clipping window.
            #use expand by default
            if self._startX + clipperWidth > frameWidth:
                self._startX = frameWidth - clipperWidth
                hi = 1.0
            else:
                if self._startX < 0:
                    self._startX = 0
                hi = (self._startX + clipperWidth) / frameWidth
            relwidth = ''

        if self._startX != _startX:
            # Position frame relative to clipper.
            self.innerframe.place(x=-self._startX, relwidth=relwidth)

        lo = self._startX / frameWidth
        self.xscrollbar.set(lo, hi)

    def yview(self, mode=None, value=None, units=None):
        value = float(value)
        clipperHeight = self._clipper.winfo_height()
        frameHeight = self._frameHeight

        _startY = self._startY

        if mode is None:
            return self.yscrollbar.get()
        elif mode == 'moveto':
            self._startY = value * frameHeight
        else:  # mode == 'scroll'
            if units == 'units':
                jump = int(clipperHeight * self._jfraction)
            else:
                jump = clipperHeight
            self._startY = self._startY + value * jump

        if frameHeight <= clipperHeight:
            # The scrolled frame is smaller than the clipping window.

            self._startY = 0
            hi = 1.0
            # use expand by default
            relheight = 1
        else:
            # The scrolled frame is larger than the clipping window.
            # use expand by default
            if self._startY + clipperHeight > frameHeight:
                self._startY = frameHeight - clipperHeight
                hi = 1.0
            else:
                if self._startY < 0:
                    self._startY = 0
                hi = (self._startY + clipperHeight) / frameHeight
            relheight = ''

        if self._startY != _startY:
            # Position frame relative to clipper.
            self.innerframe.place(y=-self._startY, relheight=relheight)

        lo = self._startY / frameHeight
        self.yscrollbar.set(lo, hi)
예제 #23
0
    class Monitor(Frame):
        def __init__(self, parent, port, baud_rate, ser, toolchain, bii):
            '''
            Params:
                parent: The parent Frame
                port: string
                baud_rate:
                ser: serial
            '''

            Frame.__init__(self, parent)
            self.parent = parent
            self.port = port
            self.baud_rate = baud_rate
            self.ser = ser
            self.toolchain = toolchain
            self.bii = bii
            self.initUI()

        def initUI(self):
            self.parent.title("Biicode serial monitor %s" % self.port)
            self.style = Style()  # We need to define a style, otherwhise seems flat whit in macos
            self.style.theme_use(get_style())
            for x in range(1):
                Grid.columnconfigure(self, x, weight=1)
            for y in [1, 2]:
                Grid.rowconfigure(self, y, weight=1)

            self._make_top_bar()
            self._make_user_input()
            self._make_rcv_log()
            self._make_button_bar()

            self.pack(fill=BOTH, expand=1)

            self.serial_buffer = ""
            self.count = 0
            self.running = True
            self.after(50, self.read_serial)  # check serial again soon

        def _make_top_bar(self):
            menubar = Menu(self.parent)
            filemenu = Menu(menubar, tearoff=0)
            biimenu = Menu(menubar, tearoff=0)
            editmenu = Menu(menubar, tearoff=0)

            biimenu.add_command(label="Work (Save and process)", command=self.bii.work)
            biimenu.add_command(label="Find", command=self.bii.find)
            menubar.add_cascade(label="bii", menu=biimenu)

            filemenu.add_command(label="Flash code", command=self.upload)
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.parent.quit)
            menubar.add_cascade(label="File", menu=filemenu)

            editmenu.add_command(label="Clear", command=self.clear)
            # editmenu.add_separator()
            menubar.add_cascade(label="Edit", menu=editmenu)
            self.parent.config(menu=menubar)

        def _make_button_bar(self):
            self.button_upload = Button(self, text="Flash code", command=self.upload)
            self.button_upload.style = self.style
            self.button_upload.grid(row=0, column=0, padx=2, pady=2)

            self.baud_rate = 9600
            self.button_combobox = Combobox(self)
            self.button_combobox.bind("<<ComboboxSelected>>", self._update_baud_rate)
            bauds = (300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200)
            self.button_combobox['values'] = bauds
            self.button_combobox.current(4)
            self.button_combobox.grid(row=3, column=1, padx=2, pady=2)

        def _make_user_input(self):
            # make user input
            self.user_input = Text(self, width=52, height=3, takefocus=1,
                                   borderwidth=1, relief='ridge')
            self.user_input.grid(row=1, column=0, padx=2, pady=2, sticky=N + S + E + W)

            # make send button
            self.button_send = Button(self, text="Send", command=self.send_clicked)
            self.button_send.style = self.style
            self.button_send.grid(row=1, column=1, padx=2, pady=2, sticky=N + S + E + W)

        def _make_rcv_log(self):
            # make receive log
            recvLogFrame = Frame(self, width=400, height=200)
            recvLogFrame.style = self.style
            recvLogFrame.grid(row=2, column=0, padx=2, pady=2, sticky=N + S + E + W)
            self.start_stop_button = Button(self, text="Stop", command=self.start_stop_clicked)
            self.start_stop_button.style = self.style
            self.start_stop_button.grid(row=2, column=1, padx=2, pady=2, sticky=N + S + E + W)

            # make a scrollbar
            self.scrollbar = Scrollbar(recvLogFrame)
            self.scrollbar.pack(side=RIGHT, fill=Y)

            # make a text box to put the serial output
            self.log = Text(recvLogFrame, width=50, height=30, takefocus=0,
                            borderwidth=1, relief='ridge')
            self.log.pack(fill=BOTH, expand=True)

            # attach text box to scrollbar
            self.log.config(yscrollcommand=self.scrollbar.set)
            self.scrollbar.config(command=self.log.yview)

        def send_clicked(self):
            data = str(self.user_input.get(1.0, "end-1c") + '\0')
            self.ser.write(data)
            self._log(data)
            self.user_input.delete(1.0, END)

        def _log(self, msg):
            # if platform.system() == 'Darwin':
            #    print '>> %s' % msg
            # else:
            self.log.insert(END, '\n>> %s' % msg)
            self.log.yview(END)
            self.update_idletasks()

        def clear(self):
            self.log.delete(1.0, END)
            self.update_idletasks()

        def start_stop_clicked(self):
            if self.running:
                self.running = False
                self.start_stop_button['text'] = 'Start'
            else:
                self.running = True
                self.start_stop_button['text'] = 'Stop'
                self.read_serial()  # check serial again soon

        def upload(self):
            self.bii.work()
            try:
                if platform.system() == 'Darwin':
                    self.toolchain.upload()
                else:
                    self.ser.close()
                    self.toolchain.upload()
                    self.ser.open()
                self._log('** Code uploaded **')
            except BiiException:
                self._log('** Code upload failed **')

        def _update_baud_rate(self, event=None):
            new_rate = self.button_combobox.get()
            if new_rate != self.baud_rate:
                self.baud_rate = new_rate
                self.ser.setBaudrate(new_rate)
                logger.debug('Updated serial speed to %s' % new_rate)
                self.update_idletasks()

        def read_serial(self):
            self.log.update()  # display input text

            self._read_character()
            if self.running:
                self.after(100, self.read_serial)  # check serial again soon
            self.after(100, self.update_idletasks)

        def _read_character(self):
            try:
                c = self.ser.read()  # attempt to read a character from Serial
            except SerialException as e:
                logger.error("Couldn't read serial port: %s" % str(e))
                return

            # was anything read?
            while len(c) > 0 and c != '\r':
                # get the buffer from outside of this function
                # check if character is a delimeter
                if c == '\r':
                    c = ''  # don't want returns. chuck it
                if c == '\n':
                    # self.serial_buffer += "\n"  # add the newline to the buffer
                    self.log.insert(END, "\n")
                    self.log.insert(END, self.serial_buffer)
                    self.log.yview(END)
                    self.update_idletasks()
                    self.serial_buffer = ""  # empty the buffer
                else:
                    self.serial_buffer += c  # add to the buffer
                c = self.ser.read()