def _init_menu(self):

        self._menubar = Menu(self._parent)
        menubar = self._menubar
        self._parent.config(menu=menubar)

        #new_menu = Menu(menubar, tearoff=0)
        #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface)

        file_menu = Menu(menubar, tearoff=0)
        #file_menu.add_cascade(label="New", menu=new_menu)
        file_menu.add_command(label="Octagon", command=self.add_octagon)
        file_menu.add_command(label="MegaWollmilchsau",
                              command=self.add_mega_wollmilchsau)
        file_menu.add_separator()
        file_menu.add_command(label="About", command=self.on_about)
        file_menu.add_command(label="Export PostScript",
                              command=self.on_export)
        file_menu.add_command(label="Exit",
                              command=self.exit,
                              accelerator="Alt+F4")
        menubar.add_cascade(label="File", underline=0, menu=file_menu)

        self._surface_menu = Menu(menubar, tearoff=0)
        self._selected_surface = IntVar()
        self._selected_surface.set(-1)
        menubar.add_cascade(label="Surface",
                            underline=0,
                            menu=self._surface_menu)
        self._surface_menu.add_radiobutton(label="None",
                                           command=self.menu_select_surface,
                                           variable=self._selected_surface,
                                           value=-1)
Example #2
0
    def initUI(self):

        self.parent.title("MyStock")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        submenu= Menu(fileMenu)
        submenu.add_command(label="New feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label='Import', menu=submenu, underline=0)

        fileMenu.add_separator()

        closeButton = Button(self, text="Close", command=self.quit)
        closeButton.pack(side=RIGHT, padx=5, pady=5)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)

        self.pack(fill=BOTH, expand=1)
        self.centerWindow()
Example #3
0
	def __add_menu_item( self, o_config, s_menu_label ):

		#this will be the menu labeled s_menu_label (ex: "File" menu)
		#and the command items (like "Open" or "Save""Save") are then added
		#to this item using the o_config objects options:
		o_this_menu = Menu( self.__menubar, tearoff = self.__tearoff ) 

		ld_args = self.get_add_command_params_and_args(  o_config, s_menu_label )

		for d_args in ld_args:
			if d_args[ "label" ] == "sep":
				o_this_menu.add_separator()
			else:
				o_this_menu.add_command( **d_args )
			#end if seperator, else sub menu
		#end for each set of args

		dv_menu_values = self.__get_menu_values( o_config, s_menu_label )

		s_accel = dv_menu_values[ "accelerator" ] if dv_menu_values[ "accelerator" ] is not None  else None

		self.__menubar.add_cascade( label = s_menu_label, 
			menu = o_this_menu, 
			underline=dv_menu_values[ "underline" ],
			accelerator=s_accel )
		return
Example #4
0
 def setupWidgets(self):
     menubar = Menu(self.root)
     filemenu = Menu(menubar, tearoff=0)
     filemenu.add_command(label="New", command=lambda: self.donothing())
     filemenu.add_command(label="Open", command=lambda: self.chooseFile())
     filemenu.add_command(label="Save", command=lambda: self.donothing())
     filemenu.add_command(label="Save as...", command=lambda: self.donothing())
     filemenu.add_command(label="Close", command=lambda: self.donothing())
     
     filemenu.add_separator()
     
     filemenu.add_command(label="Exit", command=lambda: self.quitCallBack())
     menubar.add_cascade(label="File", menu=filemenu)
     editmenu = Menu(menubar, tearoff=0)
     editmenu.add_command(label="Undo", command=lambda: self.donothing())
     
     helpmenu = Menu(menubar, tearoff=0)
     helpmenu.add_command(label="Help Index", command=lambda: self.donothing())
     helpmenu.add_command(label="About...", command=lambda: self.donothing())
     menubar.add_cascade(label="Help", menu=helpmenu)
     
     self.root.config(menu=menubar)
     
     # label for the video frame
     self.videoLabel = tk.Label(master=self.root)
     self.videoLabel.bind("<Button-1>", lambda e: self.handleVideoClick())
     self.videoLabel.pack()
    def _init_menu(self):
        
        self._menubar = Menu(self._parent)
        menubar=self._menubar
        self._parent.config(menu=menubar)
        
        #new_menu = Menu(menubar, tearoff=0)
        #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface)
        
        file_menu = Menu(menubar, tearoff=0)
        #file_menu.add_cascade(label="New", menu=new_menu)
        file_menu.add_command(label="Octagon", command=self.add_octagon)
        file_menu.add_command(label="MegaWollmilchsau", command=self.add_mega_wollmilchsau)
        file_menu.add_separator()
        file_menu.add_command(label="About", command=self.on_about)
        file_menu.add_command(label="Export PostScript", command=self.on_export)
        file_menu.add_command(label="Exit", command=self.exit, accelerator="Alt+F4")
        menubar.add_cascade(label="File", underline=0, menu=file_menu)

        self._surface_menu = Menu(menubar, tearoff=0)
        self._selected_surface = IntVar()
        self._selected_surface.set(-1)
        menubar.add_cascade(label="Surface", underline=0, menu=self._surface_menu)
        self._surface_menu.add_radiobutton(label="None", 
            command=self.menu_select_surface, variable=self._selected_surface, 
            value=-1)
Example #6
0
def build_root():

	ui_root = Tk()

	# Build root drop-down menu and immediate child menus.
	main_menu = Menu(ui_root)
	file_submenu = Menu(main_menu, title="File")
	settings_submenu = Menu(main_menu, title="Settings")
	help_submenu = Menu(main_menu, title="Help")

	# File
	file_submenu.add_command(label="New Dataset...", command=dummy)
	file_submenu.add_command(label="Open...", command=dummy)
	file_submenu.add_command(label="Export...", command=dummy)
	file_submenu.add_separator()
	file_submenu.add_command(label="Quit", command=dummy)

	# Settings
	settings_submenu.add_command(label="PyNewhall Settings...", command=dummy)

	# Help
	help_submenu.add_command(label="About...", command=dummy)
	help_submenu.add_command(label="Documentation...", command=dummy)

	# Wrap up building main drop down menubar.
	main_menu.add_cascade(label="File", menu=file_submenu)
	main_menu.add_cascade(label="Settings", menu=settings_submenu)
	main_menu.add_cascade(label="Help", menu=help_submenu)
	ui_root.config(menu=main_menu)

	ui_root.mainloop()
Example #7
0
    def createMenubar( self ):
        "Create our menu bar."

        font = self.font

        mbar = Menu( self.top, font=font )
        self.top.configure( menu=mbar )

        # Application menu
        appMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label=self.appName, font=font, menu=appMenu )
        appMenu.add_command( label='About MiniEdit', command=self.about,
                             font=font)
        appMenu.add_separator()
        appMenu.add_command( label='Quit', command=self.quit, font=font )

        #fileMenu = Menu( mbar, tearoff=False )
        #mbar.add_cascade( label="File", font=font, menu=fileMenu )
        #fileMenu.add_command( label="Load...", font=font )
        #fileMenu.add_separator()
        #fileMenu.add_command( label="Save", font=font )
        #fileMenu.add_separator()
        #fileMenu.add_command( label="Print", font=font )

        editMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label="Edit", font=font, menu=editMenu )
        editMenu.add_command( label="Cut", font=font,
                              command=lambda: self.deleteSelection( None ) )

        runMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label="Run", font=font, menu=runMenu )
        runMenu.add_command( label="Run", font=font, command=self.doRun )
        runMenu.add_command( label="Stop", font=font, command=self.doStop )
        runMenu.add_separator()
        runMenu.add_command( label='Xterm', font=font, command=self.xterm )
    def __init__(self, namespace):
        Tk.__init__(self, className="Koshka")

        self.dac = DAC()
        self.dac.start()

        self.score_path = namespace.score

        self.sequencer = None
        self.sequencer_frame = None
        self.mixer_window = None
        self.scale_window = None
        self._open_score(self.score_path)

        menu = Menu(self)
        self.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Open...", command=self.open, accelerator="meta-o")
        filemenu.add_command(label="Save", command=self.save, accelerator="meta-s")
        filemenu.add_command(label="Save As...", command=self.save_as, accelerator="meta-shift-s")
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.quit)

        menu.add_cascade(label="Help", menu=filemenu)
        filemenu.add_command(label="Online Help...", command=lambda: webbrowser.open_new_tab(URL_HELP_DOC))

        # Note: This is only implemented and tested for Mac OS
        self.bind_all("<Command-o>", self.open)
        self.bind_all("<Command-s>", self.save)
        self.bind_all("<Command-Shift-s>", self.save_as)
        self.bind_all("<Meta-o>", self.open)
        self.bind_all("<Meta-s>", self.save)
        self.bind_all("<Meta-Shift-s>", self.save_as)
Example #9
0
        def __addComponents(components, node):
            componentlist = self.nodelist[node]['componentlist']
            ComponentMenu = self.nodelist[node]['menu']

            for comp in components:
                self.loginfo("Adding component '%s@%s'" % (comp, node))
                if self.autoscan.get() and comp not in componentlist:
                    self.scancomponent(comp, node)
                FuncMenu = Menu(ComponentMenu)
                FuncMenu.add_command(
                    label="Scan",
                    command=lambda
                    (name, node)=(comp, node): self.scancomponent(name, node))
                FuncMenu.add_command(
                    label="Copy Name",
                    command=lambda name=comp: self.copystring(name))
                FuncMenu.add_command(
                    label="Compose...",
                    command=lambda
                    (name, node)=(comp, node): self.composeMessage(name, node))
                FuncMenu.add_separator()
                FuncMenu = Menu(ComponentMenu)

                ComponentMenu.add_cascade(label=comp, menu=FuncMenu)
                componentlist[comp] = {'menu': FuncMenu}
Example #10
0
 def _setup_menu(self):
   """
   Creates the menu.
   """
   file_menu = Menu(self._menu, tearoff=0)
   file_menu.add_command(label='New', command=self._new_file,
       accelerator='Ctrl+N')
   file_menu.add_command(label='Open', command=self._open_file,
       accelerator='Ctrl+O')
   file_menu.add_command(label='Save', command=self._save_file,
       accelerator='Ctrl+S')
   file_menu.add_command(label='Save as', command=self._save_as)
   file_menu.add_separator()
   file_menu.add_command(label='Quit', command=self.board.quit,
       accelerator='Ctrl+Q')
   self._menu.add_cascade(label='File', menu=file_menu)
   edit_menu = Menu(self._menu, tearoff=0)
   edit_menu.add_command(label='Undo', command=self.board.undo,
       accelerator='Ctrl+Z')
   edit_menu.add_command(label='Redo', command=self.board.redo,
       accelerator='Ctrl+Y')
   edit_menu.add_command(label='Delete selected',
       command=self.board._delete_selected_items, accelerator='Delete')
   edit_menu.add_command(label='Rotate selected',
       command=self.board._rotate_selected_item, accelerator='r')
   edit_menu.add_command(label='Toggle cursor', command=self._toggle_cursor,
       accelerator='D')
   self._menu.add_cascade(label='Edit', menu=edit_menu)
   self._root.config(menu=self._menu)
Example #11
0
    def createMenubar( self ):
        "Create our menu bar."

        font = self.font

        mbar = Menu( self.top, font=font )
        self.top.configure( menu=mbar )

        # Application menu
        appMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label=self.appName, font=font, menu=appMenu )
        appMenu.add_command( label='About MiniEdit', command=self.about,
                             font=font)
        appMenu.add_separator()
        appMenu.add_command( label='Quit', command=self.quit, font=font )

        #fileMenu = Menu( mbar, tearoff=False )
        #mbar.add_cascade( label="File", font=font, menu=fileMenu )
        #fileMenu.add_command( label="Load...", font=font )
        #fileMenu.add_separator()
        #fileMenu.add_command( label="Save", font=font )
        #fileMenu.add_separator()
        #fileMenu.add_command( label="Print", font=font )

        editMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label="Edit", font=font, menu=editMenu )
        editMenu.add_command( label="Cut", font=font,
                              command=lambda: self.deleteSelection( None ) )

        runMenu = Menu( mbar, tearoff=False )
        mbar.add_cascade( label="Run", font=font, menu=runMenu )
        runMenu.add_command( label="Run", font=font, command=self.doRun )
        runMenu.add_command( label="Stop", font=font, command=self.doStop )
        runMenu.add_separator()
        runMenu.add_command( label='Xterm', font=font, command=self.xterm )
Example #12
0
 def file_menu():
     menu = Menu(menubar, tearoff=0)
     menu.add_command(label="Open ctxt / cbin", command=self.open_file)
     # menu.add_command(label="Append ctxt", command=self.append_file)
     menu.add_separator()
     menu.add_command(label="Exit", command=self.save_settings_and_quit)
     return menu
Example #13
0
    def initUI(self):
      
        self.parent.title("Simple CSV parser GUI")
        self.pack(fill=BOTH, expand=1)
        
        menu = Menu(self.parent)
        self.parent.config(menu=menu)
        
        filemenu = Menu(menu)
        menu.add_cascade(label="File"        , menu=filemenu)
        
        fileOpenMenu = Menu(filemenu)
        filemenu.add_cascade(label="Open..." , menu=fileOpenMenu)
        fileOpenMenu.add_command(label="CSV..." , command=self.open_reqCSVcommand)

        fileSaveMenu = Menu(filemenu)
        filemenu.add_cascade(label="Save..." , menu=fileSaveMenu)
        fileSaveMenu.add_command(label="CSV..." , command=self.save_reqCSVcommand)
        fileSaveMenu.add_command(label="DOX..." , command=self.save_reqDOXcommand)
        fileSaveMenu.add_command(label="MM..."  , command=self.save_reqMMcommand)
        
        filemenu.add_separator()
        filemenu.add_command(label="Exit"    , command=self.exit_command)
        
        helpmenu = Menu(menu)
        menu.add_cascade(label="Help"        , menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.about_command)
        # end of menu creation       
        
        self.txt = Text(self)
        self.txt.pack(fill=BOTH, expand=1)
Example #14
0
 def set_up_menu(self):
     ''' Sets up the menu bar and its submenus '''
     menubar = Menu(self.root)
     filemenu = Menu(menubar, tearoff=0)
     filemenu.add_command(label="About", command=self.about)
     filemenu.add_separator()
     filemenu.add_command(label="Exit", command=self.root.quit)
     menubar.add_cascade(label="File", menu=filemenu)
     self.root.config(menu=menubar)
    def __init__(self, root):

        self.canvas = Canvas(root, width = 400, height = 350)
        self.canvas.configure(cursor="crosshair")
        self.canvas.pack(expand=YES, fill=BOTH, side='right')

        self.canvas.bind("<Key>", self.handle_key)
        self.canvas.bind("<Double-Button-1>", self.set_focus)
        self.canvas.bind("<Button-1>", self.set_cursor)
        self.canvas.bind("<Return>", self.remove_highlight)

        self.image, self.ponto1, self.ponto2 = (None, None, None)

        self.menubar = Menu(root)

        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Open Image", command=self.openImage)
        filemenu.add_command(label="Save", command=self.hello)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=root.quit)
        self.menubar.add_cascade(label="File", menu=filemenu)

        editmenu = Menu(self.menubar, tearoff=0)
        for e in ("Cut","Copy","Paste"):
            editmenu.add_command(label=e, command=self.hello)

        self.menubar.add_cascade(label="Edit", menu=editmenu)

        filtermenu = Menu(self.menubar, tearoff=0)
        filtermenu.add_command(label="Threshold", command=self.thresholdFilter)
        self.menubar.add_cascade(label="Filter", menu=filtermenu)

        reportmenu = Menu(self.menubar, tearoff=0)
        reportmenu.add_command(label="Relatorio.txt",
        command=self.generateReport)
        reportmenu.add_command(label="Relatorio.pdf")
        reportmenu.add_command(label="Email")
        self.menubar.add_cascade(label="Report", menu=reportmenu)

        helpmenu = Menu(self.menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.hello)
        self.menubar.add_cascade(label="Help", menu=helpmenu)

        root.config(menu=self.menubar)

        self.toolbar = Frame(root)
        self.toolbar.pack(side='left', fill='both')
        clean = Label(self.toolbar, text='Clean')
        clean.bind("<Button-1>", self.clean)
        b = Label(self.toolbar, text='B')
        c = Label(self.toolbar, text='C')
        d = Label(self.toolbar, text='D')

        for w in (clean,b,c,d):
            w.configure(relief="groove", font="Times 12 bold")
            w.pack(fill='both')
Example #16
0
    def __init__(self, application):#, frame):
#    def __init__(self, tkroot, application):#, frame):

        # Keep a reference to the input frame
#        frame = frame

#        d = Detector(Detector.SOUTH_SMALL)

        # Create the menu bar and add it to the tkroot

        menu = Menu(application)
        application.config(menu = menu)
#        menu = Menu(tkroot)
#        tkroot.config(menu = menu)

        # Create the various drop-downs - file, edit...

        # Create the "file" menu, with commands like "Open" and "Quit"
        file_menu = Menu(menu)
#        file_menu.add_command(label = 'greeting', command = application.say_hi)
#        file_menu.add_command(label = 'insult', command = application.say_insult)
        file_menu.add_command(label = 'Save', command=application.save_all)
        file_menu.add_command(label = 'Export ROOT file', command=application.save_root)
        file_menu.add_command(label = 'Export PostScript file', command=application.save_postscript)
        file_menu.add_command(label = 'Open', command=application.read_input)
        file_menu.add_separator()
        file_menu.add_command(label = 'Quit', command = application.exit)
#        file_menu.add_command(label='Dialog', menu=open_dialog)

        # Creates the "edit" menu
        view_menu = Menu(menu)
#        view_menu.add_command(label='Change small cells',
#                                   command = application.calibrate_all_small)
        view_menu.add_command(label = 'NSTB', command = application.image_window.display_detector)
        view_menu.add_command(label = 'QT Slots', command = application.image_window.display_qt_boards)
        view_menu.add_separator()
        view_menu.add_command(label = 'Large Cell Voltages', command = application.image_window.display_large_voltage)
        view_menu.add_command(label = 'Small Cell Voltages', command = application.image_window.display_small_voltage)
        view_menu.add_command(label = 'Bitshifts', command = application.image_window.display_qt_bitshift)
        view_menu.add_command(label = 'Gains', command = application.image_window.display_gain)
        # Add a drop-down sub-menu to edit allowing to change
        # either all the small or all the large voltages using
        # an input file.
#        edit_change_submenu = Menu(view_menu);
#        edit_change_submenu.add_command(label='Change small cells',
#                                   command = application.calibrate_all_small)
#        edit_change_submenu.add_command(label='Change large cells',
#                                   command = application.calibrate_all_small)

        edit_menu = Menu(menu)
        edit_menu.add_command(label='Modify gains', command=application.apply_corrections_from_file)

        # Add each drop-down to its parent
        menu.add_cascade(label = 'File', menu = file_menu)
        menu.add_cascade(label = 'View', menu = view_menu)
        menu.add_cascade(label = 'Edit', menu = edit_menu)
Example #17
0
def getClassificationMenu(main_frame, menu_bar):
    menu = Menu(menu_bar, tearoff=0)

    menu.add_command(label='Perceptron classification',
                     command=main_frame.on_apply_perceptron_algorithm)
    menu.add_command(label='SOM classification',
                     command=main_frame.on_apply_som_algorithm)

    menu.add_separator()
    menu.add_command(label='K-means classification',
                     command=main_frame.on_apply_k_means_algorithm)

    return menu
Example #18
0
def getClassificationMenu(main_frame, menu_bar):
    menu = Menu(menu_bar, tearoff=0)
    
    menu.add_command(label = 'Perceptron classification',
                     command = main_frame.on_apply_perceptron_algorithm)
    menu.add_command(label = 'SOM classification', 
                     command = main_frame.on_apply_som_algorithm)
    
    menu.add_separator()
    menu.add_command(label = 'K-means classification',
                     command = main_frame.on_apply_k_means_algorithm)
    
    return menu
def createmenubar(_root_window_, _listofentriesdicts_):
    ''' under development 
    input format example: 
        <class app>
        [{ 'title' : 'Title1', 'title_com' : (print , '>command11<') },
        { 'title' : 'Title2',
        'cascade' : (('cnd_label' ,'>command31<'),('cnd_label' ,'>command33<'),
        ('separator'),('cnd_label' ,'>command33<'))}]
    '''
    # using list of list instead dict because an order is needed
    # First create the menu bar
    menu_bar = Menu(_root_window_)  # menubar "object"
    _root_window_.config(menu=menu_bar)

    for i in range(len(_listofentriesdicts_)):
        entry_dict = _listofentriesdicts_[i]
        if 'title_com' in entry_dict.keys():
            _com_ = entry_dict['title_com']
            if len(_com_) > 1:
                menu_bar.add_command(label=entry_dict['title'],
                                     command=(lambda com=_com_: com[0]
                                              (com[1])))
            else:
                menu_bar.add_command(label=entry_dict['title'],
                                     command=_com_[0])

        elif 'cascade' in entry_dict.keys():
            # allocating space
            sub_menu = Menu(menu_bar)
            # Create a menu button labeled "File" as example, that brings up a
            # menu this comes in the entry_dict['title']
            if 'titlei' in entry_dict.keys():
                menu_bar.add_cascade(image=entry_dict['titlei'], menu=sub_menu)
            else:
                menu_bar.add_cascade(label=entry_dict['title'], menu=sub_menu)
            # Create cascades in menus
            content = entry_dict['cascade']
            for cc in range(len(content)):
                _ccc_ = content[cc]

                if len(_ccc_) == 3:
                    sub_menu.add_command(label=content[cc][0],
                                         command=(lambda com=_ccc_: _ccc_[1]
                                                  (_ccc_[2])))
                elif len(_ccc_) == 2:
                    sub_menu.add_command(label=content[cc][0],
                                         command=_ccc_[1])
                else:
                    sub_menu.add_separator()
        else:
            print ' - incomplete data - '
Example #20
0
class FileMenu(object):
    def __init__(self, main_frame, menu_bar):
        self.menu = Menu(menu_bar, tearoff=0)
        
        self.menu.add_command(label = 'Open image', 
                              command = main_frame.on_open_image)
        self.menu.add_command(label = 'Save classified image', 
                              command = main_frame.on_save_classified_image)
        
        self.menu.add_separator()
        
        self.menu.add_command(label = 'Exit', 
                              command = main_frame.on_exit_from_application)
        
    def get(self):
        return self.menu
Example #21
0
    def init_components(self):
        menu_bar = Menu(self.top, font=self.font)

        self.top.configure(menu=menu_bar)
        # self.top.attributes('-fullscreen', True)
        self.top.geometry('{0}x{1}+0+0'.format(self.top.winfo_screenwidth() - 200, self.top.winfo_screenheight() - 200))

        file_menu = Menu(menu_bar, tearoff=0, font=self.font)

        file_menu.add_command(label="Start Hsm", command=self.start_hsm)
        file_menu.add_command(label="Stop Hsm", command=self.stop_hsm)

        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=self.exit)

        menu_bar.add_cascade(label="File", menu=file_menu, font=self.font)
Example #22
0
class FileMenu(object):
    def __init__(self, main_frame, menu_bar):
        self.menu = Menu(menu_bar, tearoff=0)

        self.menu.add_command(label='Open image',
                              command=main_frame.on_open_image)
        self.menu.add_command(label='Save classified image',
                              command=main_frame.on_save_classified_image)

        self.menu.add_separator()

        self.menu.add_command(label='Exit',
                              command=main_frame.on_exit_from_application)

    def get(self):
        return self.menu
Example #23
0
    def initUI(self):

        self.parent.title("Typesetting")

        self.min_margin = 10
        self.max_margin = 100
        self.margin_value = self.min_margin
        self.words = []

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.openfile)
        fileMenu.add_command(label="Clear", command=self.clear)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        grid = Frame(self.parent)
        left_grid = Frame(grid)
        w_list_label = Label(left_grid,text="Lista de palabras")
        w_list_label.pack(side=TOP)
        self.w_list = MultiListbox(left_grid,(("Palabra",20),("Longitud",10)))
        self.w_list.pack(side=BOTTOM,fill=BOTH,expand=TRUE)
        left_grid.pack(side=LEFT,fill=BOTH,expand=TRUE)


        right_grid = Frame(grid)
        up_grid = Frame(right_grid)
        margin_label = Label(up_grid,text="Margen")
        margin_label.pack(side=LEFT,expand=TRUE)
        self.margin_scale = Scale(up_grid,orient=HORIZONTAL,showvalue=0,\
            variable=self.margin_value,from_=self.min_margin,to=self.max_margin,
            command=self.refresh_margin)
        self.margin_scale.pack(side=LEFT)
        self.margin_spinbox = Spinbox(up_grid,\
            textvariable=self.margin_value,from_=self.min_margin,to=self.max_margin)
        self.margin_spinbox.pack(side=LEFT)
        typeset_btn = Button(up_grid, text ="Typeset", command =self.typeset)
        typeset_btn.pack(side=RIGHT)
        up_grid.pack(side=TOP)

        self.text = Text(right_grid)
        self.text.pack(side=BOTTOM,fill=BOTH,expand=TRUE)
        right_grid.pack(side=RIGHT,fill=BOTH)
        grid.pack(fill=BOTH, expand=YES)
Example #24
0
    def __init__(self, gui, master):
        self.gui = gui
        menu = Menu(master)
        master.config(menu=menu)
        subMenu = Menu()
        menu.add_cascade(label="File", menu=subMenu)
        subMenu.add_command(label="Open image file", command=self.open_file)
        subMenu.add_command(label="Open file list", command=self.file_list)
        subMenu.add_separator()
        subMenu.add_command(label="Printing Window",
                            command=self.printing_window)
        subMenu.add_separator()
        subMenu.add_command(label="Exit", command=self.exit)

        editMenu = Menu(menu)
        menu.add_cascade(label="Help", menu=editMenu)
        editMenu.add_command(label="About", command=self.about)
Example #25
0
File: TkAdmin.py Project: ri0t/cape
    def __handleNewNode(self, node):
        if node not in self.nodelist:
            self.loginfo("New node appeared! Hmm.")
        else:       
            self.loginfo("Node rescanned.")
            print self.__MenuNodes   
            
        componentlist = {}
        ComponentMenu = Menu(self.__MenuNodes)
        ComponentMenu.add_command(label="Scan", command=lambda node=node: self.scanregistry(node))
        ComponentMenu.add_command(label="Copy Name", command=lambda node=node: self.copystring(node))
        ComponentMenu.add_separator()

        nodeinfo = {'componentlist': componentlist,
                    'menu': ComponentMenu}
            
        self.nodelist[node] = nodeinfo
Example #26
0
File: TkAdmin.py Project: ri0t/cape
        def __addComponents(components, node):
            componentlist = self.nodelist[node]['componentlist']
            ComponentMenu = self.nodelist[node]['menu']
            
            for comp in components:
                self.loginfo("Adding component '%s@%s'" % (comp, node))
                if self.autoscan.get() and comp not in componentlist:
                    self.scancomponent(comp, node)
                FuncMenu = Menu(ComponentMenu)
                FuncMenu.add_command(label="Scan", command=lambda (name,node)=(comp, node): self.scancomponent(name, node))
                FuncMenu.add_command(label="Copy Name", command=lambda name=comp: self.copystring(name))
                FuncMenu.add_command(label="Compose...", command=lambda (name,node)=(comp,node): self.composeMessage(name, node))
                FuncMenu.add_separator()
                FuncMenu = Menu(ComponentMenu)

                ComponentMenu.add_cascade(label=comp, menu=FuncMenu)
                componentlist[comp] = {'menu': FuncMenu}
Example #27
0
    def initUI(self):

        self.parent.title("PC Nexus Access 1.1a")
        menubar = Menu(self.parent)
        fname='/root/scripts/script.txt'
        self.parent.config(menu=menubar)
        #   st=ScrolledText(root)

        # multimenu and items

        multimenu = Menu(menubar, fg='Blue', tearoff=0)
        multimenu.add_command (label="script",  underline = 0, command=self.display_script)
        multimenu.add_command (label="run",     underline = 1, command=self.display_runlog )      
        multimenu.add_separator()
        multimenu.add_command (label="mscript", underline = 1, command=self.display_mscript)
        multimenu.add_command (label="mrun",    underline = 1, command=self.display_mrunlog)
        multimenu.add_separator()
        multimenu.add_command (label="close",   underline = 0, command=self.close)

        menubar.add_cascade   (label="File",    underline = 1, menu=multimenu  )                              

        #   File menu and menu items
        
        fileMenu = Menu(menubar, fg='Yellow', bg='Blue',tearoff=0)
        fileMenu.add_command (label="Multi",   underline = 0, command=self.run_multiscript)   
        fileMenu.add_command (label='Host0',   underline = 0, command=self.run_host0)           
        fileMenu.add_command (label='Host1',   underline = 0, command=self.run_host1)
        fileMenu.add_command (label='Host2',   underline = 0, command=self.run_host2)
        menubar.add_cascade  (label="Script",  underline = 1, menu=fileMenu   )

        # fileMenu.add_separator()

        menubar.add_command (label="Queues",   underline = 1, command = self.get_queue )                  

        interfacemenu = Menu(menubar,tearoff=0)
        interfacemenu.add_command (label="All  ", underline = 1, command=self.get_interface)                     
        interfacemenu.add_command (label="up   ", underline = 1, command=self.get_interface_up)                     
        interfacemenu.add_command (label="down ", underline = 1, command=self.get_interface_down)
        interfacemenu.add_command (label="vlan ", underline = 1, command=self.get_interface_vlan)
       
        menubar.add_cascade (label="Interface", underline = 1, menu=interfacemenu)                     

        menubar.add_command (label="Buffers",   underline = 1, command=self.get_BMdata)                        
        menubar.add_command (label="Routing",   underline = 1, command=self.get_routing)
        menubar.add_command (label="TCP Sockets",underline = 1, command=self.get_tcp_sockets)     
        menubar.add_command (label="About",     underline = 1, command=self.nexus_about) 
Example #28
0
    def __init__(self,  file_path = ''):
        self.file_path = file_path
        self.root = Tk(className = 'MockViewer')
        self.text_pad = ScrolledText.ScrolledText(self.root,  width = 300,  height = 200)

        self.menu = Menu(self.root)
        self.root.config(menu = self.menu)

        file_menu = Menu(self.menu)
        file_menu.add_command(label = 'Open',  command = self.open_doc_from_dlg)
        file_menu.add_command(label = 'Print to default printer.', command = self.print_doc)
        file_menu.add_separator()
        file_menu.add_command(label = 'Exit...',  command = self.exit)

        self.menu.add_cascade(label = 'File',  menu = file_menu)

        self.text_pad.pack()
Example #29
0
    def __init__(self,parent=None, width = 800, height = 50):
        """
        Initialise / crée le menu
        """
        Frame.__init__(self,borderwidth=2)

        #Vars
        self.parent = parent
        self.fileOpened = None

        mbuttonFile = Menubutton(self,text='Fichier')
        #mbuttonFile.grid(row=0, column=0)
        mbuttonFile.pack(side=LEFT)
        menuFile=Menu(mbuttonFile)
        menuFile.add_command(label='Nouveau',command=self.new)
        menuFile.add_separator()
        menuFile.add_command(label='Sauvegarder',command=self.save)
        menuFile.add_command(label='Sauvegarder sous...',command=self.saveAs)
        menuFile.add_command(label='Charger...',command=self.load)
        menuFile.add_separator()

        #Search for an exit function on the parent, or take the default one from MenuBar class if not found
        try:
            menuFile.add_command(label='Quitter',command=self.parent.exit)
        except AttributeError:
            menuFile.add_command(label='Quitter',command=self.exit)
            
        mbuttonFile.configure(menu=menuFile)

        mbuttonHelp = Menubutton(self,text='Aide')
        #mbuttonHelp.grid(row=0, column=1)
        mbuttonHelp.pack(side=RIGHT)
        menuHelp = Menu(mbuttonHelp)
        menuHelp.add_command(label='Aide',command=self.infos)
        menuHelp.add_command(label='A propos',command=self.aPropos)
        mbuttonHelp.configure(menu=menuHelp)

        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('text files', '.txt'),('all files', '.*')]
        options['initialdir'] = 'C:\\'
        options['initialfile'] = 'save.txt'
        options['parent'] = parent
        options['title'] = 'Choissisez le fichier'
Example #30
0
    def initUI(self):

        self.parent.title("Submenu")

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="New")
        submenu.add_command(label="Open")
        fileMenu.add_cascade(label="Files", menu=submenu)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=fileMenu)
Example #31
0
    def __handleNewNode(self, node):
        if node not in self.nodelist:
            self.loginfo("New node appeared! Hmm.")
        else:
            self.loginfo("Node rescanned.")
            print self.__MenuNodes

        componentlist = {}
        ComponentMenu = Menu(self.__MenuNodes)
        ComponentMenu.add_command(
            label="Scan", command=lambda node=node: self.scanregistry(node))
        ComponentMenu.add_command(
            label="Copy Name", command=lambda node=node: self.copystring(node))
        ComponentMenu.add_separator()

        nodeinfo = {'componentlist': componentlist, 'menu': ComponentMenu}

        self.nodelist[node] = nodeinfo
Example #32
0
    def initUI(self):
        self.parent.title("SubMenu")

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu= Menu(fileMenu)
        submenu.add_command(label="New feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label="Import", menu= submenu, underline=0)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit",underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
Example #33
0
    def set_up_menu_bar(self):
        ''' Sets up the main menu bar and submenus '''
        menubar = Menu(self.root)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        filemenu.add_command(label="Save as", command=self.save_as_file)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.quit)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.about)

        menubar.add_cascade(label="File", menu=filemenu)
        menubar.add_cascade(label="Help", menu=helpmenu)

        self.root.config(menu=menubar)
Example #34
0
    def initUI(self):

        self.parent.title("Submenu")

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="New feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label='Import', menu=submenu, underline=0)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
Example #35
0
        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)
Example #36
0
        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)
Example #37
0
    def initUI(self):
        self.title("Firewall Configuration")
        menubar = Menu(self)
        self.config(menu=menubar)
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Apply")
        fileMenu.add_command(label="Reload")
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit",command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)
	optionsMenu = Menu(menubar)
	optionsMenu.add_command(label="Start Configuration Wizard", state=DISABLED)
	optionsMenu.add_separator()
	optionsMenu.add_command(label="Enable Firewall", command=self.onEnable)
	optionsMenu.add_command(label="Disable Firewall", command=self.onDisable, state=DISABLED)
	menubar.add_cascade(label="Options", menu=optionsMenu)

	helpMenu = Menu(menubar)
	helpMenu.add_command(label="About", command=self.onAbout)
	menubar.add_cascade(label="Help", menu=helpMenu)
Example #38
0
    def createMenu(self):       
        """
        Creates GUI components and register events
        """
        self.menubar = Menu(self.root)
        self.dbfdata = None
        
        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.__openShpfile)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.quit)
        self.menubar.add_cascade(label="File", menu=filemenu)
        
        self.attibmenu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label="Attibutes", menu=self.attibmenu,state='disabled')

        #Sagar Jha
        self.menubar.add_cascade(label="Simulator",command=self.__simulate) 
        #Added Simulator 
        
        self.root.config(menu=self.menubar)
Example #39
0
    def add_menubar(self, parent):
        """ Add menubar to figure """
        menubar = Menu(parent)

        # create a pulldown menu, and add it to the menu bar
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_current)
        filemenu.add_separator()

        filemenu.add_command(label="Exit", command=self.exit)
        menubar.add_cascade(label="File", menu=filemenu)

        # create more pulldown menus
        toolmenu = Menu(menubar, tearoff=0)
        toolmenu.add_command(label="Open Toolbox", command=self.dq_tools)
        menubar.add_cascade(label="Tools", menu=toolmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Show Help", command=self.help_file)
        menubar.add_cascade(label="Help", menu=helpmenu)

        # submenu
        cmapmenu = Menu(toolmenu, tearoff=0)
        cmapmenu.add_radiobutton(
            label='Grey',
            variable=self.cmap,
            value='gist_yarg')
        cmapmenu.add_radiobutton(
            label='Prism',
            variable=self.cmap,
            value='prism')
        cmapmenu.add_radiobutton(label='Jet', variable=self.cmap, value='jet')
        cmapmenu.add_radiobutton(
            label='Ncar',
            variable=self.cmap,
            value='gist_ncar')
        toolmenu.insert_cascade(index=2, label='Select Cmap', menu=cmapmenu)

        return menubar
Example #40
0
 def __init__(self):
     self.window = Tk()
     self.window.title("Dimens Convert Tool")
     windowW = 420
     if (platform.system() == "Windows"):
         windowW = 420
     else:
         windowW = 490
     self.window.minsize(windowW, 355)
     self.center_wind(self.window, windowW, 355)
     frame = Frame(self.window)
     frame.pack()
     config_path = os.path.split(
         os.path.realpath(__file__))[0] + "/" + "configs.ini"
     self.rootDir = os.path.split(os.path.realpath(__file__))[0]
     self.config_path = config_path
     conf = ConfigUtils.Config(config_path)
     self.conf = conf
     fontSize = 35
     menubar = Menu(self.window)
     helpmenu = Menu(menubar, tearoff=0)
     helpmenu.add_command(label="使用方法", command=self.help)
     helpmenu.add_separator()
     helpmenu.add_command(label="关于", command=self.about)
     menubar.add_cascade(label="帮助", menu=helpmenu)
     self.window.config(menu=menubar)
     index = 0
     designDevice = DesignDevice.Design(conf, index, frame, fontSize,
                                        self.rootDir)
     index = designDevice.layout()
     self.designDevice = designDevice
     targetDevice = TargetDevice.Design(conf, index, frame, fontSize)
     index = targetDevice.layout()
     self.targetDevice = targetDevice
     btApply = Button(frame, text="生成", command=self.processButtonGeneral)
     btApply.grid(row=index + 1, column=1, columnspan=2)
     btCancel = Button(frame, text="取消", command=self.processButtonCancel)
     btCancel.grid(row=index + 1, column=2, columnspan=2)
     # 监测事件直到window被关闭
     self.window.mainloop()
Example #41
0
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        menu = Menu()
        parent.config(menu=menu)

        gameMenu = Menu(menu)
        menu.add_cascade(label="File", menu=gameMenu)
        gameMenu.add_command(label="New Player", command=self.dont)
        gameMenu.add_command(label="Open Player", command=self.dont)
        gameMenu.add_command(label="Save Player", command=self.dont)
        gameMenu.add_command(label="Delete Player", command=self.dont)
        gameMenu.add_separator()
        gameMenu.add_command(label="Exit", command=self.dont)

        helpMenu = Menu(menu)

        menu.add_cascade(label="Edit", menu=helpMenu)
        helpMenu.add_command(label="Help", command=self.dont)
        helpMenu.add_command(label="Credits", command=self.dont)
        gameMenu.add_separator()
        helpMenu.add_command(label="About", command=self.dont)
Example #42
0
 def _setup_menu(self):
     """
 Creates the menu.
 """
     file_menu = Menu(self._menu, tearoff=0)
     file_menu.add_command(label='New',
                           command=self._new_file,
                           accelerator='Ctrl+N')
     file_menu.add_command(label='Open',
                           command=self._open_file,
                           accelerator='Ctrl+O')
     file_menu.add_command(label='Save',
                           command=self._save_file,
                           accelerator='Ctrl+S')
     file_menu.add_command(label='Save as', command=self._save_as)
     file_menu.add_separator()
     file_menu.add_command(label='Quit',
                           command=self.board.quit,
                           accelerator='Ctrl+Q')
     self._menu.add_cascade(label='File', menu=file_menu)
     edit_menu = Menu(self._menu, tearoff=0)
     edit_menu.add_command(label='Undo',
                           command=self.board.undo,
                           accelerator='Ctrl+Z')
     edit_menu.add_command(label='Redo',
                           command=self.board.redo,
                           accelerator='Ctrl+Y')
     edit_menu.add_command(label='Delete selected',
                           command=self.board._delete_selected_items,
                           accelerator='Delete')
     edit_menu.add_command(label='Rotate selected',
                           command=self.board._rotate_selected_item,
                           accelerator='r')
     edit_menu.add_command(label='Toggle cursor',
                           command=self._toggle_cursor,
                           accelerator='D')
     self._menu.add_cascade(label='Edit', menu=edit_menu)
     self._root.config(menu=self._menu)
Example #43
0
    def initUI(self):
      
        self.parent.title("Property Rate Prediction System")
        self.pack(fill=BOTH, expand=1)
        
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        wel = Label(self, text="Welcome to property rate predictor", font=("Helvetica", 30))
        wel.place( x=200,y=150)
        """photo = PhotoImage(file="house.jpeg")
        w = Label(parent, image=photo)
        w.photo = photo
        w.pack()"""
        fileMenu = Menu(menubar)       
        fileMenu.add_command(label='Add a File', underline=0,command=lambda:self.onOpen(wel))
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)


        menubar.add_cascade(label="File", underline=0, menu=fileMenu)       
        
        
        """addFile = Button(self, text="Add a File",command=self.onOpen)
Example #44
0
class Menubar(Menu):
    def __init__(self, root, gui):
        Menu.__init__(self)

        self.filemenu = Menu(self, tearoff=0)
        self.filemenu.add_command(label="Logout")
        self.filemenu.add_command(label="Print...")
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=root.destroy)

        self.add_cascade(label="File", menu=self.filemenu)

        self.adminmenu = Menu(self, tearoff=0)
        self.adminmenu.add_command(label="Database")
        self.adminmenu.add_command(label="Users")

        self.add_cascade(label="Admin", menu=self.adminmenu)

        self.helpmenu = Menu(self, tearoff=0)
        self.helpmenu.add_command(label="About")
        self.helpmenu.add_command(label="Help")

        self.add_cascade(label="Help", menu=self.helpmenu)
Example #45
0
class Menubar(Menu):
    def __init__(self, root, gui):
        Menu.__init__(self)
        
        self.filemenu = Menu(self, tearoff=0)
        self.filemenu.add_command(label="Logout")
        self.filemenu.add_command(label="Print...")
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=root.destroy)
        
        self.add_cascade(label="File", menu=self.filemenu)
        
        self.adminmenu = Menu(self, tearoff=0)
        self.adminmenu.add_command(label="Database")
        self.adminmenu.add_command(label="Users")
        
        self.add_cascade(label="Admin", menu=self.adminmenu)
        
        self.helpmenu = Menu(self, tearoff=0)
        self.helpmenu.add_command(label="About")
        self.helpmenu.add_command(label="Help")
        
        self.add_cascade(label="Help", menu=self.helpmenu)
Example #46
0
    def initUI(self):

        self.parent.title("Property Rate Prediction System")
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        wel = Label(self,
                    text="Welcome to property rate predictor",
                    font=("Helvetica", 30))
        wel.place(x=200, y=150)
        """photo = PhotoImage(file="house.jpeg")
        w = Label(parent, image=photo)
        w.photo = photo
        w.pack()"""
        fileMenu = Menu(menubar)
        fileMenu.add_command(label='Add a File',
                             underline=0,
                             command=lambda: self.onOpen(wel))
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)

        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
        """addFile = Button(self, text="Add a File",command=self.onOpen)
def build_menubar(parent, mbardata):
    from Tkinter import Menu
    menubar = Menu(parent)
    parent.config(menu=menubar)
    menus = []
    for (label, items) in mbardata:
        menu = Menu(menubar)
        menus.append(menu)
        menubar.add_cascade(label=label, menu=menu)
        for item in items:
            if item == '-':
                menu.add_separator()
            else:
                label = item[0]
                underline = label.find('&')
                if underline >= 0:
                    label = label[:underline] + label[underline+1:]
                else:
                    underline = None
                accelerator = item[2] if len(item) > 2 else None
                menu.add_command(label=label, command=item[1],
                                 accelerator=accelerator,
                                 underline=underline)
    return (menubar, menus)
Example #48
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del")
        filemenu.add_command(label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p")
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g")
        editmenu.add_command(label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t")
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space")
        rulemenu.add_separator()
        rulemenu.add_command(label="Match", underline=0, command=self.match, accelerator="Ctrl-m")
        rulemenu.add_command(label="Expand", underline=0, command=self.expand, accelerator="Ctrl-e")
        rulemenu.add_separator()
        rulemenu.add_command(label="Backtrack", underline=0, command=self.backtrack, accelerator="Ctrl-b")
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar
        )
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize)
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animation_frames, value=0)
        animatemenu.add_radiobutton(
            label="Slow Animation", underline=0, variable=self._animation_frames, value=10, accelerator="-"
        )
        animatemenu.add_radiobutton(
            label="Normal Animation", underline=0, variable=self._animation_frames, value=5, accelerator="="
        )
        animatemenu.add_radiobutton(
            label="Fast Animation", underline=0, variable=self._animation_frames, value=2, accelerator="+"
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1")
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)
Example #49
0
    def init_window(self):
        global user_defaults
        self.grid()

        # Setup menu content###

        self.master.title("Antifier v0.9")
        self.master.option_add("*tearOff", False)

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a menu instance
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # create the Setup object)
        Setup = Menu(menu)

        # add commands to the Setup option
        Setup.add_command(label="Head Unit", command=self.HeadUnit_window)

        subSetup = Menu(Setup)
        subSetup.add_command(
            label="iMagic",
            command=lambda p="power_calc_factors_imagic.txt": self.settrainer(
                p),
        )
        subSetup.add_command(
            label="Fortius",
            command=lambda p="power_calc_factors_fortius.txt": self.settrainer(
                p),
        )
        subSetup.add_command(
            label="Custom Curve",
            command=lambda p="power_calc_factors_custom.txt": self.settrainer(
                p),
        )

        Setup.add_cascade(label="Power Curve", menu=subSetup)

        Setup.add_separator()
        Setup.add_command(label="Exit", command=self.EXITbutton)

        # added "Setup" to our menu
        menu.add_cascade(label="Setup", menu=Setup)

        # create the Options object)
        Options = Menu(menu)

        # add commands to the Options option
        Options.add_command(label="Debug", command=self.DebugButton)
        Options.add_command(label="Simulate Trainer",
                            command=self.Simulatebutton)
        Options.add_command(label="Power Factor",
                            command=self.PowerFactor_Window)

        # added "Options" to our menu
        menu.add_cascade(label="Options", menu=Options)

        # create the Help object
        Help = Menu(menu)

        # adds a command to the Help option.
        Help.add_command(label="Readme", command=self.Readme)
        Help.add_command(label="Zwift shortcuts", command=self.Zwift_shortcuts)

        # added "Help" to our menu
        menu.add_cascade(label="Help", menu=Help)

        # Setup GUI buttons and labels###

        self.FindHWbutton = Button(self,
                                   height=1,
                                   width=15,
                                   text=u"1. Locate HW",
                                   command=self.ScanForHW)
        self.FindHWbutton.grid(column=0, row=0)

        label = Label(self, height=1, width=10, text="Head Unit")
        label.grid(column=0, row=1, sticky="EW")
        self.trainerVariable = StringVar()
        label = Label(self,
                      textvariable=self.trainerVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=1, columnspan=2, sticky="EW")

        label = Label(self, height=1, width=10, text="Power curve")
        label.grid(column=0, row=2, sticky="EW")
        self.PowerCurveVariable = StringVar()
        label = Label(
            self,
            textvariable=self.PowerCurveVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=2, columnspan=2, sticky="EW")
        if "power_curve" in user_defaults:
            self.settrainer(user_defaults["power_curve"])

        label = Label(self, height=1, width=10, text="ANT+")
        label.grid(column=0, row=3, sticky="EW")
        self.ANTVariable = StringVar()
        label = Label(self,
                      textvariable=self.ANTVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=3, columnspan=2, sticky="EW")

        label = Label(self, text="Power factor")
        label.grid(column=0, row=4, sticky="EW")
        self.PowerFactorVariable = StringVar()
        label = Label(
            self,
            textvariable=self.PowerFactorVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=4, columnspan=2, sticky="EW")

        self.RunoffButton = Button(self,
                                   height=1,
                                   width=15,
                                   text=u"2. Perform Runoff",
                                   command=self.Runoff)
        self.RunoffButton.grid(column=0, row=5)
        self.RunoffButton.config(state="disabled")
        self.runoffVariable = StringVar()
        label = Label(
            self,
            textvariable=self.runoffVariable,
            anchor="w",
            fg="black",
            bg="grey",
            width=40,
        )
        label.grid(column=1, row=5, columnspan=2, sticky="EW")

        self.StartAPPbutton = Button(self,
                                     height=1,
                                     width=15,
                                     text=u"3. Start script",
                                     command=self.Start)
        self.StartAPPbutton.grid(column=0, row=6)
        self.StartAPPbutton.config(state="disabled")

        self.StopAPPbutton = Button(
            self,
            height=1,
            width=15,
            text=u"Stop script",
            command=self.Stop,
            state="disabled",
        )
        self.StopAPPbutton.grid(column=1, row=6)

        label = Label(self, text="Speed")
        label.grid(column=0, row=7, sticky="EW")

        self.SpeedVariable = StringVar()
        label = Label(self,
                      textvariable=self.SpeedVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=7, columnspan=2, sticky="EW")
        self.SpeedVariable.set(u"0")

        label = Label(self, text="Heartrate")
        label.grid(column=0, row=8, sticky="EW")
        self.HeartrateVariable = StringVar()
        label = Label(self,
                      textvariable=self.HeartrateVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=8, columnspan=2, sticky="EW")
        self.HeartrateVariable.set(u"0")

        label = Label(self, text="Cadence")
        label.grid(column=0, row=9, sticky="EW")

        self.CadenceVariable = StringVar()
        label = Label(self,
                      textvariable=self.CadenceVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=9, columnspan=2, sticky="EW")
        self.CadenceVariable.set(u"0")

        label = Label(self, text="Power")
        label.grid(column=0, row=10, sticky="EW")
        self.PowerVariable = StringVar()
        label = Label(self,
                      textvariable=self.PowerVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=10, columnspan=2, sticky="EW")
        self.PowerVariable.set(u"0")

        label = Label(self, text="Slope")
        label.grid(column=0, row=11, sticky="EW")
        self.SlopeVariable = StringVar()
        label = Label(self,
                      textvariable=self.SlopeVariable,
                      anchor="w",
                      fg="black",
                      bg="grey")
        label.grid(column=1, row=11, columnspan=2, sticky="EW")

        label = Label(self, text="Target Power")
        label.grid(column=0, row=12, sticky="EW")
        self.TargetPowerVariable = StringVar()
        label = Label(
            self,
            textvariable=self.TargetPowerVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=12, columnspan=2, sticky="EW")

        label = Label(self, text="Resistance Level")
        label.grid(column=0, row=13, sticky="EW")
        self.ResistanceLevelVariable = StringVar()
        label = Label(
            self,
            textvariable=self.ResistanceLevelVariable,
            anchor="w",
            fg="black",
            bg="grey",
        )
        label.grid(column=1, row=13, columnspan=2, sticky="EW")
        self.ResistanceLevelVariable.set(u"0")
Example #50
0
class FalconGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("Credo QSFP-SFP Tester")
        self.api = Falcon_lib()

        self.tab_1 = Frame(self.master,relief=)
        self.tab_1.grid(row=0,column=0)
        self.monitor_1 = Label(self.tab_1, text='RX Monitor 1')
        self.monitor_1.bind("<Button-3>", self.print_click)
        self.monitor_1.pack(ipady=5)
        self.table_1 = Frame(self.tab_1)
        self.table_1.pack(fill='both', padx=10)

        self.link_status = Label(self.table_1, text='Link Status')
        self.link_status.grid(row=1, sticky='W', padx=10)
        self.eye = Label(self.table_1, text='Eye Margin')
        self.eye.grid(row=3, sticky='W', padx=10)
        self.BER = Label(self.table_1, text='BER')
        self.BER.grid(row=4, sticky='W', padx=10)
        self.passfail = Label(self.table_1, text='Pass/Fail')
        self.passfail.grid(row=5, sticky='W', padx=10)



        self.table_2 = Frame(self.master)
        self.table_2.grid(row=0,column=1)#pack(fill='both', padx=10)
        self.monitor_2 = Label(self.tab_1, text='RX Monitor 2')
        self.monitor_2.pack(pady=10)

        self.link_status = Label(self.table_2, text='Link Status')
        self.link_status.grid(row=1, sticky='W', padx=10)
        self.eye = Label(self.table_2, text='Eye Margin')
        self.eye.grid(row=3, sticky='W', padx=10)
        self.BER = Label(self.table_2, text='BER')
        self.BER.grid(row=4, sticky='W', padx=10)
        self.passfail = Label(self.table_2, text='Pass/Fail')
        self.passfail.grid(row=5, sticky='W', padx=10)
        self.count = 0

        self.all_button = Button(self.tab_1, text='Reset All',
                                 command=self.prbs_reset)
        self.all_button.pack(pady=10)

        self.all_button1 = Button(self.tab_1, text='Reset All  1',
                                 command=self.testGPIO)
        self.all_button1.pack(pady=11)

        self.main_menu = Menu(self.master)
        self.master.config(menu=self.main_menu)
        self.option_menu = Menu(self.main_menu, tearoff=0)
        self.option_menu.add_command(label='Load Alternate Script',
                                     command=self.load_window)
        self.option_menu.add_separator()
        self.option_menu.add_command(label='Exit', command=the_end)
        self.main_menu.add_cascade(label='Options', menu=self.option_menu)

        self.table()
        self.display()

    def print_click(self):
        print 'You right clicked!'

    def prbs_reset(self):
        for i in range(16):
            self.api.Falcon_Reset_PRBS_Cntr_B(i + 1)
        self.count = 0

    def table(self):
        eye = []
        ber = []
        ar = []
        br = []

        for i in range(1, 9):
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            ar.append('AR%d' % i)

            ar[i - 1] = Label(self.table_1, text='AR%d' % i, bg='grey')
            eye[i - 1] = Label(self.table_1, bg='white')
            ber[i - 1] = Label(self.table_1, bg='white')

            ar[i - 1].grid(row=0, column=i, sticky='S', ipadx=41, pady=1)
            eye[i - 1].grid(row=3, column=i, ipadx=52, ipady=5)
            ber[i - 1].grid(row=4, column=i, ipadx=52, ipady=5)

        for i in range(1, 9):
            v = i + 8
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            br.append('BR%d' % i)

            br[i - 1] = Label(self.table_2, text='BR%d' % i, bg='grey')
            eye[v - 1] = Label(self.table_2, bg='white')
            ber[v - 1] = Label(self.table_2, bg='white')

            br[i - 1].grid(row=0, column=i, ipadx=41, pady=1)
            eye[v - 1].grid(row=3, column=i, ipadx=52, ipady=5)
            ber[v - 1].grid(row=4, column=i, ipadx=52, ipady=5)

    def data(self):

        link = []
        eye = []
        ber = []
        fail = []

        self.count += 1
        timer = Label(self.master, text='Test Time: %d' % self.count)
        timer.grid(row=1, pady=10, ipadx=7)

        for i in range(1, 9):
            link.append('link_%d' % i)
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            fail.append('fail_%d' % i)

            link[i - 1] = Label(self.table_2, width=3, height=1)
            fail[i - 1] = Label(self.table_2, width=3, height=1, relief='solid', bd=1)
            
            if self.link_stat(i) == 1:
                link[i - 1].config(text='ON', bg='green')
                if self.ber(i) <= 1e-13:
                    fail[i - 1].config(text='PASS', bg='green')
                else:
                    fail[i - 1].config(text='FAIL', bg='red')
            else:
                link[i - 1].config(text='OFF', bg='red')
                fail[i - 1].config(text='FAIL', bg='red')
            eye[i - 1] = Label(self.table_2, text='%.3f' % self.eye_marg(i),
                               bg='white', width=3, height=1)
            ber[i - 1] = Label(self.table_2, text='%.2E' % self.ber(i),
                               bg='white', width=3, height=1)
                               
            if (i<5):
                link[i - 1].grid(row=1, column=i+4, ipadx=41, ipady=5)
                eye[i - 1].grid(row=3, column=i+4, ipadx=14)
                ber[i - 1].grid(row=4, column=i+4, ipadx=14)
                fail[i - 1].grid(row=5, column=i+4, ipadx=40, ipady=5)
            else:
                link[i - 1].grid(row=1, column=i-4, ipadx=41, ipady=5)
                eye[i - 1].grid(row=3, column=i-4, ipadx=14)
                ber[i - 1].grid(row=4, column=i-4, ipadx=14)
                fail[i - 1].grid(row=5, column=i-4, ipadx=40, ipady=5)

            
        for i in range(1, 9):
            v = i + 8
            link.append('link_%d' % i)
            eye.append('eye_%d' % i)
            ber.append('ber_%d' % i)
            fail.append('fail_%d' % i)

            link[v - 1] = Label(self.table_1, width=3, height=1)
            fail[v - 1] = Label(self.table_1, width=3, height=1, relief='solid', bd=1)
            if self.link_stat(v) == 1:
                link[v - 1].config(text='ON', bg='green')
                if self.ber(v) <= 1e-13:
                    fail[v - 1].config(text='PASS', bg='green')
                else:
                    fail[v - 1].config(text='FAIL', bg='red')
            else:
                link[v - 1].config(text='OFF', bg='red')
                fail[v - 1].config(text='FAIL', bg='red')
            eye[v - 1] = Label(self.table_1, text='%.3f' % self.eye_marg(v),
                               bg='white', width=3, height=1)
            ber[v - 1] = Label(self.table_1, text='%.2E' % self.ber(v),
                               bg='white', width=3, height=1)
          
            if (i<5):
                link[v - 1].grid(row=1, column=i+4, ipadx=41, ipady=5)
                eye[v - 1].grid(row=3, column=i+4, ipadx=14)
                ber[v - 1].grid(row=4, column=i+4, ipadx=14)
                fail[v - 1].grid(row=5, column=i+4, ipadx=40, ipady=5)
            else:
                link[v - 1].grid(row=1, column=i-4, ipadx=41, ipady=5)
                eye[v - 1].grid(row=3, column=i-4, ipadx=14)
                ber[v - 1].grid(row=4, column=i-4, ipadx=14)
                fail[v - 1].grid(row=5, column=i-4, ipadx=40, ipady=5)
            '''
            link[v - 1].grid(row=1, column=i, ipadx=41, ipady=5)
            eye[v - 1].grid(row=3, column=i, ipadx=14)
            ber[v - 1].grid(row=4, column=i, ipadx=14)
            fail[v - 1].grid(row=5, column=i, ipadx=40, ipady=5)
            '''
    def display(self):
        self.data()
        self.master.after(1000, self.display)

    def testGPIO(self):
        adr=0
        a=self.api.MdioRd(0)
        print "addr %x's value0x%x" %(adr,a)

    def connect(self):
        self.api.connect()

    def link_stat(self, m):
        return int(self.api.Falcon_Link_Status_B(m))

    def eye_marg(self, m):
        eye = float(self.api.Falcon_Read_Eyemargin_B(m))
        return eye

    def ber(self, m):
        return self.api.RxReadPRBSCounterB(m) / float((40 * 50 * 10 ** 9))

    def load_window(self):
        new = Toplevel(self.master)
        what = Fetch(new)
        "PyText", "This is a placeholder item and will be replaced later")


menu = Menu(root)
# configuration for a menu bar
root.config(menu=menu)

# setup for the filemenu
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)

# drop down items for the commands within the file menu
filemenu.add_command(label="New", command=placeholder)
filemenu.add_command(label="Open", command=openFile)
filemenu.add_command(label="Save", command=saveFile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=exit)

# setup for edit menu
editmenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editmenu)

# drop down items for the commands within the edit menu
editmenu.add_command(label="Undo", command=placeholder)
editmenu.add_command(label="Redo", command=placeholder)
editmenu.add_separator()
editmenu.add_command(label="Copy", command=copy)
editmenu.add_command(label="Cut", command=cut)
editmenu.add_command(label="Paste", command=paste)

# setup for help menu
Example #52
0
class PypeTkPad(object):
    def __init__(self, master, queue, pypeOutput):

        self.queue = queue
        self.pypeOutput = pypeOutput

        self.master = master
        self.master.title('PypePad')
        self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0))
        self.master.minsize(300, 100)
        self.output_file_name = None

        self.BuildMainFrame()
        self.UpdateOutput()

    def NewCommand(self):
        self.ClearAllCommand()

    def OpenCommand(self):
        import tkFileDialog
        from Tkinter import END
        openfile = tkFileDialog.askopenfile()
        if not openfile:
            return
        for line in openfile.readlines():
            self.text_input.insert(END, line)

    def SaveCommand(self):
        import tkFileDialog
        from Tkinter import END
        saveasfile = tkFileDialog.asksaveasfile()
        if not saveasfile:
            return
        alltext = self.text_input.get("1.0", END)
        saveasfile.write(alltext)

    def QuitCommand(self):
        self.master.quit()

    def ClearInputCommand(self):
        from Tkinter import END
        self.text_input.delete("1.0", END)

    def ClearOutputCommand(self):
        from Tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.delete("1.0", END)
        self.text_output["state"] = DISABLED
        self.text_output.see(END)
        self.text_output.update()

    def ClearAllCommand(self):
        self.ClearInputCommand()
        self.ClearOutputCommand()

    def OutputFileCommand(self):
        import tkFileDialog
        outputfilename = tkFileDialog.asksaveasfilename()
        if sys.platform == 'win32' and len(outputfilename.split()) > 1:
            outputfilename = '"%s"' % outputfilename
        self.output_file_name = outputfilename

    def AboutCommand(self):
        self.OutputText('\n')
        self.OutputText(
            '* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n')
        self.OutputText('\n')

    def UpdateOutput(self):
        if self.pypeOutput:
            text = self.pypeOutput.pop(0)
            self.output_stream.write(text)
        self.master.after(10, self.UpdateOutput)

    def RunPype(self, arguments):
        if not arguments:
            return
        if self.output_to_file.get() is not 'n' and self.output_file_name:
            self.output_stream.output_to_file = True
            self.output_stream.output_file = open(self.output_file_name,
                                                  self.output_to_file.get())
        else:
            self.output_stream.output_to_file = False

        self.queue.append(arguments)

    def GetWordUnderCursor(self):
        from Tkinter import CURRENT
        splitindex = self.text_input.index(CURRENT).split('.')
        line = self.text_input.get(splitindex[0] + ".0",
                                   splitindex[0] + ".end")
        wordstart = line.rfind(' ', 0, int(splitindex[1]) - 1) + 1
        wordend = line.find(' ', int(splitindex[1]))
        if wordend == -1:
            wordend = len(line)
        word = line[wordstart:wordend]
        return word

    def GetWordIndex(self):
        startindex = self.text_input.index("insert-1c wordstart")
        endindex = self.text_input.index("insert-1c wordend")
        if self.text_input.get(startindex +
                               '-1c') == '-' and self.text_input.get(
                                   startindex + '-2c') == '-':
            startindex = self.text_input.index("insert-1c wordstart -2c")
        elif self.text_input.get(startindex +
                                 '-1c') == '-' and self.text_input.get(
                                     startindex + '-2c') == ' ':
            startindex = self.text_input.index("insert-1c wordstart -1c")
        self.wordIndex[0] = startindex
        self.wordIndex[1] = endindex
        word = self.text_input.get(self.wordIndex[0], self.wordIndex[1])
        return word

    def GetLogicalLine(self, physicallineid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallineid]]

    def GetLogicalLineRange(self, physicallinefirstid, physicallinelastid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallinefirstid]:indexes[physicallinelastid] +
                     1]

    def GetAllLogicalLines(self):
        return self.GetLogicalLines()[1]

    def GetLogicalLines(self):
        from Tkinter import END
        physicallines = self.text_input.get("1.0", END).split('\n')
        lines = []
        indexes = [0] * len(physicallines)
        lineid = 0
        previousline = ""
        join = 0
        for line in physicallines:
            if line.startswith('#'):
                if join:
                    indexes[lineid] = indexes[lineid - 1]
            elif join:
                if line.endswith('\\'):
                    lines[-1] = lines[-1] + " " + line[:-1]
                    join = 1
                else:
                    lines[-1] = lines[-1] + " " + line
                    join = 0
                indexes[lineid] = indexes[lineid - 1]
            else:
                if line.endswith('\\'):
                    join = 1
                    lines.append(line[:-1])
                else:
                    lines.append(line)
                    join = 0
                if lineid > 0:
                    indexes[lineid] = indexes[lineid - 1] + 1
            lineid += 1
        return indexes, lines

    def GetLineUnderCursor(self):
        from Tkinter import INSERT
        currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1
        return self.GetLogicalLine(currentlineid)

    def RunAllCommand(self):
        lines = self.GetAllLogicalLines()
        for line in lines:
            if line and line.strip():
                self.RunPype(line)

    def RunLineCommand(self):
        line = self.GetLineUnderCursor()
        if line and line.strip():
            self.RunPype(line)

    def RunSelectionCommand(self):
        from Tkinter import TclError, SEL_FIRST, SEL_LAST
        try:
            firstlineid = int(
                self.text_input.index(SEL_FIRST).split('.')[0]) - 1
            lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1
            lines = self.GetLogicalLineRange(firstlineid, lastlineid)
            for line in lines:
                self.RunPype(line)
        except TclError:
            pass

    def GetSuggestionsList(self, word):
        list = []
        try:
            exec('import vmtkscripts')
        except ImportError:
            return None
        if word.startswith('--'):
            list = ['--pipe', '--help']
        elif word.startswith('-'):
            optionlist = []
            scriptindex = self.text_input.search('vmtk',
                                                 self.wordIndex[0],
                                                 backwards=1)
            moduleName = self.text_input.get(scriptindex,
                                             scriptindex + ' wordend')
            try:
                exec('import ' + moduleName)
                exec('scriptObjectClassName =  ' + moduleName + '.' +
                     moduleName)
                exec('scriptObject = ' + moduleName + '.' +
                     scriptObjectClassName + '()')
                members = scriptObject.InputMembers + scriptObject.OutputMembers
                for member in members:
                    optionlist.append('-' + member.OptionName)
                exec(
                    'list = [option for option in optionlist if option.count(word)]'
                )
            except:
                return list
        else:
            exec(
                'list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word) ]'
            )
        return list

    def FillSuggestionsList(self, word):
        from Tkinter import END
        self.suggestionslist.delete(0, END)
        suggestions = self.GetSuggestionsList(word)
        for suggestion in suggestions:
            self.suggestionslist.insert(END, suggestion)

    def ReplaceTextCommand(self, word):
        self.text_input.delete(self.wordIndex[0], self.wordIndex[1])
        self.text_input.insert(self.wordIndex[0], word)
        self.text_input.focus_set()

    def ShowHelpCommand(self):
        word = self.GetWordUnderCursor()
        self.OutputText(word)
        if word:
            self.RunPype(word + ' --help')
        else:
            self.OutputText('Enter your vmtk Pype above and Run.\n')

    def AutoCompleteCommand(self):
        word = self.GetWordIndex()
        self.suggestionswindow.withdraw()
        if word:
            self.FillSuggestionsList(word)
            self.suggestionswindow.geometry(
                "%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),
                                 self.text_output.winfo_rooty()))
            self.suggestionswindow.deiconify()
            self.suggestionswindow.lift()

    def InsertScriptName(self, scriptname):
        from Tkinter import INSERT
        self.text_input.insert(INSERT, scriptname + ' ')

    def InsertFileName(self):
        from Tkinter import INSERT
        import tkFileDialog
        openfilename = tkFileDialog.askopenfilename()
        if not openfilename:
            return
        if len(openfilename.split()) > 1:
            openfilename = '"%s"' % openfilename
        self.text_input.insert(INSERT, openfilename + ' ')

    def KeyPressHandler(self, event):
        if event.keysym == "Tab":
            self.AutoCompleteCommand()
            self.suggestionslist.focus_set()
            self.suggestionslist.selection_set(0)
            return "break"
        else:
            self.text_input.focus_set()

    def TopKeyPressHandler(self, event):
        from Tkinter import ACTIVE, INSERT
        if event.keysym in ['Down', 'Up']:
            self.suggestionslist.focus_set()
        elif event.keysym == "Return":
            word = self.suggestionslist.get(ACTIVE)
            self.ReplaceTextCommand(word)
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
        elif len(event.keysym) == 1:
            self.suggestionswindow.withdraw()
            self.text_input.insert(INSERT, event.keysym)
            self.text_input.focus_set()
        else:
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()

    def NewHandler(self, event):
        self.NewCommand()

    def OpenHandler(self, event):
        self.OpenCommand()

    def SaveHandler(self, event):
        self.SaveCommand()

    def InsertFileNameHandler(self, event):
        self.InsertFileName()
        return "break"

    def QuitHandler(self, event):
        self.QuitCommand()

    def ShowHelpHandler(self, event):
        self.ShowHelpCommand()

    def RunKeyboardHandler(self, event):
        from Tkinter import SEL_FIRST, TclError
        try:
            self.text_input.index(SEL_FIRST)
            self.RunSelectionCommand()
        except TclError:
            self.RunLineCommand()
        return "break"

    def RunAllHandler(self, event):
        self.RunAllCommand()

    def PopupHandler(self, event):
        try:
            self.popupmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popupmenu.grab_release()

    def OutputText(self, text):
        from Tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.insert(END, text)
        self.text_output["state"] = DISABLED

    def BuildScriptMenu(self, parentmenu, modulename):
        from Tkinter import Menu
        menu = Menu(parentmenu, bd=1, activeborderwidth=0)
        try:
            exec('import ' + modulename)
        except ImportError:
            return None
        scriptnames = []
        exec('scriptnames = [scriptname for scriptname in ' + modulename +
             '.__all__]')
        menulength = 20
        for i in range(len(scriptnames) / menulength + 1):
            subscriptnames = scriptnames[i * menulength:(i + 1) * menulength]
            if not subscriptnames:
                break
            submenu = Menu(menu, bd=1, activeborderwidth=0)
            menu.add_cascade(label=subscriptnames[0] + "...", menu=submenu)
            for scriptname in subscriptnames:
                callback = CallbackShim(self.InsertScriptName, scriptname)
                submenu.add_command(label=scriptname, command=callback)
        return menu

    def BuildMainFrame(self):
        from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master, activeborderwidth=0, bd=0)
        self.master.config(menu=menu)

        filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="File", underline=0, menu=filemenu)
        filemenu.add_command(label="New",
                             accelerator='Ctrl+N',
                             command=self.NewCommand)
        filemenu.add_command(label="Open...",
                             accelerator='Ctrl+O',
                             command=self.OpenCommand)
        filemenu.add_command(label="Save as...",
                             accelerator='Ctrl+S',
                             command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",
                             accelerator='Ctrl+Q',
                             command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)

        self.output_to_file = StringVar()
        self.output_to_file.set('n')

        scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu, modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu)

        editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Edit", underline=0, menu=editmenu)
        editmenu.add_cascade(label="Insert script", menu=scriptmenu)
        editmenu.add_command(label="Insert file name",
                             accelerator='Ctrl+F',
                             command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input",
                             command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output",
                             command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file",
                                 variable=self.output_to_file,
                                 value='n')
        editmenu.add_radiobutton(label="Write output to file",
                                 variable=self.output_to_file,
                                 value='w')
        editmenu.add_radiobutton(label="Append output to file",
                                 variable=self.output_to_file,
                                 value='a')
        editmenu.add_command(label="Output file...",
                             command=self.OutputFileCommand)

        runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line",
                            command=self.RunLineCommand)
        runmenu.add_command(label="Run selection",
                            command=self.RunSelectionCommand)

        helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help",
                             underline=0,
                             accelerator='F1',
                             command=self.ShowHelpCommand)
        helpmenu.add_command(label="About",
                             underline=0,
                             command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)

        self.wordIndex = ['1.0', '1.0']

        self.suggestionswindow = Toplevel(bg='#ffffff',
                                          bd=0,
                                          height=50,
                                          width=600,
                                          highlightthickness=0,
                                          takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,
                                       bg='#ffffff',
                                       bd=1,
                                       fg='#336699',
                                       activestyle='none',
                                       highlightthickness=0,
                                       height=9)
        self.suggestionslist.insert(END, "foo")
        self.suggestionslist.pack(side=TOP, fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        content = Frame(self.master, bd=0, padx=2, pady=2)
        content.grid(row=0, column=0, sticky=N + S + W + E)
        content.rowconfigure(0, weight=1, minsize=50)
        content.rowconfigure(1, weight=0)
        content.columnconfigure(0, weight=1)

        panes = PanedWindow(content,
                            orient=VERTICAL,
                            bd=1,
                            sashwidth=8,
                            sashpad=0,
                            sashrelief=RAISED,
                            showhandle=True)
        panes.grid(row=0, column=0, sticky=N + S + W + E)

        frame1 = Frame(panes, bd=0)
        frame1.grid(row=0, column=0, sticky=N + S + W + E)
        frame1.columnconfigure(0, weight=1)
        frame1.columnconfigure(1, weight=0)
        frame1.rowconfigure(0, weight=1)

        panes.add(frame1, height=300, minsize=20)

        frame2 = Frame(panes, bd=0)
        frame2.grid(row=1, column=0, sticky=N + S + W + E)
        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(1, weight=0)
        frame2.rowconfigure(0, weight=1)

        panes.add(frame2, minsize=20)

        self.text_input = Text(frame1,
                               bg='#ffffff',
                               bd=1,
                               highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)

        self.input_scrollbar = Scrollbar(frame1,
                                         orient=VERTICAL,
                                         command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set

        self.text_output = Text(frame2,
                                state=DISABLED,
                                bd=1,
                                bg='#ffffff',
                                highlightthickness=0)

        self.output_scrollbar = Scrollbar(frame2,
                                          orient=VERTICAL,
                                          command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set

        self.text_entry = Entry(content,
                                bd=1,
                                bg='#ffffff',
                                state=DISABLED,
                                highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0, column=0, sticky=N + S + W + E)
        self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_output.grid(row=0, column=0, sticky=N + S + W + E)
        self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_entry.grid(row=1, column=0, sticky=N + S + W + E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help",
                                   command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...",
                                   command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line",
                                   command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection",
                                   command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,
                                             self.output_stream)
Example #53
0
    def BuildMainFrame(self):
        from Tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from Tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master, activeborderwidth=0, bd=0)
        self.master.config(menu=menu)

        filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="File", underline=0, menu=filemenu)
        filemenu.add_command(label="New",
                             accelerator='Ctrl+N',
                             command=self.NewCommand)
        filemenu.add_command(label="Open...",
                             accelerator='Ctrl+O',
                             command=self.OpenCommand)
        filemenu.add_command(label="Save as...",
                             accelerator='Ctrl+S',
                             command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",
                             accelerator='Ctrl+Q',
                             command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)

        self.output_to_file = StringVar()
        self.output_to_file.set('n')

        scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu, modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu)

        editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Edit", underline=0, menu=editmenu)
        editmenu.add_cascade(label="Insert script", menu=scriptmenu)
        editmenu.add_command(label="Insert file name",
                             accelerator='Ctrl+F',
                             command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input",
                             command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output",
                             command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file",
                                 variable=self.output_to_file,
                                 value='n')
        editmenu.add_radiobutton(label="Write output to file",
                                 variable=self.output_to_file,
                                 value='w')
        editmenu.add_radiobutton(label="Append output to file",
                                 variable=self.output_to_file,
                                 value='a')
        editmenu.add_command(label="Output file...",
                             command=self.OutputFileCommand)

        runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line",
                            command=self.RunLineCommand)
        runmenu.add_command(label="Run selection",
                            command=self.RunSelectionCommand)

        helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help",
                             underline=0,
                             accelerator='F1',
                             command=self.ShowHelpCommand)
        helpmenu.add_command(label="About",
                             underline=0,
                             command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)

        self.wordIndex = ['1.0', '1.0']

        self.suggestionswindow = Toplevel(bg='#ffffff',
                                          bd=0,
                                          height=50,
                                          width=600,
                                          highlightthickness=0,
                                          takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,
                                       bg='#ffffff',
                                       bd=1,
                                       fg='#336699',
                                       activestyle='none',
                                       highlightthickness=0,
                                       height=9)
        self.suggestionslist.insert(END, "foo")
        self.suggestionslist.pack(side=TOP, fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        content = Frame(self.master, bd=0, padx=2, pady=2)
        content.grid(row=0, column=0, sticky=N + S + W + E)
        content.rowconfigure(0, weight=1, minsize=50)
        content.rowconfigure(1, weight=0)
        content.columnconfigure(0, weight=1)

        panes = PanedWindow(content,
                            orient=VERTICAL,
                            bd=1,
                            sashwidth=8,
                            sashpad=0,
                            sashrelief=RAISED,
                            showhandle=True)
        panes.grid(row=0, column=0, sticky=N + S + W + E)

        frame1 = Frame(panes, bd=0)
        frame1.grid(row=0, column=0, sticky=N + S + W + E)
        frame1.columnconfigure(0, weight=1)
        frame1.columnconfigure(1, weight=0)
        frame1.rowconfigure(0, weight=1)

        panes.add(frame1, height=300, minsize=20)

        frame2 = Frame(panes, bd=0)
        frame2.grid(row=1, column=0, sticky=N + S + W + E)
        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(1, weight=0)
        frame2.rowconfigure(0, weight=1)

        panes.add(frame2, minsize=20)

        self.text_input = Text(frame1,
                               bg='#ffffff',
                               bd=1,
                               highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)

        self.input_scrollbar = Scrollbar(frame1,
                                         orient=VERTICAL,
                                         command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set

        self.text_output = Text(frame2,
                                state=DISABLED,
                                bd=1,
                                bg='#ffffff',
                                highlightthickness=0)

        self.output_scrollbar = Scrollbar(frame2,
                                          orient=VERTICAL,
                                          command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set

        self.text_entry = Entry(content,
                                bd=1,
                                bg='#ffffff',
                                state=DISABLED,
                                highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0, column=0, sticky=N + S + W + E)
        self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_output.grid(row=0, column=0, sticky=N + S + W + E)
        self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_entry.grid(row=1, column=0, sticky=N + S + W + E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help",
                                   command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...",
                                   command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line",
                                   command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection",
                                   command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,
                                             self.output_stream)
Example #54
0
    AddRowBTN = tk.Button(UserWindow,text='Add New Row', command = AddRowButton)
    AddRowBTN.place(relx=0.9, rely=0.15, anchor=tk.CENTER)     
    
    UserWindow.mainloop()

#End of Menu Actions 
    
#Help info
def MenuHelp():
    tkMessageBox.showinfo('WLabs Replenisher', 'WLabs, Great!') 

#Menu Items
menu = Menu(window)
ReplenisherItem = Menu(menu, tearoff=0)
ReplenisherItem.add_command(label='Assignments', command = MenuAssignments)
ReplenisherItem.add_separator()
ReplenisherItem.add_command(label='Tasks', command = MenuTask)
ReplenisherItem.add_separator()
ReplenisherItem.add_command(label='Users', command = MenuUser)
menu.add_cascade(label='Select Replenisher Tasks', menu=ReplenisherItem)

HelpMenu = Menu(menu, tearoff=0)
HelpMenu.add_command(label="About Walmart Labs", command = MenuHelp) 
menu.add_cascade(label="Help", menu=HelpMenu) 

window.config(menu=menu)

window.mainloop() 


Example #55
0
class App(Frame):
    results_window = False

    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.__init_main(*args, **kwargs)

    def __init_main(self, *args, **kwargs):
        self.root = args[0]
        self.root.filename = ""
        self.root.wm_title("RSTool")
        self.root.protocol("WM_DELETE_WINDOW", self.__delete_root_window)
        self.root.bind("<Destroy>", self.__destroy_root_window)

        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar)
        self.filemenu.add_command(label="Save as...",
                                  command=self.save_to_file)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self.root.destroy)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

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

        self.tests = [
            Frequency,
            BlockFrequency,
            Runs,
            LongestRunOfOnes,
            Rank,
            DiscreteFourierTransform,
            Universal,
            Serial,
            ApproximateEntropy,
            CumulativeSums,
            RandomExcursions,
            RandomExcursionsVariant,
        ]
        self.slowtests = [
            NonOverlappingTemplateMatching,  # Slow
            OverlappingTemplateMatching,  # Slow
            LinearComplexity  # Slow
        ]
        # self.run_RandomWalkPlot = IntVar(self.root)

        rcounter = 0

        # Create and pack the title row:
        title = "NYUAD\nCenter for Cyber Security\nRandomness Testing Tool\nv0.9.0"
        self.l1 = Label(self.root, text=title)
        self.l1.grid(column=0, row=rcounter, columnspan=2, sticky=N)
        # self.l1.pack()
        rcounter += 1

        # Create and pack the "Open File" button and bind the loadFile method:
        self.b1 = Button(self.root, text="Open File", command=self.loadFile)
        self.b1.grid(column=0, row=rcounter, columnspan=1, pady=5)
        # rcounter += 1
        # self.b1.pack()

        # Create and pack the filename:
        self.l2 = Label(self.root, text=self.root.filename)
        self.l2.grid(column=1,
                     row=rcounter,
                     columnspan=2,
                     sticky=W,
                     padx=(5, 10))
        # self.l1.pack()
        rcounter += 1

        # Create textbox for bit-limit
        self.nl = Label(self.root,
                        text="Number of bits to test: (0 to test all)")
        self.nl.grid(column=0, row=rcounter, columnspan=1)
        rcounter += 1
        self.nt = Text(self.root, state="normal", width="15", height="1")
        self.nt.insert(END, "0")
        self.nt.grid(column=0,
                     row=rcounter,
                     columnspan=1,
                     padx=10,
                     pady=(0, 5))
        rcounter += 1

        # Create and pack the "Select/Deselect All" button and bind the checkAll method:
        self.b2 = Button(self.root,
                         text="Select/Deselect All Tests",
                         command=self.checkAll)
        self.b2.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Create and pack the "Select/Deselect Fast" button and bind the checkFast method:
        self.b3 = Button(self.root,
                         text="Select/Deselect Fast Tests",
                         command=self.checkFast)
        self.b3.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Create and pack the "Select/Deselect Slow" button and bind the checkSlow method:
        self.b4 = Button(self.root,
                         text="Select/Deselect Slow Tests",
                         command=self.checkSlow)
        self.b4.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Set IntVars for each test to check if it is selected to run:
        for test in self.tests + self.slowtests:
            setvar = "self.run_%s = IntVar(self.root)" % (test.__name__)
            exec(setvar)
            setvar = ""
            for i in range(func_data[test.__name__][1]):
                setvar = "self.%s_arg_%s = IntVar(self.root)" % (
                    test.__name__, func_data[test.__name__][2][i])

            # Example:
            # self.run_Frequency = IntVar(self.root)

        # Create and pack the checkbutton for each test and bind its IntVar to it:
        for test in self.tests + self.slowtests:
            make = [
                "self.cb_%s = " % (test.__name__), "Checkbutton(self.root, ",
                "text='%s ', " % (func_data[test.__name__][0]),
                "variable=self.run_%s)" % (test.__name__)
            ]
            make = "".join(make)
            grid = [
                "self.cb_%s.grid(" % (test.__name__),
                "column=0, row=%d, sticky=W)" % rcounter
            ]
            grid = "".join(grid)
            # args stuff
            rcounter += 1
            # pack = "self.cb_%s.pack()" % (test.__name__)
            exec(make)
            exec(grid)
            # exec(pack)
            # Example:
            # self.cb1 = Checkbutton(self.root, text="Frequency",
            # variable=self.run_Frequency)
            # self.cb1.pack()

        # Create and pack the "Run Tests" button and bind the runTests method:
        self.rb = Button(self.root, text="Run Tests", command=self.runTests)
        self.rb.grid(column=0, row=rcounter, columnspan=2)
        rcounter += 1
        # self.rb.pack()

        self.root.resizable(0, 0)
        self.root.lift()
        self.root.attributes('-topmost', True)
        self.root.after_idle(self.root.attributes, '-topmost', False)

    def __delete_root_window(self):
        # print "delete_root_window"
        try:
            self.root.destroy()
        except:
            pass

    def __destroy_root_window(self, event):
        # print "destroy_root_window", event
        pass

    def __delete_results_window(self):
        # print "delete_results_window"
        try:
            self.results_window.destroy()
        except:
            pass

    def __destroy_results_window(self, event):
        # print "destroy_results_window", event
        self.results_window = False

    def __make_results_window(self):
        # wname = "results_window"
        self.results_window = Toplevel(self, name="results_window")
        self.results_window.protocol("WM_DELETE_WINDOW",
                                     self.__delete_results_window)
        self.results_window.bind("<Destroy>", self.__destroy_results_window)
        self.results_window.wm_title("Test Results")
        self.results_window.config(menu=self.menubar)

        self.results_save_button = Button(self.results_window,
                                          text="Save to File",
                                          command=self.save_to_file)
        self.results_save_button.pack()

        self.results_text = Text(self.results_window,
                                 state="normal",
                                 width="70",
                                 height="50")
        self.results_text.pack(fill="both", expand=True, padx=10)

    def loadFile(self):
        # print "loadFile called!"
        self.root.filename = tkFileDialog.askopenfilename(
            initialdir=".", title="Select file...")
        # print (self.root.filename)
        # self.l2.config(text=self.root.filename)

    def save_to_file(self):
        if self.results_window:
            self.root.outfile = tkFileDialog.asksaveasfile(
                mode='w',
                defaultextension=".txt",
                initialdir=".",
                initialfile="output",
                title="Save as...")
            data = str(self.results_text.get(0.0, END))
            self.root.outfile.write(data)
            self.root.outfile.close()

    def checkAll(self):
        all_checked = 1
        for test in self.tests + self.slowtests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.tests + self.slowtests:
            eval('self.run_' + test.__name__).set(val)

    def checkFast(self):
        all_checked = 1
        for test in self.tests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.tests:
            eval('self.run_' + test.__name__).set(val)

    def checkSlow(self):
        all_checked = 1
        for test in self.slowtests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.slowtests:
            eval('self.run_' + test.__name__).set(val)

    def text_insert(self, text, noret=False):
        if not self.results_window:
            self.__make_results_window()
        place = 'end'
        if not self.results_text:
            raise Exception("results_text does not exist")
        if type(text) != str:
            raise TypeError("Expected str, got %s: %s" % (type(text), text))
        # self.results_text.configure(state="normal")  # enables changing content
        self.results_text.insert(place, text + ["\n", ""][noret])
        self.update_idletasks()
        # self.results_text.configure(state="disabled") # relocks the content

    def getn(self):
        return int(self.nt.get("1.0", END))

    def setn(self, n):
        self.nt.delete(1.0, END)
        self.nt.insert(END, str(int(n)))

    def runTests(self):
        if self.results_window:
            self.__delete_results_window()
        cont = True
        try:
            n = self.getn()
            if n < 0:
                raise ValueError
        except Exception as e:
            print 'Error:', e
            self.setn("0")
            cont = False
        if cont:
            try:
                if self.root.filename == "":
                    raise ValueError("No file selected")
                e = read_data(self.root.filename)
                if n == 0:
                    n = len(e)
                e = e[:n]
                if len(e) == 0:
                    raise LengthError("No data in file")
                out = "Data read:\n"
                out += "e = "
                out += "".join([str(i) for i in e][:min(32, len(e))])
                out += ["", "..."][len(e) > 32] + "\n"
                out += "See test_results folder for detailed results\n"
                self.text_insert(out)
            except:
                self.text_insert("Failed to read data.")
                cont = False
        if cont:
            # for test in self.tests:
            #   self.text_insert("self.run_" + test.__name__ + " = " + str(eval(
            #                    "self.run_" + test.__name__ + ".get()")))
            test_dir = "./test_results"
            if not os.path.exists(test_dir):
                os.makedirs(test_dir)
            for test in self.tests + self.slowtests:
                try:
                    if eval("self.run_" + test.__name__ + ".get()"):
                        self.text_insert("Running " + test.__name__ + ":")
                        output = test(e)
                        self.text_insert(["Non-Random", "Random"][output])
                        self.text_insert("\n")
                except Exception as e:
                    self.text_insert("\nError in %s: %s\n" %
                                     (test.__name__, e.__str__()))

            self.text_insert("Tests completed.")
Example #56
0
class MSTM_studio:

    splash_time = 0.5  # time to show splash window, seconds

    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        top.withdraw()
        time_start = time.time()
        splash = sup.SplashWindow(top)
        self.style = ttk.Style()
        if sys.platform == 'win32':
            self.style.theme_use('winnative')
        self.style.configure('.', font='TkDefaultFont')

        #~ top.geometry('838x455+364+117')
        top.geometry('850x440')
        top.title('MSTM studio')
        #~ top.configure(highlightcolor='black')
        self.load_images()
        self.root_panedwin = ttk.Panedwindow(top, orient='horizontal')
        self.root_panedwin.place(relx=0.0,
                                 rely=0.0,
                                 relheight=1.0,
                                 relwidth=1.0)

        self.root_panedwin.configure(width=200)
        self.left_frame = ttk.Frame(width=220.0)
        self.root_panedwin.add(self.left_frame)
        #~ self.middle_frame = ttk.Labelframe(width=350, text='View')
        self.middle_frame = ttk.Frame(width=350)
        self.root_panedwin.add(self.middle_frame)
        self.right_frame = ttk.Frame()
        self.root_panedwin.add(self.right_frame)
        self.__funcid0 = self.root_panedwin.bind('<Map>', self.__adjust_sash0)

        self.left_panedwin = ttk.Panedwindow(self.left_frame,
                                             orient='vertical')
        self.left_panedwin.place(relx=0.0,
                                 rely=0.0,
                                 relheight=1.0,
                                 relwidth=1.0)
        self.left_panedwin.configure(width=200)

        self.materials_frame = ttk.Labelframe(height=105, text='Materials')
        self.left_panedwin.add(self.materials_frame)
        self.spheres_frame = ttk.Labelframe(text='Spheres')
        self.left_panedwin.add(self.spheres_frame)
        self.__funcid1 = self.left_panedwin.bind('<Map>', self.__adjust_sash1)

        self.style.configure('Treeview.Heading', font='TkDefaultFont')
        self.stvMaterial = ScrolledTreeView(self.materials_frame)
        self.stvMaterial.place(relx=0.0, y=30, relheight=0.8, relwidth=1.0)
        self.configure_stvMaterial()
        self.stvMaterial.bind('<Double-1>', sup.btChangeMatColClick)

        self.btAddMat = ttk.Button(self.materials_frame,
                                   command=sup.btAddMatClick,
                                   text='A',
                                   image=self.imAdd)
        self.btAddMat.place(x=5, y=0, height=25, width=25)

        self.btLoadMat = ttk.Button(self.materials_frame,
                                    command=sup.btLoadMatClick,
                                    text='L',
                                    image=self.imLoad)
        self.btLoadMat.place(x=30, y=0, height=25, width=25)

        self.btPlotMat = ttk.Button(self.materials_frame,
                                    command=sup.btPlotMatClick,
                                    text='P',
                                    image=self.imPlot)
        self.btPlotMat.place(x=55, y=0, height=25, width=25)

        self.btDelMat = ttk.Button(self.materials_frame,
                                   command=sup.btDelMatClick,
                                   text='D',
                                   image=self.imDelete)
        self.btDelMat.place(relx=1, x=-30, rely=0, height=25, width=25)

        self.stvSpheres = ScrolledTreeView(self.spheres_frame)
        self.stvSpheres.place(relx=0.0, y=30, relheight=0.85, relwidth=1.0)
        self.configure_stvSpheres()
        self.stvSpheres.bind('<Double-1>', sup.btEditSphClick)

        self.btAddSph = ttk.Button(self.spheres_frame,
                                   command=sup.btAddSphClick,
                                   text='A',
                                   image=self.imAdd)
        self.btAddSph.place(x=5, y=0, height=25, width=25)

        self.btEditSph = ttk.Button(self.spheres_frame,
                                    command=sup.btEditSphClick,
                                    text='E',
                                    image=self.imEdit)
        self.btEditSph.place(x=30, y=0, height=25, width=25)

        self.btPlotSph = ttk.Button(self.spheres_frame,
                                    command=sup.btPlotSphClick,
                                    text='R',
                                    image=self.imRefresh)
        self.btPlotSph.place(x=55, y=0, height=25, width=25)

        self.lbEnvMat = ttk.Label(self.spheres_frame, text='Matrix')
        self.lbEnvMat.place(relx=0.45, y=-5)
        self.cbEnvMat = ttk.Combobox(self.spheres_frame)
        self.cbEnvMat.place(relx=0.45, y=10, width=55)

        self.btDelSph = ttk.Button(self.spheres_frame,
                                   command=sup.btDelSphClick,
                                   text='D',
                                   image=self.imDelete)
        self.btDelSph.place(relx=1.0, y=0, x=-30, height=25, width=25)

        self.middle_panedwin = ttk.Panedwindow(self.middle_frame,
                                               orient='vertical')
        self.middle_panedwin.place(relx=0.0,
                                   rely=0.0,
                                   relheight=1.0,
                                   relwidth=1.0)
        #~ self.middle_panedwin.configure(relwidth=1.0)
        self.canvas_frame = ttk.Labelframe(height=360, text='View')
        self.middle_panedwin.add(self.canvas_frame)
        self.spectrum_frame = ttk.Labelframe(height=-40, text='Spectrum')
        self.middle_panedwin.add(self.spectrum_frame)
        self.__funcid2 = self.left_panedwin.bind('<Map>', self.__adjust_sash2)

        self.canvas = Canvas(self.canvas_frame)
        self.canvas.place(relx=0.0, rely=0, relheight=1.0, relwidth=1.0)
        self.canvas.configure(background='white')
        self.canvas.configure(borderwidth='2')
        self.canvas.configure(relief='ridge')
        self.canvas.configure(selectbackground='#c4c4c4')
        self.canvas.bind('<Button-4>', sup.mouse_wheel)  # for Linux
        self.canvas.bind('<Button-5>', sup.mouse_wheel)  # for Linux
        self.canvas.bind('<MouseWheel>', sup.mouse_wheel)  # for Windowz
        self.canvas.bind('<Button-3>', sup.mouse_down)
        self.canvas.bind('<B3-Motion>', sup.mouse_move)
        self.canvas.bind('<ButtonRelease-3>', sup.mouse_up)

        self.lbZoom = ttk.Label(
            self.canvas, text='x1.00',
            background='white')  #font=('courier', 18, 'bold'), width=10)
        self.lbZoom.place(relx=1.0, x=-50, rely=1.0, y=-25)

        self.lbLambdaMin = ttk.Label(self.spectrum_frame, text='min')
        self.lbLambdaMin.place(x=5, y=0)
        self.edLambdaMin = ttk.Entry(self.spectrum_frame)
        self.edLambdaMin.place(x=5, y=15, width=35)
        self.edLambdaMin.insert(0, '300')

        self.lbLambdaMax = ttk.Label(self.spectrum_frame, text='max')
        self.lbLambdaMax.place(x=45, y=0)
        self.edLambdaMax = ttk.Entry(self.spectrum_frame)
        self.edLambdaMax.place(x=45, y=15, width=35)
        self.edLambdaMax.insert(0, '800')

        self.lbLambdaCount = ttk.Label(self.spectrum_frame, text='count')
        self.lbLambdaCount.place(x=85, y=0)
        self.edLambdaCount = ttk.Entry(self.spectrum_frame)
        self.edLambdaCount.place(x=85, y=15, width=35)
        self.edLambdaCount.insert(0, '51')

        self.btCalcSpec = ttk.Button(self.spectrum_frame,
                                     command=sup.btCalcSpecClick,
                                     text='Calculate',
                                     image=self.imCalc,
                                     compound='left')
        self.btCalcSpec.place(x=130, y=10, width=90, height=25)

        self.lbSpecScale = ttk.Label(self.spectrum_frame, text='scale')
        self.lbSpecScale.place(relx=1, x=-115, y=0)
        self.edSpecScale = ttk.Entry(self.spectrum_frame)
        self.edSpecScale.place(relx=1, x=-115, y=15, width=50)
        self.edSpecScale.insert(0, '1')

        self.btSaveSpec = ttk.Button(self.spectrum_frame,
                                     command=sup.btSaveSpecClick,
                                     text='S',
                                     image=self.imSave)
        self.btSaveSpec.place(relx=1, x=-55, y=10, width=25, height=25)

        self.btPlotSpec = ttk.Button(self.spectrum_frame,
                                     command=sup.btPlotSpecClick,
                                     text='P',
                                     image=self.imPlot)
        self.btPlotSpec.place(relx=1, x=-30, y=10, width=25, height=25)

        self.right_panedwin = ttk.Panedwindow(self.right_frame,
                                              orient='vertical')
        self.right_panedwin.place(relx=0.0,
                                  rely=0.0,
                                  relheight=1.0,
                                  relwidth=1.0)

        self.right_panedwin.configure(width=200)
        self.plot_frame = ttk.Labelframe(height=200, text='Plot')
        self.right_panedwin.add(self.plot_frame)
        self.contribs_frame = ttk.Labelframe(height=150,
                                             text='Other contributions')
        self.right_panedwin.add(self.contribs_frame)
        self.fitting_frame = ttk.Labelframe(height=-50, text='Fitting')
        self.right_panedwin.add(self.fitting_frame)
        self.__funcid3 = self.right_panedwin.bind('<Map>', self.__adjust_sash3)

        # CONTRIBUTIONS
        self.btAddContrib = ttk.Button(self.contribs_frame,
                                       command=sup.btAddContribClick,
                                       text='A',
                                       image=self.imAdd)
        self.btAddContrib.place(x=5, y=0, height=25, width=25)

        self.btPlotAllContribs = ttk.Button(self.contribs_frame,
                                            command=sup.btPlotAllContribsClick,
                                            text='P',
                                            image=self.imPlot)
        self.btPlotAllContribs.place(x=30, y=0, height=25, width=25)

        self.btDelContrib = ttk.Button(self.contribs_frame,
                                       command=sup.btDelContribClick,
                                       text='D',
                                       image=self.imDelete)
        self.btDelContrib.place(relx=1.0, y=0, x=-30, height=25, width=25)

        self.cbContribs = []
        self.edContribs = []  # actually, it will be the list of lists [[]]
        self.btPlotsContrib = []
        self.contribs_list = [
            'ConstBkg', 'LinearBkg', 'LorentzBkg', 'Mie single', 'Mie LN',
            'Lorentz peak', 'Gauss peak', 'Au film', 'bst-3Au/glass'
        ]
        self.cbContribMats = []
        self.btContribDistribPlots = []

        # Fitting frame
        self.edExpFileName = ttk.Entry(self.fitting_frame,
                                       text='Exp. file name')
        self.edExpFileName.place(x=5, y=0, height=25, relwidth=0.8)

        self.btLoadExp = ttk.Button(self.fitting_frame,
                                    command=sup.btLoadExpClick,
                                    text='L',
                                    image=self.imLoad)
        self.btLoadExp.place(relx=1.0, x=-55, y=0, height=25, width=25)

        self.btPlotExp = ttk.Button(self.fitting_frame,
                                    command=sup.btPlotExpClick,
                                    text='P',
                                    image=self.imPlot)
        self.btPlotExp.place(relx=1.0, x=-30, y=0, height=25, width=25)

        self.btStartFit = ttk.Button(self.fitting_frame,
                                     command=sup.btStartFitClick,
                                     text='>',
                                     image=self.imPlay)
        self.btStartFit.place(x=5, y=30, height=25, width=25)

        self.btStopFit = ttk.Button(self.fitting_frame,
                                    command=sup.btStopFitClick,
                                    text='|',
                                    image=self.imStop)
        self.btStopFit.place(x=30, y=30, height=25, width=25)

        self.lbChiSq = ttk.Label(self.fitting_frame, text='ChiSq:')
        self.lbChiSq.place(x=60, y=35)

        self.btConstraints = ttk.Button(self.fitting_frame,
                                        command=sup.btConstraintsClick,
                                        text='Constraints...')
        self.btConstraints.place(relx=1, x=-100, y=30, height=25, width=95)

        self._create_menu(top)

        time_delta = time.time() - time_start  # in seconds
        if time_delta < self.splash_time:
            time.sleep(self.splash_time - time_delta)
        top.deiconify()
        splash.destroy()

    def configure_stvMaterial(self):
        self.stvMaterial.configure(columns='Col1')
        self.stvMaterial.heading('#0', text='MatID')
        self.stvMaterial.heading('#0', anchor='center')
        self.stvMaterial.column('#0', width='46')
        self.stvMaterial.column('#0', minwidth='20')
        self.stvMaterial.column('#0', stretch='1')
        self.stvMaterial.column('#0', anchor='w')
        self.stvMaterial.heading('Col1', text='Name')
        self.stvMaterial.heading('Col1', anchor='center')
        self.stvMaterial.column('Col1', width='150')
        self.stvMaterial.column('Col1', minwidth='20')
        self.stvMaterial.column('Col1', stretch='1')
        self.stvMaterial.column('Col1', anchor='w')

    def configure_stvSpheres(self):
        self.stvSpheres.configure(columns='Col1 Col2 Col3 Col4 Col5')
        self.stvSpheres.heading('#0', text='ID')
        self.stvSpheres.heading('#0', anchor='center')
        self.stvSpheres.column('#0', width='34')
        self.stvSpheres.column('#0', minwidth='20')
        self.stvSpheres.column('#0', stretch='1')
        self.stvSpheres.column('#0', anchor='w')
        self.stvSpheres.heading('Col1', text='R')
        self.stvSpheres.heading('Col1', anchor='center')
        self.stvSpheres.column('Col1', width='37')
        self.stvSpheres.column('Col1', minwidth='20')
        self.stvSpheres.column('Col1', stretch='1')
        self.stvSpheres.column('Col1', anchor='w')
        self.stvSpheres.heading('Col2', text='X')
        self.stvSpheres.heading('Col2', anchor='center')
        self.stvSpheres.column('Col2', width='31')
        self.stvSpheres.column('Col2', minwidth='20')
        self.stvSpheres.column('Col2', stretch='1')
        self.stvSpheres.column('Col2', anchor='w')
        self.stvSpheres.heading('Col3', text='Y')
        self.stvSpheres.heading('Col3', anchor='center')
        self.stvSpheres.column('Col3', width='34')
        self.stvSpheres.column('Col3', minwidth='20')
        self.stvSpheres.column('Col3', stretch='1')
        self.stvSpheres.column('Col3', anchor='w')
        self.stvSpheres.heading('Col4', text='Z')
        self.stvSpheres.heading('Col4', anchor='center')
        self.stvSpheres.column('Col4', width='34')
        self.stvSpheres.column('Col4', minwidth='20')
        self.stvSpheres.column('Col4', stretch='1')
        self.stvSpheres.column('Col4', anchor='w')
        self.stvSpheres.heading('Col5', text='mID')
        self.stvSpheres.heading('Col5', anchor='center')
        self.stvSpheres.column('Col5', width='32')
        self.stvSpheres.column('Col5', minwidth='20')
        self.stvSpheres.column('Col5', stretch='1')
        self.stvSpheres.column('Col5', anchor='w')

    def load_images(self):
        def tryload(fn):
            try:
                im = ImageTk.PhotoImage(file=os.path.normpath(
                    os.path.join(os.path.dirname(__file__), 'images', fn)))
            except Exception as err:
                print('Can not load %s\n%s' % (fn, err))
                return None
            return im

        self.imLoad = tryload('folder_open_icon&16.png')
        self.imDelete = tryload('delete_icon&16.png')
        self.imPlot = tryload('chart_bar_icon&16.png')
        self.imPlot2 = tryload('chart_bar2_icon&16.png')
        self.imAdd = tryload('sq_plus_icon&16.png')
        self.imSave = tryload('save_icon&16.png')
        self.imRefresh = tryload('refresh_icon&16.png')
        self.imExport = tryload('export_icon&16.png')
        self.imImport = tryload('import_icon&16.png')
        self.imPlay = tryload('playback_play_icon&16.png')
        self.imStop = tryload('playback_stop_icon&16.png')
        self.imCalc = tryload('cogs_icon&16.png')
        self.imEdit = tryload('doc_edit_icon&16.png')
        self.imExit = tryload('on-off_icon&16.png')
        self.imBrush = tryload('brush_icon&16.png')
        self.imZoomIn = tryload('round_plus_icon&16.png')
        self.imZoomOut = tryload('round_minus_icon&16.png')

    def __adjust_sash0(
            self,
            event):  # mysterious functions left from previous civilizations
        paned = event.widget
        pos = [
            220,
            575,
        ]
        i = 0
        for sash in pos:
            paned.sashpos(i, sash)
            i += 1
        paned.unbind('<map>', self.__funcid0)
        del self.__funcid0

    def __adjust_sash1(self, event):
        paned = event.widget
        pos = [
            145,
        ]
        i = 0
        for sash in pos:
            paned.sashpos(i, sash)
            i += 1
        paned.unbind('<map>', self.__funcid1)
        del self.__funcid1

    def __adjust_sash2(self, event):
        paned = event.widget
        pos = [
            200,
        ]
        i = 0
        for sash in pos:
            paned.sashpos(i, sash)
            i += 1
        paned.unbind('<map>', self.__funcid2)
        del self.__funcid2

    def __adjust_sash3(self, event):
        paned = event.widget
        pos = [
            200,
        ]
        i = 0
        for sash in pos:
            paned.sashpos(i, sash)
            i += 1
        paned.unbind('<map>', self.__funcid3)
        del self.__funcid3

    def _create_menu(self, top):
        self.menubar = Menu(top)

        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label='Import spheres...',
                                  command=sup.btImportSpheres,
                                  image=self.imImport,
                                  compound='left')
        self.filemenu.add_command(label='Export spheres...',
                                  command=sup.btExportSpheres,
                                  image=self.imExport,
                                  compound='left')
        self.filemenu.add_separator()
        self.filemenu.add_command(label='Exit',
                                  command=sup.destroy_window,
                                  image=self.imExit,
                                  compound='left')
        self.menubar.add_cascade(label='File', menu=self.filemenu)

        self.matmenu = Menu(self.menubar, tearoff=0)
        self.matmenu.add_command(label='Add constant...',
                                 command=sup.btAddMatClick,
                                 image=self.imAdd,
                                 compound='left')
        self.matmenu.add_command(label='Load function...',
                                 command=sup.btLoadMatClick,
                                 image=self.imLoad,
                                 compound='left')
        self.matmenu.add_separator()
        self.matmenu.add_command(label='Delete selected',
                                 command=sup.btDelMatClick,
                                 image=self.imDelete,
                                 compound='left')
        self.matmenu.add_separator()
        self.matmenu.add_command(label='Plot selected',
                                 command=sup.btPlotMatClick,
                                 image=self.imPlot,
                                 compound='left')
        self.matmenu.add_separator()
        self.matmenu.add_command(label='Change view color...',
                                 command=sup.btChangeMatColClick,
                                 image=self.imBrush,
                                 compound='left')
        self.menubar.add_cascade(label='Materials', menu=self.matmenu)

        self.sphmenu = Menu(self.menubar, tearoff=0)
        self.sphmenu.add_command(label='Add...',
                                 command=sup.btAddSphClick,
                                 image=self.imAdd,
                                 compound='left')
        self.sphmenu.add_separator()
        self.sphmenu.add_command(label='Edit selected...',
                                 command=sup.btEditSphClick,
                                 image=self.imEdit,
                                 compound='left')
        self.sphmenu.add_command(label='Delete selected',
                                 command=sup.btDelSphClick,
                                 image=self.imDelete,
                                 compound='left')
        self.sphmenu.add_separator()
        self.sphmenu.add_command(label='Generate on mesh...',
                                 command=sup.btGenerateSpheresClick)
        self.menubar.add_cascade(label='Spheres', menu=self.sphmenu)

        self.viewmenu = Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label='Zoom in',
                                  command=lambda: sup.mouse_wheel(
                                      type('', (), {
                                          'num': 4,
                                          'delta': 0
                                      })()),
                                  image=self.imZoomIn,
                                  compound='left')
        self.viewmenu.add_command(label='Zoom out',
                                  command=lambda: sup.mouse_wheel(
                                      type('', (), {
                                          'num': 5,
                                          'delta': 0
                                      })()),
                                  image=self.imZoomOut,
                                  compound='left')
        self.viewmenu.add_command(label='Reset view',
                                  command=sup.btPlotSphClick,
                                  image=self.imRefresh,
                                  compound='left')
        self.menubar.add_cascade(label='View', menu=self.viewmenu)

        self.opticsmenu = Menu(self.menubar, tearoff=0)
        self.opticsmenu.add_command(label='Calculate',
                                    command=sup.btCalcSpecClick,
                                    image=self.imCalc,
                                    compound='left')
        self.menubar.add_cascade(label='Spectrum', menu=self.opticsmenu)

        self.fittingmenu = Menu(self.menubar, tearoff=0)
        self.fittingmenu.add_command(label='Load experiment...',
                                     command=sup.btLoadExpClick,
                                     image=self.imLoad,
                                     compound='left')
        self.fittingmenu.add_separator()
        self.fittingmenu.add_command(label='Constraints...',
                                     command=sup.btConstraintsClick)
        self.fittingmenu.add_separator()
        self.fittingmenu.add_command(label='Start fit',
                                     command=sup.btStartFitClick,
                                     image=self.imPlay,
                                     compound='left')
        self.fittingmenu.add_command(label='Stop fit',
                                     command=sup.btStopFitClick,
                                     image=self.imStop,
                                     compound='left')
        self.menubar.add_cascade(label='Fitting', menu=self.fittingmenu)

        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label='About', command=sup.btAboutClick)
        self.menubar.add_cascade(label='Help', menu=self.helpmenu)
        # display the menu
        top.config(menu=self.menubar)