def setup_widgets(self): """Five control widgets created along bottom""" # clear button clear_button = Button(self, text="Clear") clear_button.grid(row=3, column=1, padx=5, pady=5, sticky=W) clear_button.bind("<ButtonRelease-1>", self.clear_text) # Silent/Verbose select verbose_check = Checkbutton(self, text="Silent", \ variable=self.verbose_flag, onvalue="-s", offvalue="") verbose_check.grid(row=3, column=2, padx=5, pady=5) # Analysis model menu choices2 = ['Select Model', 'model1', 'model2'] om2 = OptionMenu(self, self.model, *choices2) # pylint: disable=W0142 om2.grid(row=3, column=3, padx=10, pady=20) # EMR Server Region menu choices = ['Select Region', 'Oregon', 'California', 'Virginia'] om1 = OptionMenu(self, self.region, *choices) # pylint: disable=W0142 om1.grid(row=3, column=4, padx=10, pady=20) # Run EMR button emrbutton = Button(self, text="Run EMR") emrbutton.grid(row=3, column=5, padx=5, pady=5) emrbutton.bind("<ButtonRelease-1>", self.run_emr)
def _add_check(self, frame, index, name, default, option) : self.variables[-1] = StringVar() self.variables[-1].set('') label = Label(frame, text=name) label.grid(row=index, column=0, sticky='W', padx=10) field = Checkbutton(frame, variable=self.variables[-1], onvalue=option, offvalue='') field.grid(row=index, column=1, sticky='WE')
def initPopup(self): self.var1 = IntVar() cb = Checkbutton(self, text=str("Osteolysis"), variable=self.var1) cb.grid(row=0, column=0, padx=15, pady=20, sticky=E) self.var2 = IntVar() cb = Checkbutton(self, text=str("Synovitis"), variable=self.var2) cb.grid(row=0, column=1, pady=20, sticky=W) printButton = Button(self, text="Submit", command=self.setVars) printButton.grid(row=1, column=0, padx=15, sticky=E) printButton = Button(self, text="Close", command=self.destroy) printButton.grid(row=1, column=1, sticky=W)
def checkbutton_component(self, s, r, c, init_val=False, mode=NORMAL, onvalue=-1, offvalue=-1): '''adds a checkbutton, and its associated variable''' if onvalue == -1: var = BooleanVar() var.set(init_val) btn = Checkbutton(self,text=s, variable=var) else: var = StringVar() var.set(init_val) btn = Checkbutton(self,text=s, variable=var, onvalue=onvalue, offvalue=offvalue) btn.grid(row=r, column=c, columnspan=2, sticky=W) btn.config(state=mode) return var
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent #Determines which checkbox is active. self.option = 0 #Setup window. self.parent.title("REA5PE") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) #Create label lbl = Label(self, text="Select the format PE file.") lbl.grid(sticky=W) #Create checkbox 1 self.var = IntVar() cb = Checkbutton(self, text="Show .txt", variable=self.var, command=self.onClick) cb.grid(row=1, column=0, sticky=W) #Create checkbox 2 self.var2 = IntVar() cb2 = Checkbutton(self, text="Show Console", variable=self.var2, command=self.onClick2) cb2.grid(row=2, column=0, sticky=W) #Entry form self.e1 = Entry(self) self.e1.grid(row=3, column=0) self.e1.focus_set() #Currently owns focus #Submission abtn = Button(self, text="Disassemble", command=self.onClickDisassemble) abtn.grid(row=4, column=0, sticky=W+E)
def checkbutton_component(self, s, r, c, init_val=False, mode=NORMAL, onvalue=-1, offvalue=-1): '''adds a checkbutton, and its associated variable''' if onvalue == -1: var = BooleanVar() var.set(init_val) btn = Checkbutton(self, text=s, variable=var) else: var = StringVar() var.set(init_val) btn = Checkbutton(self, text=s, variable=var, onvalue=onvalue, offvalue=offvalue) btn.grid(row=r, column=c, columnspan=2, sticky=W) btn.config(state=mode) return var
def make_checkbutton(self, f, s, r, c): v = BooleanVar() ch = Checkbutton(f, text=s, variable=v) ch.grid(row=r, column=c, columnspan=2, sticky=W) return v, ch
class A_DWI: def __init__(self, container, frame, label='', text='', row=0, column=0): self.container = container self.is_b0 = BooleanVar(container.parent) self.is_dw = BooleanVar(container.parent) self.column = column self.direction = StringVar(container.parent) self.label_from = Label(frame, text='from') self.text_from = Entry(frame) self.text_from.insert(0, text) self.button_file_from = Button(frame, text='...', command=lambda:filenameDialog_text(self.text_from)) self.button_rm = Button(frame, text='remove', command=self.click_remove) self.radio_ap = Radiobutton(frame, text='AP', variable=self.direction, value='AP', command=self.set_direction) self.radio_pa = Radiobutton(frame, text='PA', variable=self.direction, value='PA', command=self.set_direction) self.label_to = Label(frame, text='to') self.text_to = Entry(frame) #self.text_to.insert(0, text) self.button_file_to = Button(frame, text='Gen', command=self.set_filename_to) self.check_b0 = Checkbutton(frame, text='B0', variable=self.is_b0) self.check_dw = Checkbutton(frame, text='DWI', variable=self.is_dw) self.button_up = Button(frame, text='up', width=3, command=self.click_up) self.button_dn = Button(frame, text='down', width=3, command=self.click_dn) self.row = -1 self.change_row(row) if text != '': self.set_appa() self.set_filename_to() def prefix(self): return self.container.parent.prefix() def set_direction(self): pass def get_dwi_filenames(self): ''' :return: [('from', 'to'), ('from', 'to')] ''' filename_from = self.text_from.get() filename_to = self.text_to.get() if self.is_dw.get(): rtn = [ [filename_from, filename_to] ] filename_b_from = filename_wo_ext(filename_from) filename_b_to = filename_wo_ext(filename_to) rtn.append( [filename_b_from+'.bval', filename_b_to+'.bval'] ) rtn.append( [filename_b_from+'.bvec', filename_b_to+'.bvec'] ) return rtn return [] def get_b0_filename(self): ''' :return: [('from', 'to')] ''' filename_from = self.text_from.get() filename_to = self.text_to.get() ext = extname(filename_to) if self.is_b0.get(): if self.is_dw.get(): filename_to = '%s_B0%s' % (filename_wo_ext(filename_to), ext) return [ [filename_from, filename_to] ] return [] def set_appa(self): filename_from = self.text_from.get() basename_from = os.path.basename(filename_from) basename_b_from = filename_wo_ext(basename_from) if 'pa' in basename_b_from.lower(): self.direction.set('PA') elif 'ap' in basename_b_from.lower(): self.direction.set('AP') else: pass def set_filename_to(self, middle=None): filename_from = self.text_from.get() basename_from = os.path.basename(filename_from) number = os.path.dirname(filename_from).split('/')[-1].split('_')[0] if number == '': number = str(self.row) else: try: int(number) except: number = str(self.row) ext = extname(basename_from) intermediate = self.direction.get() if intermediate == '': intermediate = 'DWI' if self.is_b0.get() and not self.is_dw.get(): intermediate += '_B0' self.text_to.delete(0, len(self.text_to.get())) self.text_to.insert(0, '%s%s_%s%s' % (self.prefix(), number, intermediate, ext)) def change_row(self, row): if self.row == row: return self.row = row i = 2*row j = self.column j += 0; self.button_up.grid(row=i, column=j) j += 1; self.label_from.grid(row=i, column=j) j += 1; self.text_from.grid(row=i, column=j, sticky=EW) j += 1; self.button_file_from.grid(row=i, column=j) j += 1; self.button_rm.grid(row=i, column=j) j += 1; self.radio_ap.grid(row=i, column=j) j += 1; self.radio_pa.grid(row=i, column=j) i += 1 j = 0 j += 0; self.button_dn.grid(row=i, column=j) j += 1; self.label_to.grid(row=i, column=j) j += 1; self.text_to.grid(row=i, column=j, sticky=EW) j += 1; self.button_file_to.grid(row=i, column=j) j += 1 j += 1; self.check_b0.grid(row=i, column=j) j += 1; self.check_dw.grid(row=i, column=j) def click_remove(self): self.container.remove(self.row) self.button_up.destroy() self.label_from.destroy() self.text_from.destroy() self.button_file_from.destroy() self.button_rm.destroy() self.radio_ap.destroy() self.radio_pa.destroy() self.button_dn.destroy() self.label_to.destroy() self.text_to.destroy() self.button_file_to.destroy() self.check_b0.destroy() self.check_dw.destroy() def click_up(self): self.container.up(self.row) def click_dn(self): self.container.dn(self.row)
def __init__(self, parent, txt=dict()): """Instanciating the output workbook.""" self.parent = parent Frame.__init__(self) # subframe self.FrDb = Labelframe(self, name='database', text=txt.get('gui_fr2', "SGBD")) # DB variables self.opt_pgvw = IntVar(self.FrDb) # able/disable PostGIS views self.host = StringVar(self.FrDb, 'localhost') self.port = IntVar(self.FrDb, 5432) self.dbnb = StringVar(self.FrDb) self.user = StringVar(self.FrDb, 'postgres') self.pswd = StringVar(self.FrDb) # Form widgets self.ent_H = Entry(self.FrDb, textvariable=self.host) self.ent_P = Entry(self.FrDb, textvariable=self.port, width=5) self.ent_D = Entry(self.FrDb, textvariable=self.dbnb) self.ent_U = Entry(self.FrDb, textvariable=self.user) self.ent_M = Entry(self.FrDb, textvariable=self.pswd, show='*') caz_pgvw = Checkbutton(self.FrDb, text=txt.get('gui_views', "Views enabled"), variable=self.opt_pgvw) # Label widgets self.lb_H = Label(self.FrDb, text=txt.get('gui_host', "Host")) self.lb_P = Label(self.FrDb, text=txt.get('gui_port', "Port")) self.lb_D = Label(self.FrDb, text=txt.get('gui_db', "Database")) self.lb_U = Label(self.FrDb, text=txt.get('gui_user', "User")) self.lb_M = Label(self.FrDb, text=txt.get('gui_mdp', "Password")) # widgets placement self.ent_H.grid(row=1, column=1, columnspan=2, sticky="NSEW", padx=2, pady=2) self.ent_P.grid(row=1, column=3, columnspan=1, sticky="NSE", padx=2, pady=2) self.ent_D.grid(row=2, column=1, columnspan=1, sticky="NSEW", padx=2, pady=2) self.ent_U.grid(row=2, column=3, columnspan=1, sticky="NSEW", padx=2, pady=2) self.ent_M.grid(row=3, column=1, columnspan=3, sticky="NSEW", padx=2, pady=2) self.lb_H.grid(row=1, column=0, sticky="NSEW", padx=2, pady=2) self.lb_P.grid(row=1, column=3, sticky="NSW", padx=2, pady=2) self.lb_D.grid(row=2, column=0, sticky="NSW", padx=2, pady=2) self.lb_U.grid(row=2, column=2, sticky="NSW", padx=2, pady=2) self.lb_M.grid(row=3, column=0, sticky="NSWE", padx=2, pady=2) caz_pgvw.grid(row=4, column=0, sticky="NSWE", padx=2, pady=2) # frame position self.FrDb.grid(row=3, column=1, sticky="NSWE", padx=2, pady=2)
def __init__(self, parent, txt=dict(), path_browser=None, path_var=""): """Instanciating the output workbook.""" self.p = parent self.txt = txt Frame.__init__(self) # -- VARIABLES ------------------------------------------------------- self.target_path = StringVar() # formats / type: vectors self.li_vectors_formats = (".shp", ".tab", ".kml", ".gml", ".geojson" ) # vectors handled self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.li_kml = [] # list for KML path self.li_gml = [] # list for GML path self.li_geoj = [] # list for GeoJSON paths self.li_gxt = [] # list for GXT paths self.li_vectors = [] # list for all vectors # formats / type: rasters self.li_raster = [] # list for rasters paths self.li_raster_formats = (".ecw", ".tif", ".jp2") # raster handled # formats / type: file databases self.li_fdb = [] # list for all files databases self.li_egdb = [] # list for Esri File Geodatabases self.li_spadb = [] # list for Spatialite Geodatabases # formats / type: CAO/DAO self.li_cdao = [] # list for all CAO/DAO files self.li_dxf = [] # list for AutoCAD DXF paths self.li_dwg = [] # list for AutoCAD DWG paths self.li_dgn = [] # list for MicroStation DGN paths # formats / type: maps documents self.li_mapdocs = [] # list for all map & documents self.li_pdf = [] # list for GeoPDF path self.li_lyr = [] # list for LYR path self.li_mxd = [] # list for MXD path self.li_qgs = [] # list for QGS path # -- Source path ----------------------------------------------------- self.FrPath = Labelframe(self, name='files', text=txt.get('gui_fr1', "Path")) # target folder self.lb_target = Label(self.FrPath, text=txt.get('gui_path')) self.ent_target = Entry(master=self.FrPath, width=35, textvariable=self.target_path) self.btn_browse = Button(self.FrPath, text=u"\U0001F3AF " + txt.get('gui_choix', "Browse"), command=lambda: self.get_target_path(r"."), takefocus=True) self.btn_browse.focus_force() # widgets placement self.lb_target.grid(row=1, column=1, columnspan=1, sticky="NSWE", padx=2, pady=2) self.ent_target.grid(row=1, column=2, columnspan=1, sticky="NSWE", padx=2, pady=2) self.btn_browse.grid(row=1, column=3, sticky="NSE", padx=2, pady=2) # -- Format filters -------------------------------------------------- self.FrFilters = Labelframe(self, name='filters', text=txt.get('gui_fr3', "Filters")) # formats options self.opt_shp = IntVar(self.FrFilters) # able/disable shapefiles self.opt_tab = IntVar(self.FrFilters) # able/disable MapInfo tables self.opt_kml = IntVar(self.FrFilters) # able/disable KML self.opt_gml = IntVar(self.FrFilters) # able/disable GML self.opt_geoj = IntVar(self.FrFilters) # able/disable GeoJSON self.opt_gxt = IntVar(self.FrFilters) # able/disable GXT self.opt_egdb = IntVar(self.FrFilters) # able/disable Esri FileGDB self.opt_spadb = IntVar(self.FrFilters) # able/disable Spatalite DB self.opt_rast = IntVar(self.FrFilters) # able/disable rasters self.opt_cdao = IntVar(self.FrFilters) # able/disable CAO/DAO files self.opt_pdf = IntVar(self.FrFilters) # able/disable Geospatial PDF self.opt_lyr = IntVar(self.FrFilters) # able/disable Geospatial Lyr self.opt_mxd = IntVar(self.FrFilters) # able/disable Geospatial MXD self.opt_qgs = IntVar(self.FrFilters) # able/disable Geospatial QGS # format choosen: check buttons caz_shp = Checkbutton(self.FrFilters, text=u'.shp', variable=self.opt_shp) caz_tab = Checkbutton(self.FrFilters, text=u'.tab', variable=self.opt_tab) caz_kml = Checkbutton(self.FrFilters, text=u'.kml', variable=self.opt_kml) caz_gml = Checkbutton(self.FrFilters, text=u'.gml', variable=self.opt_gml) caz_geoj = Checkbutton(self.FrFilters, text=u'.geojson', variable=self.opt_geoj) caz_gxt = Checkbutton(self.FrFilters, text=u'.gxt', variable=self.opt_gxt) caz_egdb = Checkbutton(self.FrFilters, text=u'Esri FileGDB', variable=self.opt_egdb) caz_spadb = Checkbutton(self.FrFilters, text=u'Spatialite', variable=self.opt_spadb) caz_rast = Checkbutton(self.FrFilters, text=u'rasters ({0})'.format(', '.join( self.li_raster_formats)), variable=self.opt_rast) caz_cdao = Checkbutton(self.FrFilters, text=u'CAO/DAO', variable=self.opt_cdao) caz_pdf = Checkbutton(self.FrFilters, text=u'Geospatial PDF', variable=self.opt_pdf) self.caz_lyr = Checkbutton(self.FrFilters, text=u'.lyr', variable=self.opt_lyr) self.caz_mxd = Checkbutton(self.FrFilters, text=u'.mxd', variable=self.opt_mxd) caz_qgs = Checkbutton(self.FrFilters, text=u'.qgs', variable=self.opt_qgs) # widgets placement caz_shp.grid(row=1, column=0, sticky="NSWE", padx=2, pady=2) caz_tab.grid(row=1, column=1, sticky="NSWE", padx=2, pady=2) caz_kml.grid(row=1, column=2, sticky="NSWE", padx=2, pady=2) caz_gml.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) caz_geoj.grid(row=1, column=4, sticky="NSWE", padx=2, pady=2) caz_gxt.grid(row=1, column=7, sticky="NSWE", padx=2, pady=2) caz_pdf.grid(row=1, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_rast.grid(row=2, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_egdb.grid(row=2, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_cdao.grid(row=2, column=4, columnspan=1, sticky="NSWE", padx=2, pady=2) caz_spadb.grid(row=2, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_lyr.grid(row=3, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_mxd.grid(row=3, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_qgs.grid(row=3, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # frames placement self.FrPath.grid(row=3, column=1, padx=2, pady=2, sticky="NSWE") self.FrFilters.grid(row=4, column=1, padx=2, pady=2, sticky="NSWE")
def set_optional_buttons(self, supervoxel_id_path=None): """ Set bottoms to quit, change axis, show and hide segmentation, ... at the upper row of the main frame. """ _sub_frame1 = Frame(self) _sub_frame1.grid(column=0, row=0, padx=10, sticky=['n', 'e', 'w']) _sub_sub_frame1 = Frame(_sub_frame1) _sub_sub_frame1.grid(column=0, row=0, sticky=['e', 'w'], pady=10) ind = 0 self.button_axis = Button(_sub_sub_frame1, text="Change axis", command=self.change_axis) self.button_axis.grid(column=0, row=ind, pady=3) ind += 1 self.button_axis = Button(_sub_sub_frame1, text="Mirror Images", command=self.mirror_image) self.button_axis.grid(column=0, row=ind, pady=3) ind = 0 if self.segm is not None: _sub_sub_frame2 = Frame(_sub_frame1) _sub_sub_frame2.grid(column=0, row=1, sticky=['e', 'w'], pady=10) _sub_sub_frame3 = Frame(_sub_frame1) _sub_sub_frame3.grid(column=0, row=2, sticky=['e', 'w'], pady=10) self.button_supervoxels = Button(_sub_sub_frame2, text="Show/Hide supervoxels", command=self.change_supervoxels) self.button_supervoxels.grid(column=0, row=ind, sticky=['w', 'n', 'e']) if supervoxel_id_path is None: self.button_supervoxels['state'] = 'disabled' ind += 1 self.tumor_checkbox_label = Label(_sub_sub_frame2, text="Display tumor type: ", relief=FLAT) self.tumor_checkbox_label.grid(column=0, row=ind) ind += 1 self.tumor_cb = [] for i in range(len(labels)): tumor_button = IntVar() this_text = '%s (%s <%s>)' % (labels[i], label_colors_d[i], label_hot_keys[i+1]) button = Checkbutton(_sub_sub_frame2, text=this_text, variable=tumor_button, command=lambda arg0=i: self.change_segm(arg0)) button.grid(column=0, row=ind, sticky=['w', 'n', 'e']) self.tumor_cb.append(tumor_button) ind += 1 self.all_tumor_bc = IntVar() button = Checkbutton(_sub_sub_frame2, text="All tumors", variable=self.all_tumor_bc, command=lambda : self.change_segm(3)) button.grid(column=0, row=ind, sticky=['w', 'n', 'e']) ind += 1 self.no_tumor_bc = IntVar() button = Checkbutton(_sub_sub_frame2, text="No tumors", variable=self.no_tumor_bc, command=lambda : self.change_segm(4)) button.grid(column=0, row=ind, sticky=['w', 'n', 'e']) ind += 1 alpha_label = Label(_sub_sub_frame2, text="Opacity:") alpha_label.grid(column=0, row=ind) self.alpha_scale = Scale(_sub_sub_frame2, from_=0.0, to=1.0, command=self.set_alpha, orient=HORIZONTAL) ind += 1 self.alpha_scale.set(self.alpha) self.alpha_scale.grid(column=0, row=ind, columnspan=self.image_nb, sticky=['w', 'n', 'e']) ind = 0 self.button_save_segm = Button(_sub_sub_frame3, text="Save segmentation", command=self.save_segm) self.button_save_segm.grid(column=0, row=ind, sticky=['w', 'n', 'e']) ind += 1 self.button_open_segm = Button(_sub_sub_frame3, text="Open segmentation", command=self.open_segm) self.button_open_segm.grid(column=0, row=ind, sticky=['w', 'n', 'e'])
class Principal(Frame): # Class for helping Tooltips class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text, lang): self.text = text if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() + 27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass label = Label(tw, text=self.text[lang], justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() # Initialization function def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # Spiral parameters (defined as StringVars for convenience) self.a = StringVar() self.a.set('0') self.b = StringVar() self.b.set('0.5') self.c = StringVar() self.c.set('1') self.lMax = StringVar() self.lMax.set(158) self.frec = StringVar() self.frec.set(500) self.StringLongitud = StringVar() self.StringRadio = StringVar() # Help mode flag self.ayuda = False # Figure object self.f = Figure(figsize=(5, 5)) self.initUI() # Tooltip creator function (allowed by help mode flag) def createToolTip(self, widget, text): toolTip = self.ToolTip(widget) def enter(event): if self.ayuda: toolTip.showtip(text, self.lang) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) # Euclidean distance calculator function def distancia(self, r1, phi1, r2, phi2): return sqrt(r1**2 + r2**2 - 2 * r1 * r2 * cos(phi1 - phi2)) # Polar to Cartesian coordinates def pol2cart(self, rho, phi): x = rho * cos(phi) y = rho * sin(phi) return (x, y) # def grafico(self): # Set figure size self.f = Figure(figsize=(5, 5)) # Check whether negative parameters are present and show an error if float(self.c.get()) < 0 or float(self.b.get()) < 0: print self.lang tkMessageBox.showerror("Error", self.error.get()) return # Set figure axis ax = self.f.add_subplot(111, polar=True) # Initialize r and theta lists at the center point self.theta_disc = [0] self.r_disc = [0] self.theta_disc_n = [0] # Initialize length value and list l = 0 l_vec = [] # Loop limited by antenna length while l < int(self.lMax.get()): # Length of each antenna segment in cm, computed as 1/15 of the wave length lseg = 300 / float(self.frec.get()) * 100 / 15 if self.tipoCurva.get() == 1: # Archimedean spiral # New theta values are calculated according to the following: # In an Archimedean spiral # /r - a\ c # theta = |-------| # \ b / # In order to get an approximately equally spaced segments, new theta values are computed according to the next formula. This formula has been worked # out gradually, not basing on any well-known expression. # /0.5 * lseg - a\ c # |----------------| - lseg # \ b / # ------------------------------ + lseg # 10 * theta + 1 # n # theta = theta + --------------------------------------- # n + 1 n r + 1 # n self.theta_disc.append(self.theta_disc[-1] + \ (( ((0.5*lseg - float(self.a.get()))/float(self.b.get()))**(float(self.c.get())) - lseg) / (10*self.theta_disc[-1] + 1) + lseg) \ / (self.r_disc[-1] + 1)) # print str(lseg) # print str(self.r_disc[-1]) else: # print "Eh: " + str(self.theta_disc[-1]) # print "Ra: " + str(self.r_disc[-1]) # print "Ls: " + str(lseg) # print "Ot: " + str(log(0.5*lseg/float(self.a.get()))/float(self.b.get())) self.theta_disc.append(self.theta_disc[-1] + \ (( max(log(0.5*lseg/float(self.a.get()))/float(self.b.get()),float(self.a.get())) - lseg) * exp(-1*self.theta_disc[-1]) + lseg) \ / (self.r_disc[-1] + 1)) #print str(lseg) #print str(self.r_disc[-1]) if self.tipoCurva.get() == 1: self.r_disc.append( float(self.b.get()) * self.theta_disc[-1]**(1 / float(self.c.get())) + float(self.a.get())) elif self.tipoCurva.get() == 2: self.r_disc.append( float(self.a.get()) * exp(float(self.b.get()) * self.theta_disc[-1])) self.theta_disc_n.append(pi + self.theta_disc[-1]) l_vec.append( self.distancia(self.r_disc[-1], self.theta_disc[-1], self.r_disc[-2], self.theta_disc[-2])) l += l_vec[-1] if self.fuente.get() and str( self.checkFuente.cget('state')) == 'normal': self.theta_disc.remove(0) self.r_disc.remove(0) self.theta_disc_n.remove(0) ax.plot([self.theta_disc[0], self.theta_disc_n[0]], [self.r_disc[0], self.r_disc[0]], color='r') ax.plot([0], [0], color='m', marker='o', markersize=5) self.StringLongitud.set("%#.1f cm" % l) self.StringRadio.set("%#.1f cm" % max(self.r_disc)) ax.plot(self.theta_disc, self.r_disc, color='b', marker='.', markersize=4) if self.espejar.get(): ax.plot(self.theta_disc_n, self.r_disc, color='g', marker='.', markersize=4) ax.set_rmax(max(self.r_disc)) ax.grid(True) #with open('distancias.csv', 'wb') as f: # writer = csv.writer(f) # writer.writerows(izip(self.theta_disc, l_vec)) def regraficar(self): self.grafico() self.canvas.get_tk_widget().pack_forget() self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) #canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1, padx=10, pady=10) def cambiaFormula(self): curvas = [ '''R0lGODlhbAAWAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABsABYAAAT+8MlJq7046817ToYnjmRpXsqpriw3JGgrz2pDHHDFFHTvezjL4kcsWoKUBIHCQDQQxmhy4EhZDATGkoKcEHIPwjIBkJoljsZVEFIwuGDJUJJwhM7ngN0i4D0YcxJdDwVqEg0CeC0DHQhlOokSCJGCcVYSAYyHiiaaGwOXEwCGDwqRBQgOC28PBqEPCAgMDDANgH8MCnEzAQSxCFufHQ6xuSF6FACeFgwBG1AHCwYGaSgC19jZAssViHQOrMIbelsIQwoHCuoLDsFCGwUgDn67LXVgDvUX3BeOEw0OHgCAcmgeBgME4QUssoBSgQMe+Am5lOqBQQkKHq0gIHEGMS9yHU1lO6CN34FwDamBOZBQhYCWGERqyyaxjp8HLyNuoOYMDYI6//awcNDzh0oJ1HiEy9CRwsIHDSBanCBg6YkCT4kA8EPAToGiTDkIgGEAQM8XsAKtuGUkgRsoYqxiaDrBbS4wbmNx2iuBLt+/HNQCfhABADs=''', '''R0lGODlhQwASAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABDABIAAATn8MlJq70463ZSJQyhjWSpGUe1BM/imXCcNQvVDNLQyHz/KAOGgiXYPQAsn7IEKDwKg4SDgCA4DMtsBiVpCAqALk5LrhRqPwIt5yy7H4GaAWBIKJ7391uBULyoIhMNDDUMQi9uAVQIVRQJCAyMMAgPBwsGBg5GFAoCnp+gAmMXXhJSDBOEE3kkBQmZbYhkUogOLwEHWHCBJgUOehMLAhMFKTlBkG0wBKN6DpQSzBMOqD4C0BmdoaHNE1LK1xKwSg5Jepkv46gOyk+yGr7AE03RVwUsCrwF1SWq8g92Ij0gAGIClUjmSEQAADs=''', '''''' ] formula = PhotoImage(data=curvas[self.tipoCurva.get() - 1]) self.formulaLabel.configure(image=formula) self.formulaLabel.image = formula if self.tipoCurva.get() == 1: self.parC.config(state=NORMAL) self.labelC.config(state=NORMAL) else: self.parC.config(state=DISABLED) self.labelC.config(state=DISABLED) def activarFuente(self): if self.espejar.get(): self.checkFuente.config(state=NORMAL) else: self.checkFuente.config(state=DISABLED) def escribirFichero(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.nec' options['filetypes'] = [('NEC2 files', '.nec'), ('all files', '.*')] options['initialdir'] = '~/Documentos/Antenas/Espirales' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save NEC' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) r_final = list(reversed(self.r_disc)) + self.r_disc theta_final = list(reversed(self.theta_disc_n)) + self.theta_disc x_ant, y_ant = self.pol2cart(r_final[0], theta_final[0]) tipoCurvaExt = ['Archimedean', 'Logarithmic'] fich.write('CM Created with PySAD\n') fich.write('CM L = %#.1f\n' % float(self.lMax.get())) fich.write('CM ' + tipoCurvaExt[int(self.tipoCurva.get()) - 1] + ' spiral') fich.write('CM a = ' + self.a.get()) fich.write('CM b = ' + self.b.get()) if int(self.tipoCurva.get()) == 0: fich.write('CM c = ' + self.c.get()) fich.write('CE\n') print len(r_final) for i in range(len(r_final) - 1): x, y = self.pol2cart(r_final[i + 1], theta_final[i + 1]) linea = 'GW\t%#d\t%#d\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\n' % ( i + 1, 1, x_ant / 100, y_ant / 100, 0, x / 100, y / 100, 0, 0.001) fich.write(linea) x_ant, y_ant = x, y fich.write('GE\t0\nGN\t-1\nEK\n') fich.write('EX\t%#d\t%#d\t%#d\t%#d\t%#d\t%#d\n' % (0, len(r_final) / 2, 1, 0, 1, 0)) fich.write('FR\t0\t0\t0\t0\t299.8\t0\nEN') fich.close() def escribirPDF(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.pdf' options['filetypes'] = [('PDF files', '.pdf'), ('all files', '.*')] options['initialdir'] = '~' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save PDF' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) #self.f.axis('off') matplotlib.rcParams.update({'font.size': 1}) self.f.gca().axes.get_xaxis().set_visible(False) self.f.gca().axes.get_yaxis().set_visible(False) papeles_w = [21, 29.7, 42, 59.4, 84.1] papeles_h = [29.7, 42, 59.4, 84.1, 118.9] for i_pap in range(0, len(papeles_w) - 1): if 2 * max(self.r_disc) < papeles_w[i_pap]: break print i_pap self.f.set_size_inches(papeles_w[i_pap] / 2.54, papeles_h[i_pap] / 2.54) noMargen = dict(pad=72 * (papeles_w[i_pap] - 2 * max(self.r_disc)) / 2 / 2.54, h_pad=0, w_pad=0) self.f.set_tight_layout(noMargen) self.f.suptitle('test title') self.f.savefig(fich, format='pdf', dpi='90') fich.close() def mostrarAyuda(self): self.ayuda = not self.ayuda if self.ayuda: self.helpButton.state(["pressed"]) self.config(cursor="question_arrow") else: self.helpButton.state(["!pressed"]) self.config(cursor="") def initText(self): self.curTip = StringVar() self.ArcSpi = StringVar() self.LogSpi = StringVar() self.aaa = StringVar() self.bbb = StringVar() self.ccc = StringVar() self.Lma = StringVar() self.fre = StringVar() self.Mir = StringVar() self.Sou = StringVar() self.Gen = StringVar() self.lenlen = StringVar() self.radrad = StringVar() self.error = StringVar() def updateText(self, lang): self.lang = lang if lang == 0: self.espButton.state(["pressed"]) self.engButton.state(["!pressed"]) else: self.engButton.state(["pressed"]) self.espButton.state(["!pressed"]) self.stringText = { 'curTip': ["Tipo de curva", "Curve type"], 'ArcSpi': ["Espiral de Arquímedes", "Archimedean spiral "], 'LogSpi': ["Espiral logarítmica", "Logarithmic spiral"], 'aaa': ["a (cm)", "a (cm)"], 'bbb': ["b (cm/rad)", "b (cm/rad)"], 'ccc': ["c", "c"], 'Lma': ["Lmax (cm)", "Lmax (cm)"], 'fre': ["frec (MHz)", "freq (MHz)"], 'LmaToo': [ "Longitud máxima de cada brazo de la antena", "Maximum length of each antenna's branch" ], 'FreToo': [ "Frecuencia de diseño (aumentar para disminuir la longitud de los segmentos)", "Design frequency (increase for decreasing segment length)" ], 'Mir': ["Espejar", "Mirror"], 'MirToo': [ "Crea otra rama de la espiral girada 180º", "Create another spiral branch, twisted 180º" ], 'Sou': ["Colocar fuente", "Put source"], 'SouToo': [ "Une las dos mitades y crea una fuente NEC2 en el centro", "Join both halves and create a NEC2 source at the middle" ], 'Gen': ["Generar", "Generate"], 'GenToo': [ "Genera la espiral con los parámetros indicados", "Generate spiral following given parameters" ], 'NEC': ["NEC", "NEC"], 'NECToo': [ "Guarda la espiral como archivo NEC2", "Save the spiral as a NEC2 file" ], 'PDF': ["PDF", "PDF"], 'PDFToo': [ "Imprime la espiral a tamaño real en un documento PDF (máximo A0)", "Print the real sized spiral into a PDF document (A0 maximum)" ], 'HHH': ["H", "H"], 'lenlen': ["Longitud:", "Length:"], 'radrad': ["Radio:", "Radius:"], 'error': [ "No se permiten valores negativos de b o c", "Negative values of b or c are not allowed" ] } self.curTip.set(self.stringText['curTip'][self.lang]) self.ArcSpi.set(self.stringText['ArcSpi'][self.lang]) self.LogSpi.set(self.stringText['LogSpi'][self.lang]) self.aaa.set(self.stringText['aaa'][self.lang]) self.bbb.set(self.stringText['bbb'][self.lang]) self.ccc.set(self.stringText['ccc'][self.lang]) self.Lma.set(self.stringText['Lma'][self.lang]) self.fre.set(self.stringText['fre'][self.lang]) self.Mir.set(self.stringText['Mir'][self.lang]) self.Sou.set(self.stringText['Sou'][self.lang]) self.Gen.set(self.stringText['Gen'][self.lang]) self.lenlen.set(self.stringText['lenlen'][self.lang]) self.radrad.set(self.stringText['radrad'][self.lang]) self.error.set(self.stringText['error'][self.lang]) def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0, columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva, value=1, command=self.cambiaFormula, width=17).grid(row=1, columnspan=2, sticky=W, padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva, value=2, command=self.cambiaFormula).grid(row=2, columnspan=2, sticky=W, padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame, textvariable=self.aaa).grid(row=5, column=0, pady=2) Label(editarFrame, textvariable=self.bbb).grid(row=6, column=0, pady=2) self.labelC = Label(editarFrame, textvariable=self.ccc) self.labelC.grid(row=7, column=0, pady=2) self.labelC.config(state=DISABLED) Label(editarFrame, textvariable=self.Lma).grid(row=8, column=0, pady=2) Label(editarFrame, textvariable=self.fre).grid(row=9, column=0, pady=2) parA = Entry(editarFrame, width=4, textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame, width=4, textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame, width=4, textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame, width=4, textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame, width=4, textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage( data= '''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''' ) saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3, textvariable=self.lenlen).grid(row=1, column=0, pady=4, padx=12) Label(frame3, textvariable=self.radrad).grid(row=2, column=0, pady=4, padx=12) Label(frame3, textvariable=self.StringLongitud).grid(row=1, column=1, pady=4) Label(frame3, textvariable=self.StringRadio).grid(row=2, column=1, pady=4) def onExit(self): self.quit()
class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.levels = list() self.signs = list() self.items = [i for i in range(0,64)] self.items.remove(16) self.current_item = 0 self.parent = parent self.max_width = 600 self.max_height = 600 self.client = Client() self.initDimensions() self.initUI() self.event = None self.reset_canvas() def connect(self): res = self.client.regis() if(res == 1): time.sleep(1) self.connect_button.config(state = 'disabled') self.disconnect_button.config(state = 'normal') def disconnect(self): self.client.close() self.connect_button.config(state = 'normal') self.disconnect_button.config(state = 'disabled') def initDimensions(self): self.canvas_width = self.max_width self.canvas_height = self.max_height self.rows = 10 self.cols = 10 # self.h = 1; self.cellwidth = self.canvas_width/self.cols self.cellheight = self.canvas_height/self.rows self.initData() def add_new_level(self): temp=dict() temp2 = dict() self.levels.append(temp) self.signs.append(temp2) def insert_new_level(self, loc): temp=dict() temp2 = dict() self.levels.insert(loc,temp) self.signs.insert(loc,temp2) def initData(self): self.levels = list() self.signs = list() self.rect = dict() self.rect_text = dict() self.curr_level = 0 self.overlay_level = 0 self.overlayToggle = False self.levels.append(dict()) self.signs.append(dict()) self.current_item = 1 def reset_canvas(self): self.canvas.delete(ALL) self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols)) def redraw_overlay(self): c = set(self.levels[self.overlay_level].keys()) if self.overlayToggle == 1: for key in c: x1 = key[1] * self.cellwidth y1 = (self.rows - key[0] - 1) * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight if (key[0], key[1]) in self.rect: self.canvas.itemconfig(self.rect[key[0],key[1]], width = OVERLAYWIDTH) else: self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill='white', outline = 'black', width = OVERLAYWIDTH, tag = 'block') self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = '', font=('verdana', 7), tag = 'blocktext') def redraw_level(self): # self.canvas.delete(ALL) # self.rect=dict() # self.rect_text = dict() start = time.clock() b = set(self.levels[self.curr_level].keys()) for key in b: val = self.levels[self.curr_level][key] if (key[0], key[1]) in self.rect: self.canvas.itemconfig(self.rect[key[0],key[1]], fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH) self.canvas.itemconfig(self.rect_text[key[0],key[1]], text = val) else: x1 = key[1] * self.cellwidth y1 = (self.rows - key[0] - 1) * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight self.rect[key[0],key[1]] = self.canvas.create_rectangle(x1,y1,x2,y2, fill = COLORS[val], outline = 'black', width = DEFAULTWIDTH, tag = 'block') self.rect_text[key[0],key[1]] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = val, font=('verdana', 7), tag = 'blocktext') items_to_remove = list() for key in self.rect: if key not in self.levels[self.curr_level]: self.canvas.delete(self.rect[key[0],key[1]]) self.canvas.delete(self.rect_text[key[0],key[1]]) items_to_remove.append(key) for i in items_to_remove: self.rect.pop(i) self.rect_text.pop(i) self.parent.title("Craft Builder: Dimensions: " + str(self.rows) + 'x' + str(len(self.levels)) +'x' + str(self.cols)) self.redraw_overlay() def updateDimensions(self,r,c,y=1): self.rows = r self.cols = c self.cellwidth = self.max_width/self.cols self.cellheight = self.max_height/self.rows if(self.cellwidth<=self.cellheight): self.cellheight = self.cellwidth else: self.cellwidth = self.cellheight self.canvas_height = self.rows * self.cellheight self.canvas_width = self.cols * self.cellwidth self.canvas.config(width = self.canvas_width, height = self.canvas_height) self.canvas.delete(ALL) self.initData() for i in range(y-1): self.levels.append(dict()) self.signs.append(dict()) def altMenu(self, event): # print "Keycode:", event.keycode, "State:", event.keysym, event.type self.event = event if event.type == '2': self.altAction = True self.clear_button.config(text = 'Multi Clear', bg = 'white') self.delete_button.config(text = 'Multi Delete', bg='white') self.insert_button.config(text = 'Multi Insert', bg='white') self.copy_level_button.config(text = 'Multi Copy', bg = 'white') elif event.type == '3': defaultbg = self.parent.cget('bg') self.altAction = False self.clear_button.config(text = 'Clear Level', bg = defaultbg) self.delete_button.config(text = 'Delete', bg = defaultbg) self.insert_button.config(text = 'Insert', bg = defaultbg) self.copy_level_button.config(text = 'Copy overlay level', bg = defaultbg) sys.stdout.flush() def initUI(self): self.altAction = False self.parent.title("Craft Builder") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=0) self.columnconfigure(0, pad = 7) self.columnconfigure(1, pad = 7) self.columnconfigure(2, pad = 7) self.columnconfigure(9, weight =1 ) self.columnconfigure(3, pad=7) self.columnconfigure(5, pad=7) self.rowconfigure(1, weight=1) self.rowconfigure(5, pad=7) self.rowconfigure(6, pad=7) self.rowconfigure(7, pad=7) self.rowconfigure(8, pad=7) area = Frame(self, width=500, height=500, borderwidth = 2, relief = 'sunken') area.grid(row=1, column=0, columnspan=11, rowspan=4, padx=5, sticky=E+W+S+N) self.canvas = Canvas(area, bg='white', width=self.canvas_width, height=self.canvas_height) self.canvas.pack() self.canvas.bind("<Button-1>", self.callbackLeftClick) self.canvas.bind("<B1-Motion>", self.callbackLeftClick) self.canvas.bind("<Button-3>", self.callbackRightClick) self.canvas.bind("<B3-Motion>", self.callbackRightClick) self.canvas.bind("<Button-5>", self.scrollWheel) self.canvas.bind("<Button-4>", self.scrollWheel) self.parent.bind("<Shift_L>", self.altMenu) self.parent.bind("<KeyRelease-Shift_L>", self.altMenu) self.new_button = Button(self, text="New", command = self.onNew, width = 6) self.new_button.grid(row=5, column=0) save_button = Button(self, text="Save", command = self.onSave, width = 6) save_button.grid(row=6, column=0) load_button = Button(self, text="Load", command = self.onLoad, width = 6) load_button.grid(row=7, column=0) self.connect_button = Button(self, text="Connect", command = self.connect, width = 6) self.connect_button.grid(row=8, column=0) self.clear_button = Button(self, text="Clear Level", command = self.onClear, width =8) self.clear_button.grid(row=5, column=1) self.delete_button = Button(self, text="Delete Level", command = self.onDelete, width =8) self.delete_button.grid(row=6, column=1) self.insert_button = Button(self, text="Insert Level", command = self.onInsertLevel, width =8) self.insert_button.grid(row=7, column=1) self.disconnect_button = Button(self, text="Disconnect", command = self.disconnect, width = 8) self.disconnect_button.grid(row=8, column=1) self.disconnect_button['state'] = 'disabled' lbl_a = Label(self, text="Curr. Level", font=("Verdana", 10)) lbl_a.grid(row = 5, column = 2) lbl_b = Label(self, text="Overlay Level", font=("Verdana", 10)) lbl_b.grid(row = 6, column = 2) self.copy_level_button = Button(self, text="Copy overlay level", command = self.onCopy, width = 12) self.copy_level_button.grid(row=7, column=2, columnspan=1) load_world_button = Button(self, text="Load from world", command = self.onLoadFromWorld, width = 12) load_world_button.grid(row=8, column=2) self.currLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly') self.currLevelCombo.grid(row = 5, column = 3) self.currLevelCombo.bind("<<ComboboxSelected>>", self.currLevelChooser) self.currLevelCombo.set(0) self.overlayLevelCombo = Combobox(self, values = range(len(self.levels)), width = 5, state = 'readonly') self.overlayLevelCombo.grid(row = 6, column = 3) self.overlayLevelCombo.bind("<<ComboboxSelected>>", self.overlayLevelChooser) self.overlayLevelCombo.set(0) self.new_level_button = Button(self, text="New Level", command = self.onNewLevel, width = 12) self.new_level_button.grid(row=7, column=3,columnspan=1) paste_button = Button(self, text="Paste in world", command = self.onPaste, width = 12) paste_button.grid(row=8, column=3) lbl_d = Label(self, text="Item", font=("Verdana", 10)) lbl_d.grid(row = 5, column = 4) self.toggle = Checkbutton(self, text="Overlay Toggle", command = self.onToggle) self.toggle.grid(row=6, column=4) rotate_button = Button(self, text="Rotate", command = self.onRotate, width = 12) rotate_button.grid(row=7, column=4,columnspan=1) paste_sign_button = Button(self, text="Paste Signs", command = self.onPasteSign, width = 12) paste_sign_button.grid(row=8, column=4) self.itemCombo = Combobox(self, values = self.items, width = 5, state = 'readonly') self.itemCombo.grid(row = 5, column = 5) self.itemCombo.bind("<<ComboboxSelected>>", self.itemChooser) self.itemCombo.set(1) self.current_item = 1 self.lbl_e = Label(self, text="", font=("Verdana", 8), width = 12, relief = 'ridge') self.lbl_e.grid(row = 6, column = 5) add_geo_button = Button(self, text="Add Geometry", command = self.addGeo, width = 12) add_geo_button.grid(row=8, column=5) try: global builder import builder except ImportError: add_geo_button.config(state = 'disabled') def scrollWheel(self, event): if event.num == 5: #scroll down if self.curr_level==len(self.levels) -1: pass else: self.curr_level = self.curr_level + 1 self.currLevelCombo.set(self.curr_level) self.redraw_level() else: #scroll up if self.curr_level == 0: pass else: self.curr_level = self.curr_level - 1 self.currLevelCombo.set(self.curr_level) self.redraw_level() def onInsertLevel(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter num_levels to insert and level below which to insert\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split(' ') try: if len(data) == 2: for i in range(int(data[0])): self.insert_new_level(int(data[1])) self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: self.insert_new_level(self.curr_level) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.redraw_level() def onCopy(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_level num_times\n" + "and level above which to copy, all seperated by spaces.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split(' ') try: if len(data) == 4: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) n = data[2] l = int(data[3]) + 1 for i in range(int(n)): for j in range(st, sto +1): for col in range(self.cols): for row in range(self.rows): if (row,col) in self.levels[j]: if l+j-st < len(self.levels) : self.levels[l+j-st][row,col] = self.levels[j][row,col] l = l +(sto-st+1) else: print 'Not enough arguments' except ValueError: print 'Error in values' else: for col in range(self.cols): for row in range(self.rows): if (row,col) in self.levels[self.overlay_level]: self.levels[self.curr_level][row,col] = self.levels[self.overlay_level][row,col] sys.stdout.flush() self.redraw_level() def onClear(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to clear\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split() try: if len(data) == 2: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) for i in range(st,sto+1): if i < len(self.levels): self.levels[i] = dict() self.signs[i] = dict() self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: if tkMessageBox.askquestion('Clear', "Clear Level: " + str(self.curr_level)) == 'yes': self.levels[self.curr_level] = dict() self.signs[self.curr_level] = dict() self.redraw_level() else: pass def onDelete(self): if self.altAction == 1: self.w=popupWindow(self,title = "Enter the arguments start_level end_levels to delete\n" + "seperated by a space.") self.wait_window(self.w.top) self.altAction = 0 data = self.w.value.split() try: if len(data) == 2: st,sto = sorted((data[0],data[1])) st = int(st) sto = int(sto) for i in range(sto,st-1,-1): if i < len(self.levels) and i >=0 and len(self.levels)>1: self.levels.pop(i) self.signs.pop(i) elif i < len(self.levels) and i ==0 : self.levels[i] = dict() self.signs[i] = dict() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.curr_level = 0 self.currLevelCombo.set(0) self.overlayLevelCombo.set(0) self.redraw_level() else: print 'Not enough arguments' except ValueError: print 'Error in values' else: if tkMessageBox.askquestion('Delete', "Delete Level: " + str(self.curr_level)) == 'yes': if len(self.levels) == 1: self.onClear() else: self.levels.pop(self.curr_level) self.signs.pop(self.curr_level) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 if self.curr_level != 0: self.curr_level = self.curr_level - 1 self.currLevelCombo.set(self.curr_level) else: self.currLevelCombo.set(self.curr_level) self.redraw_level() def addGeo(self): self.w=popupWindow(self,title = "Enter Command: help for Help") self.wait_window(self.w.top) try: c = self.w.value.split(' ') if c[0] == 'help': self.h = HelpWindow(self, title = 'Enter command followed by args seperated by spaces\n' + 'Available commands (sphere, pyramid, cuboid)\n' + '1. pyramid x1 x2 y z1 z2 fill(0/1) \n' + '2. sphere cx cy cz r fill(0/1) \n' + '4. circle_x x y z r fill(0/1) \n' + '5. circle_y x y z r fill(0/1) \n' + '6. circle_z x y z r fill(0/1) \n' + '7. cylinder_x x1 x2 y z r fill(0/1) \n' + '8. cylinder_y x y1 y2 z r fill(0/1) \n' + '9. cylinder_z x y z1 z2 r fill(0/1) \n' + '10. cuboid x1 x2 y1 y2 z1 z2 fill(0/1) \n' ) elif c[0] == 'sphere': if len(c) - 1 == 5: result = builder.sphere(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >=0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'pyramid': if len(c) - 1 == 6: result = builder.pyramid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_x': if len(c) - 1 == 5: result = builder.circle_x(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_y': if len(c) - 1 == 5: result = builder.circle_y(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'circle_z': if len(c) - 1 == 5: result = builder.circle_z(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_x': if len(c) - 1 == 6: x1,x2 = sorted([int(c[1]),int(c[2])]) result = builder.cylinder_x(x1,x2,int(c[3]),int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_y': if len(c) - 1 == 6: y1,y2 = sorted([int(c[2]),int(c[3])]) result = builder.cylinder_y(int(c[1]),y1,y2,int(c[4]),int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cylinder_z': if len(c) - 1 == 6: z1,z2 = sorted([int(c[3]),int(c[4])]) result = builder.cylinder_z(int(c[1]),int(c[2]),z1,z2,int(c[5]),int(c[6])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item elif c[0] == 'cuboid': if len(c) - 1 == 7: result = builder.cuboid(int(c[1]),int(c[2]),int(c[3]),int(c[4]),int(c[5]),int(c[6]),int(c[7])) for i in result: if i[1] < len(self.levels) and i[1] >= 0: if i[0] < self.rows and i[0] >=0 and i[2] < self.cols and i[2] >=0: self.levels[i[1]][i[0],i[2]] = self.current_item pass newLevels = list() for i, j in enumerate(self.levels): temp = dict() for key, val in j.iteritems(): if int(val) != 0: temp[key] = val newLevels.append(temp) self.levels = newLevels self.redraw_level() except RuntimeError: pass def onPaste(self): self.w=popupWindow(self,title = "On world, facing north (i.e x increases ahead of you,\n"+ "and z increases to your right.\n" + "Enter origin point (x y z) seperated by spaces: eg. 12 12 12:") self.wait_window(self.w.top) data = self.w.value.split(' ') try: xo = int(data[0]) yo = int(data[1]) zo = int(data[2]) if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes': print 'Pasting' count = 0 for j,i in enumerate(self.levels): for key,value in i.iteritems(): xr = int(xo + key[0]) yr = int(yo + j) zr = int(zo + key[1]) # self.client.client_send(xr,yr,zr,0) if int(value) != 0: self.client.client_send(xr,yr,zr,int(value)) count = count + 1 if count % NUMPERSEC == 0: time.sleep(1) else: pass except ValueError: pass def onPasteSign(self): self.w=popupWindow(self,title = "Facing north, enter origin point(x y z): eg. 12 12 12:") self.wait_window(self.w.top) data = self.w.value.split(' ') try: xo = int(data[0]) yo = int(data[1]) zo = int(data[2]) if tkMessageBox.askquestion('Coords', "Is this (x,y,z) correct: " + str(xo) +',' +str(yo) + ',' + str(zo)) == 'yes': print 'Pasting' count = 0 for j,i in enumerate(self.signs): for key,value in i.iteritems(): xr = int(xo + key[0]) yr = int(yo + j) zr = int(zo + key[1]) for num,val in enumerate(value): if val!=-1: # print j,i,num, val self.client.client_send_sign(xr, yr, zr, num, val) sys.stdout.flush() except ValueError: pass def onLoadFromWorld(self): self.w=popupWindow(self,title = "Enter bottom left point: (x y z)") self.wait_window(self.w.top) try: [x1,y1,z1] = [int(i) for i in self.w.value.split(' ')] self.w=popupWindow(self,title = "Enter top right point: (x y z)") self.wait_window(self.w.top) [x2,y2,z2] = [int(i) for i in self.w.value.split(' ')] x1,x2 = sorted([x1,x2]) y1,y2 = sorted([y1,y2]) z1,z2 = sorted([z1,z2]) if tkMessageBox.askquestion('Coords', "Bottom left: " + str(x1) +',' +str(y1) + ',' + str(z1) + '\n' + \ "Top right: " + str(x2) +',' +str(y2) + ',' + str(z2)) == 'yes': print 'Copying',x1,y1,z1,' to',x2,y2,z2 data = self.client.read_db(x1,y1,z1,x2,y2,z2, db_name) signs = self.client.read_signs(x1,y1,z1,x2,y2,z2, db_name) newData = list() for i in data: temp = dict() for key,value in i.iteritems(): if value != 0: temp[key[0], key[1]] = value newData.append(temp) newSignData = list() for i in signs: temp = dict() for key,value in i.iteritems(): temp[key[0], key[1]] = value newSignData.append(temp) if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 self.updateDimensions(x2-x1+1, z2-z1+1, len(newData)) self.reset_canvas() self.levels = newData self.signs = newSignData sys.stdout.flush() self.redraw_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except ValueError: pass def onSave(self): filename = asksaveasfilename(parent=self) pickle.dump({'Dimensions' : [self.rows,self.cols,len(self.levels)],'Levels' : self.levels, 'Signs' : self.signs}, open(filename, 'wb')) def onLoad(self): if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 filename = askopenfilename(parent=self) try: obj = pickle.load(open(filename, 'rb')) self.updateDimensions(int(obj['Dimensions'][0]), int(obj['Dimensions'][1]), int(obj['Dimensions'][2])) self.reset_canvas() self.levels = obj['Levels'] if 'Signs' in obj: self.signs = obj['Signs'] self.redraw_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except IOError: pass def onToggle(self): if self.overlayToggle == 0: self.overlayToggle =1 self.redraw_level() else: self.overlayToggle = 0 self.redraw_level() def onNewLevel(self): self.add_new_level() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.redraw_level() def onRotate(self): self.rotatedData = list() self.rotatedSignData = list() for i in self.levels: temp = dict() for key,value in i.iteritems(): xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90))) zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90))) temp[int(math.floor(xr)),int(math.floor(zr))] = value self.rotatedData.append(temp) sign_map = {0:2, 3:0, 1:3, 2:1, 6:5, 7:6, 4:7, 5:4} #FOR ROTATION CALCULATION for i in self.signs: temp = dict() for key,value in i.iteritems(): xr = (key[0] * math.cos(math.radians(-90)) - (key[1]) * math.sin(math.radians(-90))) zr = (key[0] * math.sin(math.radians(-90)) + (key[1]) * math.cos(math.radians(-90))) new_value = [value[sign_map[0]], value[sign_map[1]], value[sign_map[2]], value[sign_map[3]], value[sign_map[4]], value[sign_map[5]], value[sign_map[6]], value[sign_map[7]]] temp[int(math.floor(xr)),int(math.floor(zr))] = new_value self.rotatedSignData.append(temp) #Moving to origin x,z : 0,0 self.newData=list() self.newSignData=list() for i in self.rotatedData: temp=dict() for key,value in i.iteritems(): temp[key[0], int(key[1])+int((self.rows-1))] = value self.newData.append(temp) for i in self.rotatedSignData: temp=dict() for key,value in i.iteritems(): temp[key[0], int(key[1])+int((self.rows-1))] = value self.newSignData.append(temp) temp = self.rows self.rows = self.cols self.cols = temp temp = self.curr_level temp2 = self.overlay_level temp3 = self.overlayToggle temp4 = self.current_item self.updateDimensions(self.rows, self.cols,len(self.newData)) self.reset_canvas() self.levels = self.newData self.signs = self.newSignData self.curr_level = temp self.overlay_level = temp2 self.overlayToggle = temp3 self.itemCombo.set(temp4) self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) self.currLevelCombo.set(self.curr_level) self.overlayLevelCombo.set(self.overlay_level) self.redraw_level() def onNew(self): if self.overlayToggle == 1: self.toggle.invoke() self.overlayToggle = 0 self.w=popupWindow(self,title = "Enter Dimensions in XxZxY format (e.g. 10x20x3)") self.wait_window(self.w.top) try: data = self.w.value.split('x') if len(data) == 2: self.updateDimensions(int(data[0]), int(data[1]),1) else: self.updateDimensions(int(data[0]), int(data[1]),int(data[2])) # self.initData() self.reset_canvas() self.currLevelCombo.config(values = range(len(self.levels))) self.overlayLevelCombo.config(values = range(len(self.levels))) except ValueError: pass def currLevelChooser(self, event): self.curr_level = int(self.currLevelCombo.get()) self.redraw_level() def overlayLevelChooser(self, event): self.overlay_level = int(self.overlayLevelCombo.get()) self.redraw_level() def itemChooser(self, event): self.current_item = int(self.itemCombo.get()) def callbackLeftClick(self,event): if self.current_item == 0: return col = int(math.floor((event.x)/self.cellwidth)) row = int(math.floor((event.y)/self.cellheight)) x1 = col * self.cellwidth y1 = row * self.cellheight x2 = x1 + self.cellwidth y2 = y1 + self.cellheight if (self.rows - row - 1,col) in self.rect: self.canvas.itemconfig(self.rect[self.rows - row - 1,col],fill=COLORS[self.current_item]) self.canvas.itemconfig(self.rect_text[self.rows - row - 1,col], text = str(self.current_item)) else: self.rect[self.rows - row - 1,col] = self.canvas.create_rectangle(x1,y1,x2,y2, fill=COLORS[self.current_item], outline = 'black', width = DEFAULTWIDTH, tag = 'block') self.rect_text[self.rows - row - 1,col] = self.canvas.create_text((x1+x2)/2,(y1+y2)/2, text = self.current_item, font=('verdana', 7), tag = 'blocktext') self.levels[self.curr_level][self.rows - row - 1,col] = self.current_item if row < self.rows and row >=0 and col < self.cols and col >= 0: self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col)) def callbackRightClick(self,event): col = int(math.floor((event.x)/self.cellwidth)) row = int(math.floor((event.y)/self.cellheight)) if (self.rows - row - 1,col) in self.rect: self.canvas.delete(self.rect[self.rows - row - 1,col]) self.canvas.delete(self.rect_text[self.rows - row - 1,col]) self.rect.pop((self.rows - row -1, col)) self.rect_text.pop((self.rows - row -1, col)) self.levels[self.curr_level].pop((self.rows - row - 1,col),None) if row < self.rows and row >=0 and col < self.cols and col >= 0: self.lbl_e.config(text = 'x,y,z: ' + str(self.rows-row-1) + ',' + str(self.curr_level) + ',' + str(col))
def __init__(self, parent, txt=dict(), path_browser=None, path_var=""): """Instanciating the output workbook.""" self.p = parent self.txt = txt Frame.__init__(self) # -- VARIABLES ------------------------------------------------------- self.target_path = StringVar() # formats / type: vectors self.li_vectors_formats = (".shp", ".tab", ".kml", ".gml", ".geojson") # vectors handled self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.li_kml = [] # list for KML path self.li_gml = [] # list for GML path self.li_geoj = [] # list for GeoJSON paths self.li_gxt = [] # list for GXT paths self.li_vectors = [] # list for all vectors # formats / type: rasters self.li_raster = [] # list for rasters paths self.li_raster_formats = (".ecw", ".tif", ".jp2") # raster handled # formats / type: file databases self.li_fdb = [] # list for all files databases self.li_egdb = [] # list for Esri File Geodatabases self.li_spadb = [] # list for Spatialite Geodatabases # formats / type: CAO/DAO self.li_cdao = [] # list for all CAO/DAO files self.li_dxf = [] # list for AutoCAD DXF paths self.li_dwg = [] # list for AutoCAD DWG paths self.li_dgn = [] # list for MicroStation DGN paths # formats / type: maps documents self.li_mapdocs = [] # list for all map & documents self.li_pdf = [] # list for GeoPDF path self.li_lyr = [] # list for LYR path self.li_mxd = [] # list for MXD path self.li_qgs = [] # list for QGS path # -- Source path ----------------------------------------------------- self.FrPath = Labelframe(self, name='files', text=txt.get('gui_fr1', "Path")) # target folder self.lb_target = Label(self.FrPath, text=txt.get('gui_path')) self.ent_target = Entry(master=self.FrPath, width=35, textvariable=self.target_path) self.btn_browse = Button(self.FrPath, text=u"\U0001F3AF " + txt.get('gui_choix', "Browse"), command=lambda: self.get_target_path(r"."), takefocus=True) self.btn_browse.focus_force() # widgets placement self.lb_target.grid(row=1, column=1, columnspan=1, sticky="NSWE", padx=2, pady=2) self.ent_target.grid(row=1, column=2, columnspan=1, sticky="NSWE", padx=2, pady=2) self.btn_browse.grid(row=1, column=3, sticky="NSE", padx=2, pady=2) # -- Format filters -------------------------------------------------- self.FrFilters = Labelframe(self, name='filters', text=txt.get('gui_fr3', "Filters")) # formats options self.opt_shp = IntVar(self.FrFilters) # able/disable shapefiles self.opt_tab = IntVar(self.FrFilters) # able/disable MapInfo tables self.opt_kml = IntVar(self.FrFilters) # able/disable KML self.opt_gml = IntVar(self.FrFilters) # able/disable GML self.opt_geoj = IntVar(self.FrFilters) # able/disable GeoJSON self.opt_gxt = IntVar(self.FrFilters) # able/disable GXT self.opt_egdb = IntVar(self.FrFilters) # able/disable Esri FileGDB self.opt_spadb = IntVar(self.FrFilters) # able/disable Spatalite DB self.opt_rast = IntVar(self.FrFilters) # able/disable rasters self.opt_cdao = IntVar(self.FrFilters) # able/disable CAO/DAO files self.opt_pdf = IntVar(self.FrFilters) # able/disable Geospatial PDF self.opt_lyr = IntVar(self.FrFilters) # able/disable Geospatial Lyr self.opt_mxd = IntVar(self.FrFilters) # able/disable Geospatial MXD self.opt_qgs = IntVar(self.FrFilters) # able/disable Geospatial QGS # format choosen: check buttons caz_shp = Checkbutton(self.FrFilters, text=u'.shp', variable=self.opt_shp) caz_tab = Checkbutton(self.FrFilters, text=u'.tab', variable=self.opt_tab) caz_kml = Checkbutton(self.FrFilters, text=u'.kml', variable=self.opt_kml) caz_gml = Checkbutton(self.FrFilters, text=u'.gml', variable=self.opt_gml) caz_geoj = Checkbutton(self.FrFilters, text=u'.geojson', variable=self.opt_geoj) caz_gxt = Checkbutton(self.FrFilters, text=u'.gxt', variable=self.opt_gxt) caz_egdb = Checkbutton(self.FrFilters, text=u'Esri FileGDB', variable=self.opt_egdb) caz_spadb = Checkbutton(self.FrFilters, text=u'Spatialite', variable=self.opt_spadb) caz_rast = Checkbutton(self.FrFilters, text=u'rasters ({0})'.format(', '.join(self.li_raster_formats)), variable=self.opt_rast) caz_cdao = Checkbutton(self.FrFilters, text=u'CAO/DAO', variable=self.opt_cdao) caz_pdf = Checkbutton(self.FrFilters, text=u'Geospatial PDF', variable=self.opt_pdf) self.caz_lyr = Checkbutton(self.FrFilters, text=u'.lyr', variable=self.opt_lyr) self.caz_mxd = Checkbutton(self.FrFilters, text=u'.mxd', variable=self.opt_mxd) caz_qgs = Checkbutton(self.FrFilters, text=u'.qgs', variable=self.opt_qgs) # widgets placement caz_shp.grid(row=1, column=0, sticky="NSWE", padx=2, pady=2) caz_tab.grid(row=1, column=1, sticky="NSWE", padx=2, pady=2) caz_kml.grid(row=1, column=2, sticky="NSWE", padx=2, pady=2) caz_gml.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) caz_geoj.grid(row=1, column=4, sticky="NSWE", padx=2, pady=2) caz_gxt.grid(row=1, column=7, sticky="NSWE", padx=2, pady=2) caz_pdf.grid(row=1, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_rast.grid(row=2, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_egdb.grid(row=2, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_cdao.grid(row=2, column=4, columnspan=1, sticky="NSWE", padx=2, pady=2) caz_spadb.grid(row=2, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_lyr.grid(row=3, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_mxd.grid(row=3, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_qgs.grid(row=3, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # frames placement self.FrPath.grid(row=3, column=1, padx=2, pady=2, sticky="NSWE") self.FrFilters.grid(row=4, column=1, padx=2, pady=2, sticky="NSWE")
class TabFiles(Frame): def __init__(self, parent, txt=dict(), path_browser=None, path_var=""): """Instanciating the output workbook.""" self.p = parent self.txt = txt Frame.__init__(self) # -- VARIABLES ------------------------------------------------------- self.target_path = StringVar() # formats / type: vectors self.li_vectors_formats = (".shp", ".tab", ".kml", ".gml", ".geojson") # vectors handled self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.li_kml = [] # list for KML path self.li_gml = [] # list for GML path self.li_geoj = [] # list for GeoJSON paths self.li_gxt = [] # list for GXT paths self.li_vectors = [] # list for all vectors # formats / type: rasters self.li_raster = [] # list for rasters paths self.li_raster_formats = (".ecw", ".tif", ".jp2") # raster handled # formats / type: file databases self.li_fdb = [] # list for all files databases self.li_egdb = [] # list for Esri File Geodatabases self.li_spadb = [] # list for Spatialite Geodatabases # formats / type: CAO/DAO self.li_cdao = [] # list for all CAO/DAO files self.li_dxf = [] # list for AutoCAD DXF paths self.li_dwg = [] # list for AutoCAD DWG paths self.li_dgn = [] # list for MicroStation DGN paths # formats / type: maps documents self.li_mapdocs = [] # list for all map & documents self.li_pdf = [] # list for GeoPDF path self.li_lyr = [] # list for LYR path self.li_mxd = [] # list for MXD path self.li_qgs = [] # list for QGS path # -- Source path ----------------------------------------------------- self.FrPath = Labelframe(self, name='files', text=txt.get('gui_fr1', "Path")) # target folder self.lb_target = Label(self.FrPath, text=txt.get('gui_path')) self.ent_target = Entry(master=self.FrPath, width=35, textvariable=self.target_path) self.btn_browse = Button(self.FrPath, text=u"\U0001F3AF " + txt.get('gui_choix', "Browse"), command=lambda: self.get_target_path(r"."), takefocus=True) self.btn_browse.focus_force() # widgets placement self.lb_target.grid(row=1, column=1, columnspan=1, sticky="NSWE", padx=2, pady=2) self.ent_target.grid(row=1, column=2, columnspan=1, sticky="NSWE", padx=2, pady=2) self.btn_browse.grid(row=1, column=3, sticky="NSE", padx=2, pady=2) # -- Format filters -------------------------------------------------- self.FrFilters = Labelframe(self, name='filters', text=txt.get('gui_fr3', "Filters")) # formats options self.opt_shp = IntVar(self.FrFilters) # able/disable shapefiles self.opt_tab = IntVar(self.FrFilters) # able/disable MapInfo tables self.opt_kml = IntVar(self.FrFilters) # able/disable KML self.opt_gml = IntVar(self.FrFilters) # able/disable GML self.opt_geoj = IntVar(self.FrFilters) # able/disable GeoJSON self.opt_gxt = IntVar(self.FrFilters) # able/disable GXT self.opt_egdb = IntVar(self.FrFilters) # able/disable Esri FileGDB self.opt_spadb = IntVar(self.FrFilters) # able/disable Spatalite DB self.opt_rast = IntVar(self.FrFilters) # able/disable rasters self.opt_cdao = IntVar(self.FrFilters) # able/disable CAO/DAO files self.opt_pdf = IntVar(self.FrFilters) # able/disable Geospatial PDF self.opt_lyr = IntVar(self.FrFilters) # able/disable Geospatial Lyr self.opt_mxd = IntVar(self.FrFilters) # able/disable Geospatial MXD self.opt_qgs = IntVar(self.FrFilters) # able/disable Geospatial QGS # format choosen: check buttons caz_shp = Checkbutton(self.FrFilters, text=u'.shp', variable=self.opt_shp) caz_tab = Checkbutton(self.FrFilters, text=u'.tab', variable=self.opt_tab) caz_kml = Checkbutton(self.FrFilters, text=u'.kml', variable=self.opt_kml) caz_gml = Checkbutton(self.FrFilters, text=u'.gml', variable=self.opt_gml) caz_geoj = Checkbutton(self.FrFilters, text=u'.geojson', variable=self.opt_geoj) caz_gxt = Checkbutton(self.FrFilters, text=u'.gxt', variable=self.opt_gxt) caz_egdb = Checkbutton(self.FrFilters, text=u'Esri FileGDB', variable=self.opt_egdb) caz_spadb = Checkbutton(self.FrFilters, text=u'Spatialite', variable=self.opt_spadb) caz_rast = Checkbutton(self.FrFilters, text=u'rasters ({0})'.format(', '.join(self.li_raster_formats)), variable=self.opt_rast) caz_cdao = Checkbutton(self.FrFilters, text=u'CAO/DAO', variable=self.opt_cdao) caz_pdf = Checkbutton(self.FrFilters, text=u'Geospatial PDF', variable=self.opt_pdf) self.caz_lyr = Checkbutton(self.FrFilters, text=u'.lyr', variable=self.opt_lyr) self.caz_mxd = Checkbutton(self.FrFilters, text=u'.mxd', variable=self.opt_mxd) caz_qgs = Checkbutton(self.FrFilters, text=u'.qgs', variable=self.opt_qgs) # widgets placement caz_shp.grid(row=1, column=0, sticky="NSWE", padx=2, pady=2) caz_tab.grid(row=1, column=1, sticky="NSWE", padx=2, pady=2) caz_kml.grid(row=1, column=2, sticky="NSWE", padx=2, pady=2) caz_gml.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) caz_geoj.grid(row=1, column=4, sticky="NSWE", padx=2, pady=2) caz_gxt.grid(row=1, column=7, sticky="NSWE", padx=2, pady=2) caz_pdf.grid(row=1, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_rast.grid(row=2, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_egdb.grid(row=2, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_cdao.grid(row=2, column=4, columnspan=1, sticky="NSWE", padx=2, pady=2) caz_spadb.grid(row=2, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_lyr.grid(row=3, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_mxd.grid(row=3, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_qgs.grid(row=3, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # frames placement self.FrPath.grid(row=3, column=1, padx=2, pady=2, sticky="NSWE") self.FrFilters.grid(row=4, column=1, padx=2, pady=2, sticky="NSWE") def get_target_path(self, def_rep): """Browse and insert the path of target folder.""" print(self.target_path.get()) foldername = askdirectory(parent=self.p, initialdir=def_rep, mustexist=True, title="") # deactivate Go button # self.val.config(state=DISABLED) # check if a folder has been choosen if foldername: try: self.tab_files.ent_target.delete(0, END) self.tab_files.ent_target.insert(0, foldername) except Exception as e: logger.debug(e) showinfo(title=self.txt.get('nofolder'), message=self.txt.get('nofolder')) return else: pass # set the default output file self.output.delete(0, END) self.output.insert(0, "DicoGIS_{0}_{1}.xlsx" .format(path.split(self.target_path.get()), today)) # count geofiles in a separated thread proc = threading.Thread(target=self.ligeofiles, args=(foldername, )) proc.daemon = True proc.start() # end of function return foldername
def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0,columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva , value=1, command=self.cambiaFormula, width=17).grid(row=1,columnspan=2,sticky=W,padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva , value=2, command=self.cambiaFormula).grid(row=2,columnspan=2,sticky=W,padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame,textvariable=self.aaa).grid(row=5, column=0,pady=2) Label(editarFrame,textvariable=self.bbb).grid(row=6, column=0,pady=2) self.labelC = Label(editarFrame,textvariable=self.ccc) self.labelC.grid(row=7, column=0,pady=2) self.labelC.config(state=DISABLED) Label(editarFrame,textvariable=self.Lma).grid(row=8, column=0,pady=2) Label(editarFrame,textvariable=self.fre).grid(row=9, column=0,pady=2) parA = Entry(editarFrame,width=4,textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame,width=4,textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame,width=4,textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame,width=4,textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame,width=4,textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage(data='''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''') saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3,textvariable=self.lenlen).grid(row=1, column=0,pady=4,padx=12) Label(frame3,textvariable=self.radrad).grid(row=2, column=0,pady=4,padx=12) Label(frame3,textvariable=self.StringLongitud).grid(row=1, column=1,pady=4) Label(frame3,textvariable=self.StringRadio).grid(row=2, column=1,pady=4)
class Principal(Frame): # Class for helping Tooltips class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text, lang): self.text = text if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() +27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass label = Label(tw, text=self.text[lang], justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() # Initialization function def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # Spiral parameters (defined as StringVars for convenience) self.a = StringVar() self.a.set('0') self.b = StringVar() self.b.set('0.5') self.c = StringVar() self.c.set('1') self.lMax = StringVar() self.lMax.set(158) self.frec = StringVar() self.frec.set(500) self.StringLongitud = StringVar() self.StringRadio = StringVar() # Help mode flag self.ayuda = False # Figure object self.f = Figure(figsize=(5,5)) self.initUI() # Tooltip creator function (allowed by help mode flag) def createToolTip(self, widget, text): toolTip = self.ToolTip(widget) def enter(event): if self.ayuda: toolTip.showtip(text, self.lang) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) # Euclidean distance calculator function def distancia( self, r1, phi1, r2, phi2 ): return sqrt(r1**2 + r2**2 - 2*r1*r2*cos(phi1-phi2)) # Polar to Cartesian coordinates def pol2cart(self, rho, phi): x = rho*cos(phi) y = rho*sin(phi) return(x, y) # def grafico(self): # Set figure size self.f = Figure(figsize=(5,5)) # Check whether negative parameters are present and show an error if float(self.c.get()) < 0 or float(self.b.get()) < 0: print self.lang tkMessageBox.showerror("Error", self.error.get()) return # Set figure axis ax = self.f.add_subplot(111, polar=True) # Initialize r and theta lists at the center point self.theta_disc = [0] self.r_disc = [0] self.theta_disc_n = [0] # Initialize length value and list l = 0 l_vec = [] # Loop limited by antenna length while l < int(self.lMax.get()): # Length of each antenna segment in cm, computed as 1/15 of the wave length lseg = 300/float(self.frec.get())*100/15 if self.tipoCurva.get() == 1: # Archimedean spiral # New theta values are calculated according to the following: # In an Archimedean spiral # /r - a\ c # theta = |-------| # \ b / # In order to get an approximately equally spaced segments, new theta values are computed according to the next formula. This formula has been worked # out gradually, not basing on any well-known expression. # /0.5 * lseg - a\ c # |----------------| - lseg # \ b / # ------------------------------ + lseg # 10 * theta + 1 # n # theta = theta + --------------------------------------- # n + 1 n r + 1 # n self.theta_disc.append(self.theta_disc[-1] + \ (( ((0.5*lseg - float(self.a.get()))/float(self.b.get()))**(float(self.c.get())) - lseg) / (10*self.theta_disc[-1] + 1) + lseg) \ / (self.r_disc[-1] + 1)) # print str(lseg) # print str(self.r_disc[-1]) else: # print "Eh: " + str(self.theta_disc[-1]) # print "Ra: " + str(self.r_disc[-1]) # print "Ls: " + str(lseg) # print "Ot: " + str(log(0.5*lseg/float(self.a.get()))/float(self.b.get())) self.theta_disc.append(self.theta_disc[-1] + \ (( max(log(0.5*lseg/float(self.a.get()))/float(self.b.get()),float(self.a.get())) - lseg) * exp(-1*self.theta_disc[-1]) + lseg) \ / (self.r_disc[-1] + 1)) #print str(lseg) #print str(self.r_disc[-1]) if self.tipoCurva.get() == 1: self.r_disc.append(float(self.b.get())*self.theta_disc[-1]**(1/float(self.c.get())) + float(self.a.get())) elif self.tipoCurva.get() == 2: self.r_disc.append(float(self.a.get())*exp(float(self.b.get())*self.theta_disc[-1])) self.theta_disc_n.append(pi + self.theta_disc[-1]) l_vec.append(self.distancia(self.r_disc[-1],self.theta_disc[-1],self.r_disc[-2],self.theta_disc[-2])) l += l_vec[-1] if self.fuente.get() and str(self.checkFuente.cget('state')) == 'normal': self.theta_disc.remove(0) self.r_disc.remove(0) self.theta_disc_n.remove(0) ax.plot([self.theta_disc[0],self.theta_disc_n[0]], [self.r_disc[0], self.r_disc[0]], color='r') ax.plot([0],[0], color='m', marker='o', markersize=5) self.StringLongitud.set("%#.1f cm" % l) self.StringRadio.set("%#.1f cm" % max(self.r_disc)) ax.plot(self.theta_disc, self.r_disc, color='b', marker='.', markersize=4) if self.espejar.get(): ax.plot(self.theta_disc_n, self.r_disc, color='g', marker='.', markersize=4) ax.set_rmax(max(self.r_disc)) ax.grid(True) #with open('distancias.csv', 'wb') as f: # writer = csv.writer(f) # writer.writerows(izip(self.theta_disc, l_vec)) def regraficar(self): self.grafico() self.canvas.get_tk_widget().pack_forget() self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) #canvas.show() self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH, expand=1, padx=10, pady=10) def cambiaFormula(self): curvas = ['''R0lGODlhbAAWAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABsABYAAAT+8MlJq7046817ToYnjmRpXsqpriw3JGgrz2pDHHDFFHTvezjL4kcsWoKUBIHCQDQQxmhy4EhZDATGkoKcEHIPwjIBkJoljsZVEFIwuGDJUJJwhM7ngN0i4D0YcxJdDwVqEg0CeC0DHQhlOokSCJGCcVYSAYyHiiaaGwOXEwCGDwqRBQgOC28PBqEPCAgMDDANgH8MCnEzAQSxCFufHQ6xuSF6FACeFgwBG1AHCwYGaSgC19jZAssViHQOrMIbelsIQwoHCuoLDsFCGwUgDn67LXVgDvUX3BeOEw0OHgCAcmgeBgME4QUssoBSgQMe+Am5lOqBQQkKHq0gIHEGMS9yHU1lO6CN34FwDamBOZBQhYCWGERqyyaxjp8HLyNuoOYMDYI6//awcNDzh0oJ1HiEy9CRwsIHDSBanCBg6YkCT4kA8EPAToGiTDkIgGEAQM8XsAKtuGUkgRsoYqxiaDrBbS4wbmNx2iuBLt+/HNQCfhABADs=''', '''R0lGODlhQwASAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABDABIAAATn8MlJq70463ZSJQyhjWSpGUe1BM/imXCcNQvVDNLQyHz/KAOGgiXYPQAsn7IEKDwKg4SDgCA4DMtsBiVpCAqALk5LrhRqPwIt5yy7H4GaAWBIKJ7391uBULyoIhMNDDUMQi9uAVQIVRQJCAyMMAgPBwsGBg5GFAoCnp+gAmMXXhJSDBOEE3kkBQmZbYhkUogOLwEHWHCBJgUOehMLAhMFKTlBkG0wBKN6DpQSzBMOqD4C0BmdoaHNE1LK1xKwSg5Jepkv46gOyk+yGr7AE03RVwUsCrwF1SWq8g92Ij0gAGIClUjmSEQAADs=''', ''''''] formula = PhotoImage(data=curvas[self.tipoCurva.get()-1]) self.formulaLabel.configure(image=formula) self.formulaLabel.image = formula if self.tipoCurva.get() == 1: self.parC.config(state=NORMAL) self.labelC.config(state=NORMAL) else: self.parC.config(state=DISABLED) self.labelC.config(state=DISABLED) def activarFuente(self): if self.espejar.get(): self.checkFuente.config(state=NORMAL) else: self.checkFuente.config(state=DISABLED) def escribirFichero(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.nec' options['filetypes'] = [('NEC2 files', '.nec'),('all files', '.*')] options['initialdir'] = '~/Documentos/Antenas/Espirales' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save NEC' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) r_final = list(reversed(self.r_disc)) + self.r_disc theta_final = list(reversed(self.theta_disc_n)) + self.theta_disc x_ant, y_ant = self.pol2cart(r_final[0], theta_final[0]) tipoCurvaExt = ['Archimedean', 'Logarithmic'] fich.write('CM Created with PySAD\n') fich.write('CM L = %#.1f\n' % float(self.lMax.get())) fich.write('CM ' + tipoCurvaExt[int(self.tipoCurva.get())-1] + ' spiral') fich.write('CM a = ' + self.a.get()) fich.write('CM b = ' + self.b.get()) if int(self.tipoCurva.get()) == 0 : fich.write('CM c = ' + self.c.get()) fich.write('CE\n') print len(r_final) for i in range(len(r_final)-1): x, y = self.pol2cart(r_final[i+1], theta_final[i+1]) linea = 'GW\t%#d\t%#d\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\n' % (i+1,1,x_ant/100,y_ant/100,0,x/100,y/100,0,0.001) fich.write(linea) x_ant, y_ant = x, y fich.write('GE\t0\nGN\t-1\nEK\n') fich.write('EX\t%#d\t%#d\t%#d\t%#d\t%#d\t%#d\n' % (0,len(r_final)/2,1,0,1,0)) fich.write('FR\t0\t0\t0\t0\t299.8\t0\nEN') fich.close() def escribirPDF(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.pdf' options['filetypes'] = [('PDF files', '.pdf'),('all files', '.*')] options['initialdir'] = '~' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save PDF' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) #self.f.axis('off') matplotlib.rcParams.update({'font.size': 1}) self.f.gca().axes.get_xaxis().set_visible(False) self.f.gca().axes.get_yaxis().set_visible(False) papeles_w = [21, 29.7, 42, 59.4, 84.1] papeles_h = [29.7, 42, 59.4, 84.1, 118.9] for i_pap in range(0, len(papeles_w)-1): if 2*max(self.r_disc) < papeles_w[i_pap]: break print i_pap self.f.set_size_inches(papeles_w[i_pap]/2.54, papeles_h[i_pap]/2.54) noMargen = dict(pad=72*(papeles_w[i_pap] - 2*max(self.r_disc))/2/2.54, h_pad=0, w_pad=0) self.f.set_tight_layout(noMargen) self.f.suptitle('test title') self.f.savefig(fich, format='pdf', dpi='90') fich.close() def mostrarAyuda(self): self.ayuda = not self.ayuda if self.ayuda: self.helpButton.state(["pressed"]) self.config(cursor="question_arrow") else: self.helpButton.state(["!pressed"]) self.config(cursor="") def initText(self): self.curTip = StringVar() self.ArcSpi = StringVar() self.LogSpi = StringVar() self.aaa = StringVar() self.bbb = StringVar() self.ccc = StringVar() self.Lma = StringVar() self.fre = StringVar() self.Mir = StringVar() self.Sou = StringVar() self.Gen = StringVar() self.lenlen = StringVar() self.radrad = StringVar() self.error = StringVar() def updateText(self, lang): self.lang = lang if lang == 0: self.espButton.state(["pressed"]) self.engButton.state(["!pressed"]) else: self.engButton.state(["pressed"]) self.espButton.state(["!pressed"]) self.stringText = {'curTip': ["Tipo de curva", "Curve type"],'ArcSpi': ["Espiral de Arquímedes", "Archimedean spiral "],'LogSpi': ["Espiral logarítmica", "Logarithmic spiral"],'aaa': ["a (cm)", "a (cm)"],'bbb': ["b (cm/rad)", "b (cm/rad)"],'ccc': ["c", "c"],'Lma': ["Lmax (cm)", "Lmax (cm)"],'fre': ["frec (MHz)", "freq (MHz)"],'LmaToo': ["Longitud máxima de cada brazo de la antena", "Maximum length of each antenna's branch"],'FreToo': ["Frecuencia de diseño (aumentar para disminuir la longitud de los segmentos)", "Design frequency (increase for decreasing segment length)"],'Mir': ["Espejar", "Mirror"],'MirToo': ["Crea otra rama de la espiral girada 180º", "Create another spiral branch, twisted 180º"],'Sou': ["Colocar fuente", "Put source"],'SouToo': ["Une las dos mitades y crea una fuente NEC2 en el centro", "Join both halves and create a NEC2 source at the middle"],'Gen': ["Generar", "Generate"],'GenToo': ["Genera la espiral con los parámetros indicados", "Generate spiral following given parameters"],'NEC': ["NEC", "NEC"],'NECToo': ["Guarda la espiral como archivo NEC2", "Save the spiral as a NEC2 file"],'PDF': ["PDF", "PDF"],'PDFToo': ["Imprime la espiral a tamaño real en un documento PDF (máximo A0)", "Print the real sized spiral into a PDF document (A0 maximum)"],'HHH': ["H", "H"], 'lenlen': ["Longitud:", "Length:"], 'radrad': ["Radio:", "Radius:"], 'error': ["No se permiten valores negativos de b o c", "Negative values of b or c are not allowed"]} self.curTip.set(self.stringText['curTip'][self.lang]) self.ArcSpi.set(self.stringText['ArcSpi'][self.lang]) self.LogSpi.set(self.stringText['LogSpi'][self.lang]) self.aaa.set(self.stringText['aaa'][self.lang]) self.bbb.set(self.stringText['bbb'][self.lang]) self.ccc.set(self.stringText['ccc'][self.lang]) self.Lma.set(self.stringText['Lma'][self.lang]) self.fre.set(self.stringText['fre'][self.lang]) self.Mir.set(self.stringText['Mir'][self.lang]) self.Sou.set(self.stringText['Sou'][self.lang]) self.Gen.set(self.stringText['Gen'][self.lang]) self.lenlen.set(self.stringText['lenlen'][self.lang]) self.radrad.set(self.stringText['radrad'][self.lang]) self.error.set(self.stringText['error'][self.lang]) def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0,columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva , value=1, command=self.cambiaFormula, width=17).grid(row=1,columnspan=2,sticky=W,padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva , value=2, command=self.cambiaFormula).grid(row=2,columnspan=2,sticky=W,padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame,textvariable=self.aaa).grid(row=5, column=0,pady=2) Label(editarFrame,textvariable=self.bbb).grid(row=6, column=0,pady=2) self.labelC = Label(editarFrame,textvariable=self.ccc) self.labelC.grid(row=7, column=0,pady=2) self.labelC.config(state=DISABLED) Label(editarFrame,textvariable=self.Lma).grid(row=8, column=0,pady=2) Label(editarFrame,textvariable=self.fre).grid(row=9, column=0,pady=2) parA = Entry(editarFrame,width=4,textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame,width=4,textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame,width=4,textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame,width=4,textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame,width=4,textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage(data='''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''') saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3,textvariable=self.lenlen).grid(row=1, column=0,pady=4,padx=12) Label(frame3,textvariable=self.radrad).grid(row=2, column=0,pady=4,padx=12) Label(frame3,textvariable=self.StringLongitud).grid(row=1, column=1,pady=4) Label(frame3,textvariable=self.StringRadio).grid(row=2, column=1,pady=4) def onExit(self): self.quit()
btn2 = Button(window, text="show text", bg="blue", fg="red", command=show_text) btn2.grid(column=1, row=2) ''' combox ''' combo = Combobox(window) combo['values'] = (1, 2, 3, 4, 5, "Text") combo.current(1) #set the selected item combo.grid(column=0, row=3) val = combo.get() # print(val) chk_state = BooleanVar() chk_state.set(False) #set check state chk = Checkbutton(window, text='Choose', var=chk_state) chk.grid(column=1, row=3) ''' radiobutton ( [1] [2] [3] button )''' selected = IntVar() rad1 = Radiobutton(window, text='First', value=1, variable=selected) rad2 = Radiobutton(window, text='Second', value=2, variable=selected) rad3 = Radiobutton(window, text='Third', value=3, variable=selected) def clicked(): print(selected.get()) btn = Button(window, text="Click Me", command=clicked) rad1.grid(column=0, row=4) rad2.grid(column=1, row=4)
def __init__(self): u""" Main window constructor Creates 1 frame and 2 labelled subframes """ # basics settings Tk.__init__(self) # constructor of parent graphic class self.title(u'DicoGIS {0}'.format(DGversion)) self.li_raster_formats = ['ecw', 'geotiff'] # notebook self.nb = Notebook(self) self.FrProg = Labelframe(self, name='progression', text='gui_prog') self.FrOutp = Labelframe(self, name='output', text='gui_fr4') # tabs self.tab_files = Frame(self.nb) # tab_id = 0 self.tab_sgbd = Frame(self.nb) # tab_id = 1 self.tab_webservices = Frame(self.nb) # tab_id = 2 self.tab_isogeo = Frame(self.nb) # tab_id = 3 self.tab_about = Frame(self.nb) # tab_id = 4 ## TAB 1: FILES self.nb.add(self.tab_files, text='gui_files', padding=3) # frame: path folder self.FrPath = Labelframe(self.tab_files, name='files', text='gui_fr1') self.labtarg = Label(self.FrPath, text='gui_path') self.target = Entry(master=self.FrPath, width=35) self.browsetarg = Button(self.FrPath, # browse button text='gui_choix', command=lambda: self.setpathtarg(), takefocus=True) self.browsetarg.focus_force() # force the focus on # widgets placement self.labtarg.grid(row=1, column=1, columnspan=1, sticky="NSWE", padx=2, pady=2) self.target.grid(row=1, column=2, columnspan=1, sticky="NSWE", padx=2, pady=2) self.browsetarg.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) # frame: filters self.FrFilters = Labelframe(self.tab_files, name='filters', text='filters') # formats options self.opt_shp = IntVar(self.FrFilters) # able/disable shapefiles self.opt_tab = IntVar(self.FrFilters) # able/disable MapInfo tables self.opt_kml = IntVar(self.FrFilters) # able/disable KML self.opt_gml = IntVar(self.FrFilters) # able/disable GML self.opt_geoj = IntVar(self.FrFilters) # able/disable GeoJSON self.opt_gxt = IntVar(self.FrFilters) # able/disable GXT self.opt_egdb = IntVar(self.FrFilters) # able/disable Esri FileGDB self.opt_spadb = IntVar(self.FrFilters) # able/disable Spatalite DB self.opt_rast = IntVar(self.FrFilters) # able/disable rasters self.opt_cdao = IntVar(self.FrFilters) # able/disable CAO/DAO files self.opt_pdf = IntVar(self.FrFilters) # able/disable Geospatial PDF self.opt_lyr = IntVar(self.FrFilters) # able/disable Geospatial Lyr self.opt_mxd = IntVar(self.FrFilters) # able/disable Geospatial MXD self.opt_qgs = IntVar(self.FrFilters) # able/disable Geospatial QGS # format choosen: check buttons caz_shp = Checkbutton(self.FrFilters, text=u'.shp', variable=self.opt_shp) caz_tab = Checkbutton(self.FrFilters, text=u'.tab', variable=self.opt_tab) caz_kml = Checkbutton(self.FrFilters, text=u'.kml', variable=self.opt_kml) caz_gml = Checkbutton(self.FrFilters, text=u'.gml', variable=self.opt_gml) caz_geoj = Checkbutton(self.FrFilters, text=u'.geojson', variable=self.opt_geoj) caz_gxt = Checkbutton(self.FrFilters, text=u'.gxt', variable=self.opt_gxt) caz_egdb = Checkbutton(self.FrFilters, text=u'Esri FileGDB', variable=self.opt_egdb) caz_spadb = Checkbutton(self.FrFilters, text=u'Spatialite', variable=self.opt_spadb) caz_rast = Checkbutton(self.FrFilters, text=u'rasters ({0})'.format(', '.join(self.li_raster_formats)), variable=self.opt_rast) caz_cdao = Checkbutton(self.FrFilters, text=u'CAO/DAO', variable=self.opt_cdao) caz_pdf = Checkbutton(self.FrFilters, text=u'Geospatial PDF', variable=self.opt_pdf) caz_lyr = Checkbutton(self.FrFilters, text=u'.lyr', variable=self.opt_lyr) caz_mxd = Checkbutton(self.FrFilters, text=u'.mxd', variable=self.opt_mxd) caz_qgs = Checkbutton(self.FrFilters, text=u'.qgs', variable=self.opt_qgs) # widgets placement caz_shp.grid(row=1, column=0, sticky="NSWE", padx=2, pady=2) caz_tab.grid(row=1, column=1, sticky="NSWE", padx=2, pady=2) caz_kml.grid(row=1, column=2, sticky="NSWE", padx=2, pady=2) caz_gml.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) caz_geoj.grid(row=1, column=4, sticky="NSWE", padx=2, pady=2) caz_gxt.grid(row=1, column=7, sticky="NSWE", padx=2, pady=2) caz_pdf.grid(row=1, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_rast.grid(row=2, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_egdb.grid(row=2, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_cdao.grid(row=2, column=4, columnspan=1, sticky="NSWE", padx=2, pady=2) caz_spadb.grid(row=2, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_lyr.grid(row=3, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_mxd.grid(row=3, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_qgs.grid(row=3, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # frames placement self.FrPath.grid(row=3, column=1, padx=2, pady=2, sticky="NSWE") self.FrFilters.grid(row=4, column=1, padx=2, pady=2, sticky="NSWE") # tab 2: database self.nb.add(self.tab_sgbd, text='gui_database', padding=3) # tab 3: webservices self.nb.add(self.tab_webservices, text='gui_webservices', padding=3) ## TAB 4: ISOGEO self.nb.add(self.tab_isogeo, text='gui_Isogeo', padding=3) ## TAB 5: ABOUT self.nb.add(self.tab_about, text='gui_about', padding=3) ## MAIN FRAME # Welcome message self.welcome = Label(self, text='hola test', foreground="red2") # Progression bar self.status = StringVar(self.FrProg, '') # widgets self.prog_layers = Progressbar(self.FrProg, orient="horizontal") Label(master=self.FrProg, textvariable=self.status, foreground='DodgerBlue').pack() # widgets placement self.prog_layers.pack(expand=1, fill='both') # Output configuration # widgets self.nameoutput = Label(self.FrOutp, text='gui_fic') self.output = Entry(self.FrOutp, width=35) # widgets placement self.nameoutput.grid(row=0, column=1, sticky="NSWE", padx=2, pady=2) self.output.grid(row=0, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # Image self.icone = PhotoImage(file=r'../data/img/DicoGIS_logo.gif') Label(self, borderwidth=2, image=self.icone).grid(row=1, rowspan=4, column=0, padx=2, pady=2, sticky=W) # credits s = Style(self) s.configure('Kim.TButton', foreground='DodgerBlue', borderwidth=0) Button(self, text='by @GeoJulien\nGPL3 - 2015', style='Kim.TButton', command=lambda: open_new('https://github.com/Guts/DicoGIS')).grid(row=4, padx=2, pady=2, sticky="WE") # language switcher self.ddl_lang = Combobox(self, values=['fr', 'en'], width=5) # grid placement self.val = Button(self, text='gui_go', state=ACTIVE, command=lambda: self.process()) self.can = Button(self, text='gui_quit', command=lambda: self.destroy()) self.welcome.grid(row=1, column=1, columnspan=1, sticky="NS", padx=2, pady=2) self.ddl_lang.grid(row=1, column=1, sticky="NSE", padx=2, pady=2) self.nb.grid(row=2, column=1) self.FrProg.grid(row=3, column=1, sticky="NSWE", padx=2, pady=2) self.FrOutp.grid(row=4, column=1, sticky="NSWE", padx=2, pady=2) self.val.grid(row=5, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) self.can.grid(row=5, column=0, sticky="NSWE", padx=2, pady=2)
def initUI_main(self): self.parent.title("Personal Helper") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.columnconfigure(7, weight=1) self.columnconfigure(5, pad=10) self.columnconfigure(3, pad=10) self.columnconfigure(1, weight=3) self.rowconfigure(0, weight=0) self.rowconfigure(5, weight=1) self.rowconfigure(5, pad=7) self.rowconfigure(6, pad=6) lbl = Label(self, text="Windows") lbl.grid(sticky=W + N, pady=4, padx=5) check_box = {"work": IntVar(), "boost": IntVar()} check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"]) check1.grid(row=7, column=0) check2 = Checkbutton(self, text="boost games", variable=check_box["boost"]) check2.grid(row=7, column=1) ### old version, may be used again later area = Treeview(self) area['show'] = 'headings' area["columns"] = ("one", "two", "three", "four") area.column("one", width=10) area.column("two", width=10) area.column("three", width=10) area.column("four", width=10) area.heading("one", text="process name") area.heading("two", text="Priority") area.heading("three", text="PID") area.heading("four", text="Usage") ###about this part #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) ####### #comboboxes and relevant buttons self.block_drop = Combobox(self, postcommand=self.update_blocked) self.block_drop['values'] = working_bans self.block_drop.current(0) self.block_drop.grid(row=1, column=1, pady=1) self.entry = Entry(self) self.entry.insert(0, "enter to block") self.entry.grid(row=1, column=4) block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list( working_bans, self.block_drop.get())) block_btn_remv.grid(row=1, column=2) block_btn_add = Button( self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self. entry, defults["block"])) block_btn_add.grid(row=1, column=3) ############ #boosted combo self.boost_drop = Combobox(self, postcommand=self.update_boosted) self.boost_drop['values'] = boosted self.boost_drop.current(0) self.boost_drop.grid(row=2, column=1, pady=1) self.entry2 = Entry(self) self.entry2.insert(0, "enter to buff priority") self.entry2.grid(row=2, column=4, pady=4) boost_btn_remv = Button( self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get())) boost_btn_remv.grid(row=2, column=2) boost_btn_add = Button( self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self. entry2, defults["boost"])) boost_btn_add.grid(row=2, column=3) ######################################### #degraded combo self.deg_drop = Combobox(self, postcommand=self.update_degraded) self.deg_drop['values'] = degraded self.deg_drop.current(0) self.deg_drop.grid(row=3, column=1, pady=1) self.entry3 = Entry(self) self.entry3.insert(0, "enter to lower priority") self.entry3.grid(row=3, column=4, pady=4) deg_btn_remv = Button( self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get())) deg_btn_remv.grid(row=3, column=2) deg_btn_add = Button( self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self. entry3, defults["degrade"])) deg_btn_add.grid(row=3, column=3) #### #music combo self.music_drop = Combobox(self, postcommand=self.update_music) self.music_drop['values'] = music_list.keys() self.music_drop.current(0) self.music_drop.grid(row=4, column=1, pady=1) self.entry4 = Entry(self) self.entry4.insert(0, "enter url") self.entry4.grid(row=4, column=5) self.entry5 = Entry(self) self.entry5.insert(0, "enter song's name") self.entry5.grid(row=4, column=4) music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list( music_list, self.music_drop.get())) music_btn_remv.grid(row=4, column=2) music_btn_add = Button( self, text="Add", command=lambda: add_music(music_list, self.entry5.get( ), self.entry4.get(), self.entry5, defults["music"])) music_btn_add.grid(row=4, column=3) abtn = Button(self, text="Activate", command=scan_computer_programs) abtn.grid(row=1, column=5, sticky=E) sbtn = Button(self, text="Stop", command=lambda: stop_running()) sbtn.grid(row=2, column=5, pady=6, sticky=E) cbtn = Button(self, text="Close", command=quit) cbtn.grid(row=3, column=5, pady=4, sticky=E) hbtn = Button(self, text="Save", command=save_lists) hbtn.grid(row=6, column=0, sticky=W) tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py")) tsbtn.grid(row=3, column=5, sticky=E) obtn = Button( self, text="start", command=lambda: call_running(area, threads["procs"], check_box)) obtn.grid(row=6, column=5, sticky=E)
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.press = None self.grid(sticky=tk.N+tk.E+tk.S+tk.W) self.load_frame() self.load_mip() self.plot_mip() # Create rotate checkbutton global var1 var1 = tk.BooleanVar() rotateButton = Checkbutton(self, text = "Rotate", variable = var1, command=self.checkbutton_value1) rotateButton.grid(row=1, column=0, sticky=tk.E) # Create click checkbutton global var2 var2 = tk.BooleanVar() clickButton = Checkbutton(self, text = "Click", variable = var2, command=self.checkbutton_value2) clickButton.grid(row=1, column=1) # Create quit button quitButton = Button(self, text="Quit", command=self.quit) quitButton.grid(row=0, column=0, sticky=tk.N+tk.W) # Create interpolate button interpolButton = Button(self, text="Interpolate!", command=self.interpolate) interpolButton.grid(row=3, column=0, sticky=tk.S+tk.W) # resetButton = Button(self, text="Reset", command=self.resett) # resetButton.grid(row=4,column=0) # Add CNT logo logo_path = '%s/logo.png'%(DATA_DIR) logo = Image.open(logo_path) logo = ImageTk.PhotoImage(logo) label1 = Label(self, image=logo) label1.grid(row=0, rowspan=4, column=4) label1.image = logo # Create labels and display boxes for selected points label_a = Label(self, text= "A:") label_a.grid(row=0, column=1, sticky=tk.E+tk.S) global coord_a coord_a = Entry(self) coord_a.grid(row=0, column=2, sticky=tk.W+tk.S) label_b = Label(self, text= "B:") label_b.grid(row=1, column=1, sticky=tk.E+tk.N) global coord_b coord_b = Entry(self) coord_b.grid(row=1, column=2, sticky=tk.W+tk.N) label_c = Label(self, text= "C:") label_c.grid(row=2, column=1, sticky=tk.E+tk.N) global coord_c coord_c = Entry(self) coord_c.grid(row=2, column=2, sticky=tk.W+tk.N) label_d = Label(self, text= "D:") label_d.grid(row=3, column=1, sticky=tk.E+tk.N) global coord_d coord_d = Entry(self) coord_d.grid(row=3, column=2, sticky=tk.W+tk.N) # Initialized count variable that will be used to regulate number of corners global count count = 0
def initUI(self): self.master.title("Graph Drawer") self.pack(fill=BOTH, expand=True) self.centerWindow() menubar = Menu(self.master) self.master.config(menu=menubar) self.columnconfigure(1, weight=1) self.rowconfigure(8, weight=1) self.rowconfigure(9, pad=7) nbtn = Button(self, text="Node Mode", command=self.drawNode) nbtn.grid(row=1, column=3, pady=4) ebtn = Button(self, text="Edge Mode", command=self.drawEdge) ebtn.grid(row=2, column=3, pady=4) rbtn = Button(self, text="Obst Mode", command=self.drawRect) rbtn.grid(row=3, column=3, pady=4) cbtn = Button(self, text="Clear", command=self.clear) cbtn.grid(row=4, column=3, pady=4) self.node_list = Listbox(self, selectmode=EXTENDED) self.node_list.grid(row=5, column=3, padx=5, pady=5) n_scrollbar = Scrollbar(self, orient=VERTICAL) n_scrollbar.grid(row=5, column=4, padx=5, sticky='nsw') self.node_list.config(yscrollcommand=n_scrollbar.set) n_scrollbar.config(command=self.node_list.yview) self.node_list.bind('<FocusOut>', lambda e: self.node_list.selection_clear(0, END)) self.node_list.bind('<Double-Button>', self.highlightNode) self.edge_list = Listbox(self, selectmode=EXTENDED) self.edge_list.grid(row=6, column=3, padx=5, pady=5) e_scrollbar = Scrollbar(self, orient=VERTICAL) e_scrollbar.grid(row=6, column=4, padx=5, sticky='nsw') self.edge_list.config(yscrollcommand=e_scrollbar.set) e_scrollbar.config(command=self.edge_list.yview) self.edge_list.bind('<FocusOut>', lambda e: self.edge_list.selection_clear(0, END)) self.edge_list.bind('<Double-Button>', self.highlightEdge) self.obst_list = Listbox(self, selectmode=EXTENDED) self.obst_list.grid(row=7, column=3, padx=5, pady=5) o_scrollbar = Scrollbar(self, orient=VERTICAL) o_scrollbar.grid(row=7, column=4, padx=5, sticky='nsw') self.obst_list.config(yscrollcommand=o_scrollbar.set) o_scrollbar.config(command=self.obst_list.yview) self.obst_list.bind('<FocusOut>', lambda e: self.obst_list.selection_clear(0, END)) self.obst_list.bind('<Double-Button>', self.highlightObst) self.status = StringVar() lbl = Label(self, textvariable=self.status) lbl.grid(row=9, column=0, sticky=W, pady=4, padx=5) fig = Figure(figsize=(9, 9), dpi=100) self.axes = fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(fig, self) self.canvas.get_tk_widget().grid(row=1, column=0, columnspan=2, rowspan=8, padx=5, sticky=E + W + S + N) self.canvas.get_tk_widget().update() canvas_width = self.canvas.get_tk_widget().winfo_width() setFigure(self.axes, canvas_width) self.canvas.mpl_connect('button_press_event', self.on_click) self.canvas.mpl_connect('pick_event', self.on_pick) self.canvas.mpl_connect('button_press_event', self.on_press) self.canvas.mpl_connect('button_release_event', self.on_release) self.canvas.mpl_connect('motion_notify_event', self.on_motion) self.canvas.show() self.snap = BooleanVar() self.snap.set(Mode.snap_to_grid) cb = Checkbutton(self, text="Snap to grid", variable=self.snap, command=self.on_snap) cb.grid(row=0, column=3) txt = Label(self, text="(units) 1 = (meters) ") txt.grid(row=0, column=1, sticky=E, padx=(2, 70)) self.k = StringVar() self.k.set("1.00") spb = Spinbox(self, from_=0.1, to=100, increment=.1, format='%5.2f', width=6, textvariable=self.k) spb.grid(row=0, column=1, sticky=E, padx=(2, 20)) self.frame = Frame(self) self.frame.grid(row=0, column=0, sticky=W, pady=4, padx=5) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame) self.toolbar.update() self.toolbar.pack() self.mode = Mode(self.toolbar, self.status) self.mode.start() self.file = GraphFile() self.file.setUpGraphics(self.axes, self.canvas) self.file.scale_factor_var = self.k fileMenu = Menu(menubar) fileMenu.add_command(label="Open", command=self.openFile) fileMenu.add_command(label="Save", command=self.file.save) fileMenu.add_command(label="Save As", command=self.file.saveAs) menubar.add_cascade(label="File", menu=fileMenu) self.axes.plot(0, 0, color='red', marker='+', markersize=8, zorder=1)
def initUI_main(self): self.parent.title("Personal Helper") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.columnconfigure(7, weight=1) self.columnconfigure(5, pad=10) self.columnconfigure(3, pad=10) self.columnconfigure(1, weight=3) self.rowconfigure(0, weight=0) self.rowconfigure(5, weight=1) self.rowconfigure(5, pad=7) self.rowconfigure(6, pad=6) lbl = Label(self, text="Windows") lbl.grid(sticky=W+N, pady=4, padx=5) check_box = {"work": IntVar(), "boost": IntVar()} check1 = Checkbutton(self, text="work-Mode", variable=check_box["work"]) check1.grid(row=7, column=0) check2 = Checkbutton(self, text="boost games", variable=check_box["boost"]) check2.grid(row=7, column=1) ### old version, may be used again later area = Treeview(self) area['show'] = 'headings' area["columns"] = ("one", "two", "three", "four") area.column("one", width=10) area.column("two", width=10) area.column("three", width=10) area.column("four", width=10) area.heading("one", text="process name") area.heading("two", text="Priority") area.heading("three", text="PID") area.heading("four", text="Usage") ###about this part #area.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) ####### #comboboxes and relevant buttons self.block_drop = Combobox(self, postcommand= self.update_blocked) self.block_drop['values'] = working_bans self.block_drop.current(0) self.block_drop.grid(row=1, column=1, pady=1) self.entry = Entry(self) self.entry.insert(0, "enter to block") self.entry.grid(row=1, column=4) block_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(working_bans, self.block_drop.get())) block_btn_remv.grid(row=1, column=2) block_btn_add = Button(self, text="Add", command=lambda: add_to_list(working_bans, self.entry.get(), self.entry, defults["block"])) block_btn_add.grid(row=1, column=3) ############ #boosted combo self.boost_drop = Combobox(self, postcommand=self.update_boosted) self.boost_drop['values'] = boosted self.boost_drop.current(0) self.boost_drop.grid(row=2, column=1, pady=1) self.entry2 = Entry(self) self.entry2.insert(0, "enter to buff priority") self.entry2.grid(row=2, column=4, pady=4) boost_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(boosted, self.boost_drop.get())) boost_btn_remv.grid(row=2, column=2) boost_btn_add = Button(self, text="Add", command=lambda: add_to_list(boosted, self.entry2.get(), self.entry2, defults["boost"])) boost_btn_add.grid(row=2, column=3) ######################################### #degraded combo self.deg_drop = Combobox(self, postcommand=self.update_degraded) self.deg_drop['values'] = degraded self.deg_drop.current(0) self.deg_drop.grid(row=3, column=1, pady=1) self.entry3 = Entry(self) self.entry3.insert(0, "enter to lower priority") self.entry3.grid(row=3, column=4, pady=4) deg_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(degraded, self.deg_drop.get())) deg_btn_remv.grid(row=3, column=2) deg_btn_add = Button(self, text="Add", command=lambda: add_to_list(degraded, self.entry3.get(), self.entry3, defults["degrade"])) deg_btn_add.grid(row=3, column=3) #### #music combo self.music_drop = Combobox(self, postcommand=self.update_music) self.music_drop['values'] = music_list.keys() self.music_drop.current(0) self.music_drop.grid(row=4, column=1, pady=1) self.entry4 = Entry(self) self.entry4.insert(0, "enter url") self.entry4.grid(row=4, column=5) self.entry5 = Entry(self) self.entry5.insert(0, "enter song's name") self.entry5.grid(row=4, column=4) music_btn_remv = Button(self, text="Remove", command=lambda: remove_from_list(music_list, self.music_drop.get())) music_btn_remv.grid(row=4, column=2) music_btn_add = Button(self, text="Add", command=lambda: add_music(music_list, self.entry5.get(),self.entry4.get() ,self.entry5, defults["music"])) music_btn_add.grid(row=4, column=3) abtn = Button(self, text="Activate", command=scan_computer_programs) abtn.grid(row=1, column=5, sticky=E) sbtn = Button(self, text="Stop", command=lambda: stop_running()) sbtn.grid(row=2, column=5, pady=6, sticky=E) cbtn = Button(self, text="Close", command=quit) cbtn.grid(row=3, column=5, pady=4, sticky=E) hbtn = Button(self, text="Save", command=save_lists) hbtn.grid(row=6, column=0, sticky=W) tsbtn = Button(self, text="TaskManager", command=lambda: os.system("TaskManager\pyProcMon.py")) tsbtn.grid(row=3, column=5, sticky=E) obtn = Button(self, text="start", command=lambda: call_running(area, threads["procs"], check_box)) obtn.grid(row=6, column=5, sticky=E)
class vco_model_win(Toplevel): def __init__(self, parent): Toplevel.__init__(self) img = ImageTk.PhotoImage(file=os.path.join(os.path.dirname(__file__), 'Icons/LMS8001_PLLSim.png')) self.tk.call('wm', 'iconphoto', self._w, img) self.resizable(0, 0) self.parent = parent self.pll = self.parent.pll self.initUI() center_Window(self) self.protocol("WM_DELETE_WINDOW", self.on_Quit) def initUI(self): self.title("LMS8001-PLL-VCO Model Definition") self.style = Style() self.style.theme_use("default") self.columnconfigure(0, pad=1) self.columnconfigure(1, pad=1) self.columnconfigure(2, pad=1) #self.columnconfigure(3, pad=1, weight=1) self.rowconfigure(0, pad=10) self.rowconfigure(1, pad=1, weight=1) self.rowconfigure(2, pad=1, weight=1) self.rowconfigure(3, pad=15, weight=1) self.rowconfigure(4, pad=1, weight=1) self.VCO_EM = BooleanVar() self.VCO_EM.set(self.parent.VCO_EM.get()) self.cbox_vco_em = Checkbutton(self, text='Use EM (RLCK) VCO Model', onvalue=1, offvalue=0, variable=self.VCO_EM, command=self.on_VCO_EM) self.cbox_vco_em.grid(row=0, column=0, columnspan=3, sticky=W) self.radio_fvco = IntVar() self.radio_fvco.set(int(self.parent.VCO_MEAS_FREQ.get())) self.radio_fvco_meas = Radiobutton( self, text='Use Measured VCO Frequency Values in Analysis', variable=self.radio_fvco, value=1) self.radio_fvco_meas.grid(row=1, column=0, columnspan=2, padx=15, sticky=W + N) self.radio_fvco_sim = Radiobutton( self, text='Use Simulated VCO Frequency Values in Analysis', variable=self.radio_fvco, value=0) self.radio_fvco_sim.grid(row=2, column=0, columnspan=2, padx=15, sticky=W + N) buttonFreq = Button(self, text='Plot Freq', command=self.on_FREQ, width=10) buttonFreq.grid(row=3, column=0, sticky=W + E) buttonKVCO = Button(self, text='Plot KVCO', command=self.on_KVCO, width=10) buttonKVCO.grid(row=3, column=1, sticky=W + E) buttonFSTEP = Button(self, text='Plot FSTEP', command=self.on_FSTEP, width=17) buttonFSTEP.grid(row=3, column=2, sticky=W + E) buttonOK = Button(self, text='OK', command=self.on_OK, width=10) buttonOK.grid(row=4, column=0, sticky=W + E) buttonQuit = Button(self, text='Quit', command=self.on_Quit, width=17) buttonQuit.grid(row=4, column=2, sticky=W + E) buttonApply = Button(self, text='Apply', command=self.on_Apply, width=10) buttonApply.grid(row=4, column=1, sticky=W + E) self.on_VCO_EM() #self.pack(fill=BOTH, expand=True) def get_vals(self): if (self.VCO_EM.get()): EM_MODEL = True if (self.radio_fvco.get()): MEAS_FREQ = True else: MEAS_FREQ = False else: EM_MODEL = False MEAS_FREQ = False return (EM_MODEL, MEAS_FREQ) def on_FREQ(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fvco = np.array(np.empty([3, 256])) for sel in range(1, 4): for freq in range(0, 256): fvco[sel - 1, freq] = vco.calcF(sel, freq, 0.6) figure(15) plt1, = plotsig(range(0, 256), fvco[0, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='black', font_name=self.parent.font_name) plt2, = plotsig(range(0, 256), fvco[1, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig(range(0, 256), fvco[2, :] / 1.0e9, 15, xlabel='$Cap. Bank Code$', ylabel='$F_{VCO} [GHz]$', title='VCO Frequency vs. Cap Bank Code', line_color='red', font_name=self.parent.font_name) setlegend(15, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_KVCO(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fvco = np.array(np.empty([3, 256])) NDIV = np.array(np.empty([3, 256])) kvco = np.array(np.empty([3, 256])) for sel in range(1, 4): for freq in range(0, 256): fvco[sel - 1, freq] = vco.calcF(sel, freq, 0.6) kvco[sel - 1, freq] = vco.calcKVCO(sel, freq, 0.6) NDIV[sel - 1, freq] = 1.0 * fvco[sel - 1, freq] / self.pll.Fref for sel in range(1, 4): kvco_avg = 1.0 kvco_over_NDIV_avg = 1.0 for freq in range(0, 256): kvco_avg = kvco_avg * (kvco[sel - 1, freq] / 1.0e6)**(1.0 / 256) kvco_over_NDIV_avg = kvco_over_NDIV_avg * ( (kvco[sel - 1, freq] / 1.0e6) / NDIV[sel - 1, freq])**(1.0 / 256.0) print 'VCO_SEL=%d, KVCO_AVG=%.3f MHz/V, KVCO_over_NDIV_AVG=%.3f MHz/V' % ( sel, kvco_avg, kvco_over_NDIV_avg) print '' figure(16) plt1, = plotsig(fvco[0, :] / 1.0e9, kvco[0, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='black', font_name=self.parent.font_name) plt2, = plotsig(fvco[1, :] / 1.0e9, kvco[1, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig(fvco[2, :] / 1.0e9, kvco[2, :] / 1.0e6, 16, xlabel='$F_{VCO} [GHz]$', ylabel='$K_{VCO} [MHz/V]$', title='VCO Sensitivity vs. Frequency', line_color='red', font_name=self.parent.font_name) setlegend(16, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_FSTEP(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() vco = lms8001_vco(EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ) fstep = np.array(np.empty([3, 255])) for sel in range(1, 4): for freq in range(0, 255): fstep[sel - 1, freq] = vco.calcF(sel, freq + 1, 0.6) - vco.calcF( sel, freq, 0.6) figure(17) plt1, = plotsig( range(0, 255), fstep[0, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='black', font_name=self.parent.font_name) plt2, = plotsig( range(0, 255), fstep[1, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='blue', font_name=self.parent.font_name) plt3, = plotsig( range(0, 255), fstep[2, :] / 1.0e6, 17, xlabel='$Cap. Bank Code$', ylabel='$F_{STEP} [MHz/V]$', title='VCO Frequency Step Between Adjacent Tuning Bands', line_color='red', font_name=self.parent.font_name) setlegend(17, [plt1, plt2, plt3], ['VCO_SEL=1', 'VCO_SEL=2', 'VCO_SEL=3'], font_name=self.parent.font_name) show_plots() def on_VCO_EM(self): if (self.VCO_EM.get()): self.radio_fvco_meas.config(state='enabled') self.radio_fvco_sim.config(state='enabled') else: self.radio_fvco_meas.config(state='disabled') self.radio_fvco_sim.config(state='disabled') def on_OK(self): self.on_Apply() self.on_Quit() def on_Quit(self): self.parent.vco_model_win = None self.destroy() def on_Apply(self): (EM_MODEL, MEAS_FREQ) = self.get_vals() self.parent.VCO_EM.set(EM_MODEL) self.parent.VCO_MEAS_FREQ.set(MEAS_FREQ) self.pll.vco = lms8001_vco(SEL=2, FREQ=128, EM_MODEL=EM_MODEL, MEAS_FREQ=MEAS_FREQ)
def __init__(self): u""" Main window constructor Creates 1 frame and 2 labeled subframes """ # first: the log # see: http://sametmax.com/ecrire-des-logs-en-python/ self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) # all errors will be get log_form = logging.Formatter('%(asctime)s || %(levelname)s || %(message)s') logfile = RotatingFileHandler('Metadator_LOG.log', 'a', 5000000, 1) logfile.setLevel(logging.DEBUG) logfile.setFormatter(log_form) self.logger.addHandler(logfile) self.logger.info('\n\t ======== Metadator ========') # first messages self.logger.info('Starting the UI') # checking the path to GDAL in the path if "GDAL_DATA" not in env.keys(): try: gdal.SetConfigOption(str('GDAL_DATA'), str(path.abspath(r'data/gdal'))) except: print("Oups! Something has gone wrong...\ see: https://github.com/Guts/Metadator/issues/21") else: pass # basics settings Tk.__init__(self) # constructor of parent graphic class self.title(u'Metadator {0}'.format(MetadatorVersion)) self.style = Style() # more friendly windows style if opersys == 'win32': self.logger.info('Op. system: {0}'.format(platform.platform())) self.iconbitmap('Metadator.ico') # windows icon self.uzer = env.get(u'USERNAME') elif opersys == 'linux2': self.logger.info('Op. system: {0}'.format(platform.platform())) self.uzer = env.get(u'USER') icon = Image("photo", file=r'data/img/metadator.gif') self.call('wm', 'iconphoto', self._w, icon) self.minsize(580, 100) self.style.theme_use('clam') elif opersys == 'darwin': self.logger.info('Op. system: {0}'.format(platform.platform())) self.uzer = env.get(u'USER') else: self.logger.warning('Operating system not tested') self.logger.info('Op. system: {0}'.format(platform.platform())) self.resizable(width=False, height=False) self.focus_force() self.logger.info('GDAL version: {}'.format(gdal.__version__)) # variables self.def_rep = "" # folder to search for self.def_lang = 'FR' # language to start self.def_doc = IntVar() # to export into Word self.def_xls = IntVar() # to export into Excel 2003 self.def_xml = IntVar() # to export into ISO 19139 self.def_cat = IntVar() # to merge all output Word files self.def_odt = IntVar() # to export into OpenDocumentText self.def_dict = IntVar() # to make a dictionnary of data self.def_kass = IntVar() # to handle field name case sensitive self.def_stat = IntVar() # to active/disable stats fields self.li_pro = [] # list for profiles in language selected self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.num_folders = 0 # number of folders explored self.today = strftime("%Y-%m-%d") # date of the day self.dico_layer = OD() # dictionary about layer properties self.dico_profil = OD() # dictionary from profile selected self.dico_fields = OD() # dictionary for fields information self.dico_rekur = OD() # dictionary of recurring attributes self.dico_err = OD() # errors list self.dico_help = OD() # dictionary of help texts li_lang = [lg for lg in listdir(r'locale')] # available languages self.blabla = OD() # texts dictionary # GUI fonts ft_tit = tkFont.Font(family="Times", size=10, weight=tkFont.BOLD) # fillfulling self.load_settings() self.load_texts(self.def_lang) self.li_profiles(self.def_lang) self.li_rekurs(self.def_lang) self.recup_help(self.def_lang) # Tabs self.nb = Notebook(self) self.tab_globals = Frame(self.nb) # tab_id = 0 self.tab_options = Frame(self.nb) # tab_id = 1 self.tab_attribs = Frame(self.nb) # tab_id = 2 self.nb.add(self.tab_globals, text=self.blabla.get('gui_tab1'), padding=3) self.nb.add(self.tab_options, text=self.blabla.get('gui_tab2'), padding=3) self.nb.add(self.tab_attribs, text=self.blabla.get('gui_tab3'), padding=3) self.logger.info('UI created') ### Tab 1: global # Frames self.FrPath = Labelframe(self.tab_globals, name='main', text=self.blabla.get('tab1_fr1')) self.FrProg = Labelframe(self.tab_globals, name='progression', text=self.blabla.get('tab1_frprog')) ## Frame 1 # target folder self.labtarg = Label(self.FrPath, text=self.blabla.get('tab1_path')) self.target = Entry(self.FrPath, width=25) self.browsetarg = Button(self.FrPath, # browse button text=self.blabla.get('tab1_browse'), command=lambda: self.setpathtarg(), takefocus=True) self.browsetarg.focus_force() # force the focus on self.profil = Label(self.FrPath, text=self.blabla.get('tab1_prof')) # profiles switcher self.ddl_profil = Combobox(self.FrPath, values=self.li_pro, width=5) self.ddl_profil.current(0) self.ddl_profil.bind("<<ComboboxSelected>>", self.select_profil) # widgets placement self.labtarg.grid(row=1, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=8) self.target.grid(row=1, column=2, columnspan=1, sticky=N + S + W + E, padx=2, pady=8) self.browsetarg.grid(row=1, column=3, sticky=N + S + W + E, padx=2, pady=8) self.profil.grid(row=2, column=1, sticky=N + S + W + E, padx=2, pady=8) self.ddl_profil.grid(row=2, column=2, sticky=W + E + N + S, columnspan=2, padx=2, pady=8) # tooltips InfoBulle(self.target, message=self.dico_help.get(30)[1]) InfoBulle(self.browsetarg, message=self.dico_help.get(30)[1]) InfoBulle(self.ddl_profil, message=self.dico_help.get(31)[1]) ## Frame 2 # variables self.status = StringVar(self.FrProg, '') # widgets self.prog_layers = Progressbar(self.FrProg, orient="horizontal") self.prog_fields = Progressbar(self.FrProg, orient="horizontal") # widgets placement Label(self.FrProg, textvariable=self.status, foreground='DodgerBlue').pack(expand=1) self.prog_layers.pack(expand=1, fill=X) # Frames placement self.FrPath.pack(expand=1, fill='both') self.FrProg.pack(expand=1, fill='both') ### Tab 2: options # Export options caz_doc = Checkbutton(self.tab_options, text=u'HTML / Word (.doc/.docx)', variable=self.def_doc, command=lambda: self.catalog_dependance()) caz_xls = Checkbutton(self.tab_options, text=u'Excel 2003 (.xls)', variable=self.def_xls) caz_xml = Checkbutton(self.tab_options, text=u'XML (ISO 19139)', variable=self.def_xml) self.caz_cat = Checkbutton(self.tab_options, text=self.blabla.get('tab2_merge'), variable=self.def_cat) caz_odt = Checkbutton(self.tab_options, text=u'Open Document Text (.odt)', variable=self.def_odt) # widgets placement caz_doc.grid(row=1, column=0, sticky=N + S + W + E, padx=2, pady=2) self.caz_cat.grid(row=2, column=0, sticky=N + S + W + E, padx=2, pady=2) caz_xls.grid(row=1, column=1, sticky=N + S + W + E, padx=2, pady=2) caz_xml.grid(row=2, column=1, sticky=N + S + W + E, padx=2, pady=2) caz_odt.grid(row=3, column=1, sticky=N + S + W + E, padx=2, pady=2) # disabling the widgets which work only on Windows OS if opersys != 'win32': self.logger.info('Disabling Windows reserved functions.') self.def_doc.set(0) self.def_cat.set(0) caz_doc.configure(state='disabled') self.caz_cat.configure(state='disabled') else: pass # make the catalog option depending on the Word option self.catalog_dependance() # tooltips InfoBulle(caz_doc, message=self.dico_help.get(33)[1], image=self.dico_help.get(33)[2]) InfoBulle(caz_xls, message=self.dico_help.get(34)[1], image=self.dico_help.get(34)[2]) InfoBulle(caz_xml, message=self.dico_help.get(35)[1], image=self.dico_help.get(35)[2]) InfoBulle(caz_odt, message=self.dico_help.get(36)[1], image=self.dico_help.get(36)[2]) InfoBulle(self.caz_cat, message=self.dico_help.get(37)[1], image=self.dico_help.get(37)[2]) ### Tab 3: recurring attributes # Attribute selector self.lab_chps = Label(self.tab_attribs, text=self.blabla.get('tab3_sele')) self.ddl_attr = Combobox(self.tab_attribs, values=self.dico_rekur.keys()) self.ddl_attr.bind("<<ComboboxSelected>>", self.edit_rekur) self.supr = Button(self.tab_attribs, text=self.blabla.get('tab3_supp'), command=self.del_rekur) # frame self.FrRekur = Labelframe(self.tab_attribs, name='attributes', text=self.blabla.get('tab3_tit')) # attribute settings self.tab3_LBnom = Label(self.FrRekur, text=self.blabla.get('tab3_nom'), state=DISABLED) self.tab3_ENnom = Entry(self.FrRekur, state=DISABLED) self.tab3_LBdesc = Label(self.FrRekur, text=self.blabla.get('tab3_desc'), state=DISABLED) self.tab3_TXdesc = Text(self.FrRekur, height=5, width=30, wrap=WORD, state=DISABLED) self.tab3_CBcass = Checkbutton(self.FrRekur, text=self.blabla.get('tab3_cass'), variable=self.def_kass, state=DISABLED) self.tab3_CBstat = Checkbutton(self.FrRekur, text=self.blabla.get('tab3_stat'), variable=self.def_stat, state=DISABLED) # Validation button self.save = Button(self.FrRekur, text=self.blabla.get('tab3_save'), command=self.save_rekur, state='disabled') # widgets placement self.lab_chps.grid(row=1, column=1, sticky=N + S + W, padx=2, pady=2) self.ddl_attr.grid(row=1, column=2, sticky=N + S + W + E, padx=2, pady=2) self.supr.grid(row=1, column=3, sticky=N + S + W + E, padx=2, pady=2) self.tab3_LBnom.grid(row=1, column=0, columnspan=1, sticky=N + S + W, padx=2, pady=2) self.tab3_ENnom.grid(row=1, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_LBdesc.grid(row=2, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_TXdesc.grid(row=2, column=1, columnspan=2, sticky=N + S + W + E, padx=2, pady=2) self.tab3_CBcass.grid(row=3, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_CBstat.grid(row=3, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.save.grid(row=5, column=0, columnspan=4, sticky=N + S + W + E, padx=2, pady=2) # Frame placement self.FrRekur.grid(row=2, column=1, columnspan=3, sticky=N + S + W + E, padx=2, pady=2) # tooltips InfoBulle(self.lab_chps, message=self.dico_help.get(38)[1]) InfoBulle(self.ddl_attr, message=self.dico_help.get(39)[1]) InfoBulle(self.supr, message=self.dico_help.get(40)[1]) InfoBulle(self.tab3_CBcass, message=self.dico_help.get(41)[1]) InfoBulle(self.tab3_CBstat, message=self.dico_help.get(42)[1]) ## Main frame # Hola self.welcome = Label(self, text=self.blabla.get('hi') + self.uzer, font=ft_tit, foreground="red2") # Image self.icone = PhotoImage(master=self, file=r'data/img/metadator.gif') Label(self, image=self.icone).grid(row=2, column=0, padx=2, pady=2, sticky=N + S + W + E) # credits s = Style(self) s.configure('Kim.TButton', foreground='DodgerBlue', borderwidth=0, relief="flat") Button(self, text='by Julien M. (2015)', style='Kim.TButton', command=lambda: open_new('https://github.com/Guts')).grid(row=3, padx=2, pady=2, sticky=W+E) # language switcher self.ddl_lang = Combobox(self, values=li_lang, width=5) self.ddl_lang.current(li_lang.index(self.def_lang)) self.ddl_lang.bind("<<ComboboxSelected>>", self.change_lang) # Go go go button self.val = Button(self, text=self.blabla.get('tab1_go'), state='active', command=lambda: self.process()) # Cancel button self.can = Button(self, text=self.blabla.get('gui_quit'), command=self.destroy) # widgets placement self.welcome.grid(row=0, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.ddl_lang.grid(row=1, column=0, sticky=N, padx=2, pady=0) self.can.grid(row=4, column=0, sticky=N + S + W + E, padx=2, pady=2) self.val.grid(row=4, column=1, sticky=N + S + W + E, padx=2, pady=2) # tooltips InfoBulle(self.ddl_lang, message=self.dico_help.get(32)[1]) ### Notebook placement self.nb.grid(row=0, rowspan=4, column=1, sticky=N + S + W + E) # keep updated list of profiles self.maj()
def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0, columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva, value=1, command=self.cambiaFormula, width=17).grid(row=1, columnspan=2, sticky=W, padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva, value=2, command=self.cambiaFormula).grid(row=2, columnspan=2, sticky=W, padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame, textvariable=self.aaa).grid(row=5, column=0, pady=2) Label(editarFrame, textvariable=self.bbb).grid(row=6, column=0, pady=2) self.labelC = Label(editarFrame, textvariable=self.ccc) self.labelC.grid(row=7, column=0, pady=2) self.labelC.config(state=DISABLED) Label(editarFrame, textvariable=self.Lma).grid(row=8, column=0, pady=2) Label(editarFrame, textvariable=self.fre).grid(row=9, column=0, pady=2) parA = Entry(editarFrame, width=4, textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame, width=4, textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame, width=4, textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame, width=4, textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame, width=4, textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage( data= '''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''' ) saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3, textvariable=self.lenlen).grid(row=1, column=0, pady=4, padx=12) Label(frame3, textvariable=self.radrad).grid(row=2, column=0, pady=4, padx=12) Label(frame3, textvariable=self.StringLongitud).grid(row=1, column=1, pady=4) Label(frame3, textvariable=self.StringRadio).grid(row=2, column=1, pady=4)
class Metadator(Tk): def __init__(self): u""" Main window constructor Creates 1 frame and 2 labeled subframes """ # first: the log # see: http://sametmax.com/ecrire-des-logs-en-python/ self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) # all errors will be get log_form = logging.Formatter('%(asctime)s || %(levelname)s || %(message)s') logfile = RotatingFileHandler('Metadator_LOG.log', 'a', 5000000, 1) logfile.setLevel(logging.DEBUG) logfile.setFormatter(log_form) self.logger.addHandler(logfile) self.logger.info('\n\t ======== Metadator ========') # first messages self.logger.info('Starting the UI') # checking the path to GDAL in the path if "GDAL_DATA" not in env.keys(): try: gdal.SetConfigOption(str('GDAL_DATA'), str(path.abspath(r'data/gdal'))) except: print("Oups! Something has gone wrong...\ see: https://github.com/Guts/Metadator/issues/21") else: pass # basics settings Tk.__init__(self) # constructor of parent graphic class self.title(u'Metadator {0}'.format(MetadatorVersion)) self.style = Style() # more friendly windows style if opersys == 'win32': self.logger.info('Op. system: {0}'.format(platform.platform())) self.iconbitmap('Metadator.ico') # windows icon self.uzer = env.get(u'USERNAME') elif opersys == 'linux2': self.logger.info('Op. system: {0}'.format(platform.platform())) self.uzer = env.get(u'USER') icon = Image("photo", file=r'data/img/metadator.gif') self.call('wm', 'iconphoto', self._w, icon) self.minsize(580, 100) self.style.theme_use('clam') elif opersys == 'darwin': self.logger.info('Op. system: {0}'.format(platform.platform())) self.uzer = env.get(u'USER') else: self.logger.warning('Operating system not tested') self.logger.info('Op. system: {0}'.format(platform.platform())) self.resizable(width=False, height=False) self.focus_force() self.logger.info('GDAL version: {}'.format(gdal.__version__)) # variables self.def_rep = "" # folder to search for self.def_lang = 'FR' # language to start self.def_doc = IntVar() # to export into Word self.def_xls = IntVar() # to export into Excel 2003 self.def_xml = IntVar() # to export into ISO 19139 self.def_cat = IntVar() # to merge all output Word files self.def_odt = IntVar() # to export into OpenDocumentText self.def_dict = IntVar() # to make a dictionnary of data self.def_kass = IntVar() # to handle field name case sensitive self.def_stat = IntVar() # to active/disable stats fields self.li_pro = [] # list for profiles in language selected self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.num_folders = 0 # number of folders explored self.today = strftime("%Y-%m-%d") # date of the day self.dico_layer = OD() # dictionary about layer properties self.dico_profil = OD() # dictionary from profile selected self.dico_fields = OD() # dictionary for fields information self.dico_rekur = OD() # dictionary of recurring attributes self.dico_err = OD() # errors list self.dico_help = OD() # dictionary of help texts li_lang = [lg for lg in listdir(r'locale')] # available languages self.blabla = OD() # texts dictionary # GUI fonts ft_tit = tkFont.Font(family="Times", size=10, weight=tkFont.BOLD) # fillfulling self.load_settings() self.load_texts(self.def_lang) self.li_profiles(self.def_lang) self.li_rekurs(self.def_lang) self.recup_help(self.def_lang) # Tabs self.nb = Notebook(self) self.tab_globals = Frame(self.nb) # tab_id = 0 self.tab_options = Frame(self.nb) # tab_id = 1 self.tab_attribs = Frame(self.nb) # tab_id = 2 self.nb.add(self.tab_globals, text=self.blabla.get('gui_tab1'), padding=3) self.nb.add(self.tab_options, text=self.blabla.get('gui_tab2'), padding=3) self.nb.add(self.tab_attribs, text=self.blabla.get('gui_tab3'), padding=3) self.logger.info('UI created') ### Tab 1: global # Frames self.FrPath = Labelframe(self.tab_globals, name='main', text=self.blabla.get('tab1_fr1')) self.FrProg = Labelframe(self.tab_globals, name='progression', text=self.blabla.get('tab1_frprog')) ## Frame 1 # target folder self.labtarg = Label(self.FrPath, text=self.blabla.get('tab1_path')) self.target = Entry(self.FrPath, width=25) self.browsetarg = Button(self.FrPath, # browse button text=self.blabla.get('tab1_browse'), command=lambda: self.setpathtarg(), takefocus=True) self.browsetarg.focus_force() # force the focus on self.profil = Label(self.FrPath, text=self.blabla.get('tab1_prof')) # profiles switcher self.ddl_profil = Combobox(self.FrPath, values=self.li_pro, width=5) self.ddl_profil.current(0) self.ddl_profil.bind("<<ComboboxSelected>>", self.select_profil) # widgets placement self.labtarg.grid(row=1, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=8) self.target.grid(row=1, column=2, columnspan=1, sticky=N + S + W + E, padx=2, pady=8) self.browsetarg.grid(row=1, column=3, sticky=N + S + W + E, padx=2, pady=8) self.profil.grid(row=2, column=1, sticky=N + S + W + E, padx=2, pady=8) self.ddl_profil.grid(row=2, column=2, sticky=W + E + N + S, columnspan=2, padx=2, pady=8) # tooltips InfoBulle(self.target, message=self.dico_help.get(30)[1]) InfoBulle(self.browsetarg, message=self.dico_help.get(30)[1]) InfoBulle(self.ddl_profil, message=self.dico_help.get(31)[1]) ## Frame 2 # variables self.status = StringVar(self.FrProg, '') # widgets self.prog_layers = Progressbar(self.FrProg, orient="horizontal") self.prog_fields = Progressbar(self.FrProg, orient="horizontal") # widgets placement Label(self.FrProg, textvariable=self.status, foreground='DodgerBlue').pack(expand=1) self.prog_layers.pack(expand=1, fill=X) # Frames placement self.FrPath.pack(expand=1, fill='both') self.FrProg.pack(expand=1, fill='both') ### Tab 2: options # Export options caz_doc = Checkbutton(self.tab_options, text=u'HTML / Word (.doc/.docx)', variable=self.def_doc, command=lambda: self.catalog_dependance()) caz_xls = Checkbutton(self.tab_options, text=u'Excel 2003 (.xls)', variable=self.def_xls) caz_xml = Checkbutton(self.tab_options, text=u'XML (ISO 19139)', variable=self.def_xml) self.caz_cat = Checkbutton(self.tab_options, text=self.blabla.get('tab2_merge'), variable=self.def_cat) caz_odt = Checkbutton(self.tab_options, text=u'Open Document Text (.odt)', variable=self.def_odt) # widgets placement caz_doc.grid(row=1, column=0, sticky=N + S + W + E, padx=2, pady=2) self.caz_cat.grid(row=2, column=0, sticky=N + S + W + E, padx=2, pady=2) caz_xls.grid(row=1, column=1, sticky=N + S + W + E, padx=2, pady=2) caz_xml.grid(row=2, column=1, sticky=N + S + W + E, padx=2, pady=2) caz_odt.grid(row=3, column=1, sticky=N + S + W + E, padx=2, pady=2) # disabling the widgets which work only on Windows OS if opersys != 'win32': self.logger.info('Disabling Windows reserved functions.') self.def_doc.set(0) self.def_cat.set(0) caz_doc.configure(state='disabled') self.caz_cat.configure(state='disabled') else: pass # make the catalog option depending on the Word option self.catalog_dependance() # tooltips InfoBulle(caz_doc, message=self.dico_help.get(33)[1], image=self.dico_help.get(33)[2]) InfoBulle(caz_xls, message=self.dico_help.get(34)[1], image=self.dico_help.get(34)[2]) InfoBulle(caz_xml, message=self.dico_help.get(35)[1], image=self.dico_help.get(35)[2]) InfoBulle(caz_odt, message=self.dico_help.get(36)[1], image=self.dico_help.get(36)[2]) InfoBulle(self.caz_cat, message=self.dico_help.get(37)[1], image=self.dico_help.get(37)[2]) ### Tab 3: recurring attributes # Attribute selector self.lab_chps = Label(self.tab_attribs, text=self.blabla.get('tab3_sele')) self.ddl_attr = Combobox(self.tab_attribs, values=self.dico_rekur.keys()) self.ddl_attr.bind("<<ComboboxSelected>>", self.edit_rekur) self.supr = Button(self.tab_attribs, text=self.blabla.get('tab3_supp'), command=self.del_rekur) # frame self.FrRekur = Labelframe(self.tab_attribs, name='attributes', text=self.blabla.get('tab3_tit')) # attribute settings self.tab3_LBnom = Label(self.FrRekur, text=self.blabla.get('tab3_nom'), state=DISABLED) self.tab3_ENnom = Entry(self.FrRekur, state=DISABLED) self.tab3_LBdesc = Label(self.FrRekur, text=self.blabla.get('tab3_desc'), state=DISABLED) self.tab3_TXdesc = Text(self.FrRekur, height=5, width=30, wrap=WORD, state=DISABLED) self.tab3_CBcass = Checkbutton(self.FrRekur, text=self.blabla.get('tab3_cass'), variable=self.def_kass, state=DISABLED) self.tab3_CBstat = Checkbutton(self.FrRekur, text=self.blabla.get('tab3_stat'), variable=self.def_stat, state=DISABLED) # Validation button self.save = Button(self.FrRekur, text=self.blabla.get('tab3_save'), command=self.save_rekur, state='disabled') # widgets placement self.lab_chps.grid(row=1, column=1, sticky=N + S + W, padx=2, pady=2) self.ddl_attr.grid(row=1, column=2, sticky=N + S + W + E, padx=2, pady=2) self.supr.grid(row=1, column=3, sticky=N + S + W + E, padx=2, pady=2) self.tab3_LBnom.grid(row=1, column=0, columnspan=1, sticky=N + S + W, padx=2, pady=2) self.tab3_ENnom.grid(row=1, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_LBdesc.grid(row=2, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_TXdesc.grid(row=2, column=1, columnspan=2, sticky=N + S + W + E, padx=2, pady=2) self.tab3_CBcass.grid(row=3, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.tab3_CBstat.grid(row=3, column=1, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.save.grid(row=5, column=0, columnspan=4, sticky=N + S + W + E, padx=2, pady=2) # Frame placement self.FrRekur.grid(row=2, column=1, columnspan=3, sticky=N + S + W + E, padx=2, pady=2) # tooltips InfoBulle(self.lab_chps, message=self.dico_help.get(38)[1]) InfoBulle(self.ddl_attr, message=self.dico_help.get(39)[1]) InfoBulle(self.supr, message=self.dico_help.get(40)[1]) InfoBulle(self.tab3_CBcass, message=self.dico_help.get(41)[1]) InfoBulle(self.tab3_CBstat, message=self.dico_help.get(42)[1]) ## Main frame # Hola self.welcome = Label(self, text=self.blabla.get('hi') + self.uzer, font=ft_tit, foreground="red2") # Image self.icone = PhotoImage(master=self, file=r'data/img/metadator.gif') Label(self, image=self.icone).grid(row=2, column=0, padx=2, pady=2, sticky=N + S + W + E) # credits s = Style(self) s.configure('Kim.TButton', foreground='DodgerBlue', borderwidth=0, relief="flat") Button(self, text='by Julien M. (2015)', style='Kim.TButton', command=lambda: open_new('https://github.com/Guts')).grid(row=3, padx=2, pady=2, sticky=W+E) # language switcher self.ddl_lang = Combobox(self, values=li_lang, width=5) self.ddl_lang.current(li_lang.index(self.def_lang)) self.ddl_lang.bind("<<ComboboxSelected>>", self.change_lang) # Go go go button self.val = Button(self, text=self.blabla.get('tab1_go'), state='active', command=lambda: self.process()) # Cancel button self.can = Button(self, text=self.blabla.get('gui_quit'), command=self.destroy) # widgets placement self.welcome.grid(row=0, column=0, columnspan=1, sticky=N + S + W + E, padx=2, pady=2) self.ddl_lang.grid(row=1, column=0, sticky=N, padx=2, pady=0) self.can.grid(row=4, column=0, sticky=N + S + W + E, padx=2, pady=2) self.val.grid(row=4, column=1, sticky=N + S + W + E, padx=2, pady=2) # tooltips InfoBulle(self.ddl_lang, message=self.dico_help.get(32)[1]) ### Notebook placement self.nb.grid(row=0, rowspan=4, column=1, sticky=N + S + W + E) # keep updated list of profiles self.maj() def maj(self): """ update the profiles dropdown list every second """ try: self.li_profiles(self.ddl_lang.get()) self.ddl_profil['values'] = self.li_pro self.after(1000, self.maj) except WindowsError: # avoid an error occuring with browse button self.after(1000, self.maj) pass def alter_state(self, parent, new_state): """ just a function to change easily the state of all children widgets of a parent class parent=Tkinter class with children (Frame, Labelframe, Tk, etc.) new_state=Tkinter keyword for widget state (ACTIVE, NORMAL, DISABLED) """ for child in parent.winfo_children(): child.configure(state=new_state) # end of function return parent, new_state def catalog_dependance(self): """ unselect the catalog option if the word option is unselected """ if self.def_doc.get() == 0: self.def_cat.set(0) self.caz_cat.config(state='disabled') elif self.def_doc.get() == 1: self.caz_cat.config(state='normal') # end of function return def load_settings(self): u""" load settings from last execution """ confile = 'options.ini' config = ConfigParser.RawConfigParser() config.read(confile) # basics self.def_lang = config.get('basics', 'def_codelang') self.def_rep = config.get('basics', 'def_rep') # export preferences self.def_doc.set(config.get('export_preferences', 'def_word')) self.def_cat.set(config.get('export_preferences', 'def_cat')) self.def_xls.set(config.get('export_preferences', 'def_xls')) self.def_xml.set(config.get('export_preferences', 'def_xml')) self.def_dict.set(config.get('export_preferences', 'def_dict')) self.def_odt.set(config.get('export_preferences', 'def_odt')) # log self.logger.info('Last options loaded') # End of function return config, self.def_rep, self.def_lang, self.def_doc def save_settings(self): u""" save options in order to make the next execution easier """ confile = 'options.ini' config = ConfigParser.RawConfigParser() # add sections config.add_section('basics') config.add_section('export_preferences') # basics config.set('basics', 'def_codelang', self.ddl_lang.get()) config.set('basics', 'def_rep', self.target.get()) # export preferences config.set('export_preferences', 'def_word', self.def_doc.get()) config.set('export_preferences', 'def_cat', self.def_cat.get()) config.set('export_preferences', 'def_xls', self.def_xls.get()) config.set('export_preferences', 'def_xml', self.def_xml.get()) config.set('export_preferences', 'def_dict', self.def_dict.get()) config.set('export_preferences', 'def_odt', self.def_odt.get()) # Writing the configuration file with open(confile, 'wb') as configfile: config.write(configfile) # End of function return config def change_lang(self, event): u""" update the texts dictionary with the language selected """ new_lang = event.widget.get() # change to the new language selected self.load_texts(new_lang) self.li_profiles(new_lang) self.li_rekurs(new_lang) self.ddl_profil.delete(0, END) self.ddl_profil.config(values=self.li_pro) self.ddl_profil.update() self.ddl_attr.config(values=self.dico_rekur.keys()) self.recup_help(new_lang) # update widgets text # tab1 self.nb.tab(0, text=self.blabla.get('gui_tab1')) self.welcome.config(text=self.blabla.get('hi') + self.uzer) self.can.config(text=self.blabla.get('gui_quit')) self.FrPath.config(text=self.blabla.get('tab1_fr1')) self.FrProg.config(text=self.blabla.get('tab1_frprog')) self.labtarg.config(text=self.blabla.get('tab1_path')) self.browsetarg.config(text=self.blabla.get('tab1_browse')) self.val.config(text=self.blabla.get('tab1_go')) self.profil.config(text=self.blabla.get('tab1_prof')) # tab2 self.nb.tab(1, text=self.blabla.get('gui_tab2')) self.caz_cat.config(text=self.blabla.get('tab2_merge')) # tab3 self.nb.tab(2, text=self.blabla.get('gui_tab3')) self.lab_chps.config(text=self.blabla.get('tab3_sele')) self.supr.config(text=self.blabla.get('tab3_supp')) self.FrRekur.config(text=self.blabla.get('tab3_tit')) self.tab3_LBnom.config(text=self.blabla.get('tab3_nom')) self.tab3_LBdesc.config(text=self.blabla.get('tab3_desc')) self.tab3_CBcass.config(text=self.blabla.get('tab3_cass')) self.tab3_CBstat.config(text=self.blabla.get('tab3_stat')) self.save.config(text=self.blabla.get('tab3_save')) # End of function return self.blabla def load_texts(self, lang='FR'): u""" Load texts according to the selected language """ # clearing the text dictionary self.blabla.clear() # open xml cursor xml = ET.parse('locale/{0}/lang_{0}.xml'.format(lang)) # Looping and gathering texts from the xml file for elem in xml.getroot().getiterator(): self.blabla[elem.tag] = elem.text # updating the GUI self.update() # en of function return self.blabla def setpathtarg(self): """ ...browse and insert the path of target folder """ foldername = askdirectory(parent=self, initialdir=self.def_rep, mustexist=True, title=self.blabla.get('gui_cible')) # check if a folder has been choosen if foldername: try: self.target.delete(0, END) self.target.insert(0, foldername) except: info(title=self.blabla.get('nofolder'), message=self.blabla.get('nofolder')) return # count shapefiles and MapInfo files in a separated thread proc = threading.Thread(target=self.li_geofiles, args=(foldername, )) proc.daemon = True proc.start() # end of function return foldername def li_geofiles(self, foldertarget): u""" List shapefiles and MapInfo files (.tab, not .mid/mif) contained in the folders structure """ # reseting global variables self.li_shp = [] self.li_tab = [] self.browsetarg.config(state=DISABLED) # Looping in folders structure self.status.set(self.blabla.get('tab1_prog1')) self.prog_layers.start() for root, dirs, files in walk(unicode(foldertarget)): self.num_folders = self.num_folders + len(dirs) for f in files: """ looking for files with geographic data """ try: unicode(path.join(root, f)) full_path = path.join(root, f) except UnicodeDecodeError: full_path = path.join(root, f.decode('latin1')) # Looping on files contained if path.splitext(full_path.lower())[1].lower() == '.shp'\ and (path.isfile('{0}.dbf'.format(full_path[:-4])) or path.isfile('{0}.DBF'.format(full_path[:-4])))\ and (path.isfile('{0}.shx'.format(full_path[:-4])) or path.isfile('{0}.SHX'.format(full_path[:-4]))): """ listing compatible shapefiles """ # add complete path of shapefile self.li_shp.append(full_path) elif path.splitext(full_path.lower())[1] == '.tab'\ and (path.isfile(full_path[:-4] + '.dat') or path.isfile(full_path[:-4] + '.DAT'))\ and (path.isfile(full_path[:-4] + '.map') or path.isfile(full_path[:-4] + '.MAP'))\ and (path.isfile(full_path[:-4] + '.id') or path.isfile(full_path[:-4] + '.ID')): """ listing MapInfo tables """ # add complete path of MapInfo file self.li_tab.append(full_path) # stopping the progress bar self.prog_layers.stop() # Lists ordering and tupling self.li_shp.sort() self.li_shp = tuple(self.li_shp) self.li_tab.sort() self.li_tab = tuple(self.li_tab) # setting the label text and activing the buttons self.status.set(unicode(len(self.li_shp)) + u' shapefiles - ' + unicode(len(self.li_tab)) + u' tables (MapInfo) - ' + unicode(self.num_folders) + self.blabla.get('log_numfold')) self.browsetarg.config(state=ACTIVE) self.val.config(state=ACTIVE) # End of function return foldertarget, self.li_shp, self.li_tab def li_profiles(self, lang): u""" list profiles already existing """ # reseting global variable self.li_pro = [] # Looping in folders structure folder_profiles = path.join('locale/', lang + '/profiles/') self.li_pro = [lg[:-4] for lg in listdir(folder_profiles)] self.li_pro.append(self.blabla.get('tab1_new')) # End of function return folder_profiles, self.li_pro def li_rekurs(self, lang): u""" List recurring attributes that already exist in the selected language """ # clearing the text dictionary self.dico_rekur.clear() champis = path.abspath(r'locale/{0}/champignons_{0}.xml'.format(lang)) xml = ET.parse(champis) # Looping and gathering texts from the xml file for elem in xml.findall('champ'): rek_name = elem.find('intitule').text rek_desc = elem.find('description').text rek_kass = elem.find('case').text rek_stat = elem.find('stats').text self.dico_rekur[rek_name] = rek_desc, rek_kass, rek_stat self.dico_rekur[self.blabla.get('tab3_new')] = '', 0, 0 # updating the GUI self.update() # End of function return self.dico_rekur def edit_rekur(self, event): u""" preparing the form to edit a recurring attribute """ rekur = event.widget.get() # deactivate the selector self.ddl_attr.config(state=DISABLED) # activate the form self.alter_state(self.FrRekur, NORMAL) # change to the new language selected self.tab3_ENnom.insert(0, rekur) self.tab3_TXdesc.insert(1.0, self.dico_rekur.get(rekur)[0]) self.def_kass.set(self.dico_rekur.get(rekur)[1]) self.def_stat.set(self.dico_rekur.get(rekur)[2]) # End of function return self.dico_rekur def save_rekur(self): u""" save the recurring attribute edited """ # check if the attribute already exists if self.tab3_ENnom.get() in self.dico_rekur: if not askyesno(title=self.blabla.get('tab3_alert_exist1'), message=self.blabla.get('tab3_alert_exist2')): return else: pass else: pass # save self.dico_rekur[self.tab3_ENnom.get()] = self.tab3_TXdesc.get(1.0, END).rstrip(),\ self.def_kass.get(),\ self.def_stat.get() # reset the form self.tab3_ENnom.delete(0, END) self.tab3_TXdesc.delete(1.0, END) self.def_kass.set(0) self.def_stat.set(0) # deactivate the form self.alter_state(self.FrRekur, DISABLED) # updating the dropdown list self.ddl_attr.config(state=NORMAL) self.ddl_attr.delete(0, END) self.ddl_attr['values'] = self.dico_rekur.keys() # End of function return self.dico_rekur def del_rekur(self): u""" delete the selected recurring attribute """ # reactivate the selector self.ddl_attr.config(state=ACTIVE) self.dico_rekur.pop(self.ddl_attr.get()) self.ddl_attr.delete(0, END) self.ddl_attr['values'] = self.dico_rekur.keys() # reset the form self.tab3_ENnom.delete(0, END) self.tab3_TXdesc.delete(1.0, END) self.def_kass.set(0) self.def_stat.set(0) # deactivate the form self.alter_state(self.FrRekur, DISABLED) # End of function return self.dico_rekur def saveas_rekurs(self, lang): u""" save the recurring fields into the file dedicated """ rekur = ET.Element(u'champs') xml_path = r'locale/{0}/champignons_{0}.xml'.format(lang) self.dico_rekur.pop(self.blabla.get('tab3_new')) with open(xml_path, 'w') as champis: for elem in self.dico_rekur.keys(): rek = ET.SubElement(rekur, u'champ') # name of recurring attribute rek_name = ET.SubElement(rek, u'intitule') rek_name.text = elem # description of recurring attribute rek_desc = ET.SubElement(rek, u'description') rek_desc.text = self.dico_rekur.get(elem)[0] # stats option of recurring attribute rek_stats = ET.SubElement(rek, u'stats') rek_stats.text = unicode(self.dico_rekur.get(elem)[1]) # case sensitive option of recurring attribute rek_case = ET.SubElement(rek, u'case') rek_case.text = unicode(self.dico_rekur.get(elem)[2]) # creating the xml tree out_rekurs = ET.ElementTree(rekur) # saving it out_rekurs.write(xml_path, encoding='utf-8', xml_declaration='version="1.0"', method='xml') # End of function return self.dico_rekur def select_profil(self, event): """ when a profile is selected... """ profsel = event.widget.get() # if user wants to use an existing profile or create a new one if profsel == self.blabla.get('tab1_new'): self.val.config(text=self.blabla.get('tab1_crprofil')) else: self.val.config(text=self.blabla.get('tab1_go')) # end of function return self.val def recup_profil(self, lang): """ get the information from the profile selected """ # clearing the profile dictionary self.dico_profil.clear() # specific path to profile file path_profile = path.join('locale/{0}/profiles/{1}.xml'.format(lang, self.ddl_profil.get())) with open(path_profile, 'r') as profile: # open xml parser xml = ET.parse(profile) # basic informations self.dico_profil['description'] = xml.find('description').text self.dico_profil['sources'] = xml.find('sources').text self.dico_profil['url'] = xml.find('url').text self.dico_profil['url_label'] = xml.find('url_label').text self.dico_profil[u'diffusion'] = xml.find('diffusion').text # data language lang_data = xml.find(u'lang_data') self.dico_profil[u"lang_data"] = lang_data.find(u'name').text # metadata language lang_metad = xml.find(u'lang_metad') self.dico_profil[u"lang_md"] = lang_metad.find(u'name').text # diffusion constraints diff = xml.find(u'diffusion') self.dico_profil['diffusion'] = diff.find(u'name').text # update rythm rythm = xml.find(u'rythm') self.dico_profil['rythm'] = rythm.find(u'name').text # INSPIRE themes themes = xml.find('themesinspire') li_themesinspire = [theme.find('name').text for theme in themes.findall('theme')] self.dico_profil['themesinspire'] = li_themesinspire # custom keywords keywords = xml.find('keywords') li_keywords = [keyword.find('name').text for keyword in keywords.findall('keyword')] self.dico_profil['keywords'] = li_keywords # places keywords geokeywords = xml.find('geokeywords') li_geokeywords = [geokeyword.find('name').text for geokeyword in geokeywords.findall('geokeyword')] self.dico_profil['geokeywords'] = li_geokeywords # contacts contacts = xml.find(u'contacts') # point of contact cont = contacts.find(u'pointdecontact') self.dico_profil[u'cont_name'] = cont.find(u'name').text self.dico_profil[u'cont_orga'] = cont.find(u'org').text self.dico_profil[u'cont_mail'] = cont.find(u'mail').text self.dico_profil[u'cont_role'] = cont.find(u'role').text self.dico_profil[u'cont_func'] = cont.find(u'func')[0].text self.dico_profil[u'cont_street'] = cont.find(u'street').text self.dico_profil[u'cont_city'] = cont.find(u'city').text self.dico_profil[u'cont_cp'] = cont.find(u'cp').text self.dico_profil[u'cont_country'] = cont.find(u'country').text self.dico_profil[u'cont_phone'] = cont.find(u'tel').text # second contact (responsable, etc.) resp = contacts.find(u'second_contact') self.dico_profil[u'resp_name'] = resp.find(u'name').text self.dico_profil[u'resp_orga'] = resp.find(u'org').text self.dico_profil[u'resp_mail'] = resp.find(u'mail').text self.dico_profil[u'resp_role'] = resp.find(u'role').text self.dico_profil[u'resp_func'] = resp.find(u'func')[0].text self.dico_profil[u'resp_street'] = resp.find(u'street').text self.dico_profil[u'resp_city'] = resp.find(u'city').text self.dico_profil[u'resp_cp'] = resp.find(u'cp').text self.dico_profil[u'resp_country'] = resp.find(u'country').text self.dico_profil[u'resp_phone'] = resp.find(u'tel').text # End of function return self.dico_profil def recup_help(self, lang): """ get the help texts """ # specific path to xml file path_help = 'locale/%s/help_%s.xml' % (lang, lang) # reading and parsing the xml with open(path_help, 'r') as source: xml = ET.parse(source) # xml cursor for tooltip in xml.findall('tooltip'): idu = tooltip.find('id').text ref = tooltip.find('ref').text txt = tooltip.find('txt').text img = tooltip.find('image').text doc = tooltip.find('doc').text # fillfulling the INSPIRE dictionary self.dico_help[int(idu)] = ref, txt, img, doc # End of function return self.dico_help def process(self): u""" launch the different processes """ # display the main tab self.nb.select(0) # check option selected: process or create a new profile if self.ddl_profil.get() == self.blabla.get('tab1_new'): # launching the profile form self.logger.info('Creation of a new profile') tr_profile = threading.Thread(target=NewProfile, args=(self.blabla, self.ddl_lang.get(), self.dico_help, self.li_pro)) tr_profile.daemon = True tr_profile.run() # NewProfile(self.blabla, self.ddl_lang.get(), self.li_pro) self.li_profiles(self.ddl_lang.get()) # updating the dropdow list self.ddl_profil['values'] = self.li_pro return # check if the target folder has been selected if self.target.get() == "": info(title=self.blabla.get('info_blanktarget1'), message=self.blabla.get('info_blanktarget2')) return # check if a profile has been selected if self.ddl_profil.get() == "": info(title=self.blabla.get('info_blankprofile1'), message=self.blabla.get('info_blankprofile2')) return # disabling others GUI parts self.tab_globals.focus_force() self.alter_state(self.FrPath, DISABLED) # check if there are some layers into the folder structure if len(self.li_shp) + len(self.li_tab) == 0: self.logger.warning("No geofiles found in the folder structure") self.status.set(self.blabla.get('log_nodata')) return # specific variables dest = path.join(self.target.get(), 'metadator') if not path.isdir(dest): # test if folder already exists mkdir(dest, 0777) # if not, we create it # getting profile informations self.recup_profil(self.ddl_lang.get()) # saving options in a separated thread tr_options = threading.Thread(target=self.save_settings) tr_options.daemon = True tr_options.start() self.logger.info('Current options saved') # saving recurring fiels in a separated thread tr_rekurs = threading.Thread(target=self.saveas_rekurs, args=(self.ddl_lang.get(), )) tr_rekurs.daemon = True tr_rekurs.start() # configuring the progression bar self.prog_layers["maximum"] = len(self.li_shp) + len(self.li_tab) self.prog_layers["value"] # Processing the shapefiles self.logger.info('\tStart processing the files') for shp in self.li_shp: """ looping on shapefiles list """ self.logger.info('Processing: %s' % path.basename(shp)) self.status.set(path.basename(shp)) # reset recipient data self.dico_layer.clear() self.dico_fields.clear() # getting separated process threads Read_SHP(shp, self.dico_layer, self.dico_fields, 'shape', self.blabla) # checking layer error if self.dico_layer.get('error'): # increment the progress bar self.prog_layers["value"] = self.prog_layers["value"] + 1 self.update() self.logger.warning('This shape has an issue: %s' % shp) continue # getting fields statistics only if needed if self.def_doc.get() == 1 or self.def_xls.get() == 1 or self.def_odt.get() == 1: StatsFields(shp, self.dico_fields, self.dico_rekur, self.blabla) # export according to options selected if self.def_doc.get() == 1: ExportToHTML(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) html_path = path.join(dest, "{0}_MD.html".format(self.dico_layer['name'][:-4])) ExportToDocX(html_path, dest) if self.def_xls.get() == 1: ExportToXLS(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) if self.def_xml.get() == 1: ExportToXML(dest, self.dico_layer, self.dico_profil, '', self.blabla, 1, 0) if self.def_odt.get() == 1: ExportToODT(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) # increment the progress bar self.prog_layers["value"] = self.prog_layers["value"] + 1 self.update() # Processing the MapInfo tables for tab in self.li_tab: """ looping on MapInfo tables list """ self.logger.info('Processing: %s' % path.basename(tab)) self.status.set(path.basename(tab)) # reset recipient data self.dico_layer.clear() self.dico_fields.clear() # getting the informations Read_TAB(tab, self.dico_layer, self.dico_fields, 'table', self.blabla) # checking layer error if self.dico_layer.get('error'): self.logger.warning('This MapInfo table has an issue: %s' % tab) # increment the progress bar self.prog_layers["value"] = self.prog_layers["value"] +1 self.update() continue # getting fields statistics only if needed if self.def_doc.get() == 1 \ or self.def_xls.get() == 1 \ or self.def_odt.get() == 1: StatsFields(tab, self.dico_fields, self.dico_rekur, self.blabla) # export according to options selected if self.def_doc.get() == 1: ExportToHTML(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) html_path = path.join(dest, "{0}_MD.html".format(self.dico_layer['name'][:-4])) ExportToDocX(html_path, dest) if self.def_xls.get() == 1: ExportToXLS(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) if self.def_xml.get() == 1: ExportToXML(dest, self.dico_layer, self.dico_profil, '', self.blabla, 1, 0) if self.def_odt.get() == 1: ExportToODT(dest, self.dico_layer, self.dico_fields, self.dico_profil, self.dico_rekur, self.blabla) # increment the progress bar self.prog_layers["value"] = self.prog_layers["value"] + 1 self.update() # Word catalog export if self.def_doc.get() == 1 and self.def_cat.get() == 1: self.status.set(self.blabla.get('info_cat')) self.update() DocxMerger(dest, '00_Metadator_Catalog', 'metadator_') else: pass # final message # msg = self.blabla.get('info_end2') + self.blabla.get('info_end3') # info(title=self.blabla.get('info_end'), message=msg) # opening the destination folder self.open_dir_file(dest) # cleaning up logging.info('Hurray! It worked! All seem to have been fine!') self.destroy() # end of function return def open_dir_file(self, target): """ Open a file or a directory in the explorer of the operating system http://sametmax.com/ouvrir-un-fichier-avec-le-bon-programme-en-python """ # check if the file or the directory exists if not path.exists(target): raise IOError('No such file: {0}'.format(target)) # check the read permission if not access(target, R_OK): raise IOError('Cannot access file: {0}'.format(target)) # open the directory or the file according to the os if opersys == 'win32': # Windows proc = startfile(target) elif opersys.startswith('linux'): # Linux: proc = subprocess.Popen(['xdg-open', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif opersys == 'darwin': # Mac: proc = subprocess.Popen(['open', '--', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: raise NotImplementedError( "Your `%s` isn't a supported operating system`." % opersys) # end of function return proc
def __init__(self, parent, txt=dict(), switcher=None): """Instanciating the output workbook.""" self.parent = parent Frame.__init__(self) # subframes self.FrOptProxy = Frame(self, name='settings_proxy') self.FrOptIsogeo = Frame(self, name='settings_isogeo') # options values self.opt_proxy = IntVar(self) # proxy option self.opt_isogeo = IntVar(self) # Isogeo option # Options form widgets caz_prox = Checkbutton(self, text=u'Proxy', variable=self.opt_proxy, command=lambda: switcher(self.opt_proxy, self.FrOptProxy)) caz_isogeo = Checkbutton(self, text=u'Isogeo', variable=self.opt_isogeo, command=lambda: switcher(self.opt_isogeo, self.FrOptIsogeo)) # positionning caz_prox.grid(row=0, column=0, sticky="NSWE", padx=2, pady=2) self.FrOptProxy.grid(row=0, column=1, columnspan=8, sticky="NSWE", padx=2, pady=2, rowspan=3) caz_isogeo.grid(row=3, column=0, sticky="NSWE", padx=2, pady=2) self.FrOptIsogeo.grid(row=3, column=1, columnspan=8, sticky="NSWE", padx=2, pady=2, rowspan=4) # ------------------------------------------------------------------------ # proxy specific variables self.opt_ntlm = IntVar(self.FrOptProxy, 0) # proxy NTLM protocol option self.prox_server = StringVar(self.FrOptProxy, 'proxy.server.com') self.prox_port = IntVar(self.FrOptProxy, 80) self.prox_user = StringVar(self.FrOptProxy, 'proxy_user') self.prox_pswd = StringVar(self.FrOptProxy, '****') # widgets self.prox_ent_H = Entry(self.FrOptProxy, textvariable=self.prox_server) self.prox_ent_P = Entry(self.FrOptProxy, textvariable=self.prox_port) self.prox_ent_M = Entry(self.FrOptProxy, textvariable=self.prox_pswd, show='*') self.prox_lb_H = Label(self.FrOptProxy, text=txt.get('gui_prox_server', "Host")) self.prox_lb_P = Label(self.FrOptProxy, text=txt.get('gui_port', "Port")) caz_ntlm = Checkbutton(self.FrOptProxy, text=u'NTLM', variable=self.opt_ntlm) self.prox_lb_M = Label(self.FrOptProxy, text=txt.get('gui_mdp', "Password")) # proxy widgets position self.prox_lb_H.grid(row=1, column=0, sticky="NSEW", padx=2, pady=2) self.prox_ent_H.grid(row=1, column=1, columnspan=2, sticky="NSEW", padx=2, pady=2) self.prox_lb_P.grid(row=1, column=2, sticky="NSEW", padx=2, pady=2) self.prox_ent_P.grid(row=1, column=3, columnspan=2, sticky="NSEW", padx=2, pady=2) caz_ntlm.grid(row=2, column=0, sticky="NSEW", padx=2, pady=2) self.prox_lb_M.grid(row=2, column=1, sticky="NSEW", padx=2, pady=2) self.prox_ent_M.grid(row=2, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2) # ------------------------------------------------------------------------ # Isogeo application variables self.isog_app_id = StringVar(self.FrOptIsogeo, 'application_id') self.isog_app_tk = StringVar(self.FrOptIsogeo, 'secret') # widgets isog_ent_id = Entry(self.FrOptIsogeo, textvariable=self.isog_app_id) isog_ent_tk = Entry(self.FrOptIsogeo, textvariable=self.isog_app_tk) isog_lb_id = Label(self.FrOptIsogeo, text="Application ID") isog_lb_tk = Label(self.FrOptIsogeo, text="Application secret") # Isogeo widgets position isog_lb_id.grid(row=1, column=1, sticky="NSEW", padx=2, pady=2) isog_ent_id.grid(row=1, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2) isog_lb_tk.grid(row=2, column=1, sticky="NSEW", padx=2, pady=2) isog_ent_tk.grid(row=2, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2)
class TabFiles(Frame): def __init__(self, parent, txt=dict(), path_browser=None, path_var=""): """Instanciating the output workbook.""" self.p = parent self.txt = txt Frame.__init__(self) # -- VARIABLES ------------------------------------------------------- self.target_path = StringVar() # formats / type: vectors self.li_vectors_formats = (".shp", ".tab", ".kml", ".gml", ".geojson" ) # vectors handled self.li_shp = [] # list for shapefiles path self.li_tab = [] # list for MapInfo tables path self.li_kml = [] # list for KML path self.li_gml = [] # list for GML path self.li_geoj = [] # list for GeoJSON paths self.li_gxt = [] # list for GXT paths self.li_vectors = [] # list for all vectors # formats / type: rasters self.li_raster = [] # list for rasters paths self.li_raster_formats = (".ecw", ".tif", ".jp2") # raster handled # formats / type: file databases self.li_fdb = [] # list for all files databases self.li_egdb = [] # list for Esri File Geodatabases self.li_spadb = [] # list for Spatialite Geodatabases # formats / type: CAO/DAO self.li_cdao = [] # list for all CAO/DAO files self.li_dxf = [] # list for AutoCAD DXF paths self.li_dwg = [] # list for AutoCAD DWG paths self.li_dgn = [] # list for MicroStation DGN paths # formats / type: maps documents self.li_mapdocs = [] # list for all map & documents self.li_pdf = [] # list for GeoPDF path self.li_lyr = [] # list for LYR path self.li_mxd = [] # list for MXD path self.li_qgs = [] # list for QGS path # -- Source path ----------------------------------------------------- self.FrPath = Labelframe(self, name='files', text=txt.get('gui_fr1', "Path")) # target folder self.lb_target = Label(self.FrPath, text=txt.get('gui_path')) self.ent_target = Entry(master=self.FrPath, width=35, textvariable=self.target_path) self.btn_browse = Button(self.FrPath, text=u"\U0001F3AF " + txt.get('gui_choix', "Browse"), command=lambda: self.get_target_path(r"."), takefocus=True) self.btn_browse.focus_force() # widgets placement self.lb_target.grid(row=1, column=1, columnspan=1, sticky="NSWE", padx=2, pady=2) self.ent_target.grid(row=1, column=2, columnspan=1, sticky="NSWE", padx=2, pady=2) self.btn_browse.grid(row=1, column=3, sticky="NSE", padx=2, pady=2) # -- Format filters -------------------------------------------------- self.FrFilters = Labelframe(self, name='filters', text=txt.get('gui_fr3', "Filters")) # formats options self.opt_shp = IntVar(self.FrFilters) # able/disable shapefiles self.opt_tab = IntVar(self.FrFilters) # able/disable MapInfo tables self.opt_kml = IntVar(self.FrFilters) # able/disable KML self.opt_gml = IntVar(self.FrFilters) # able/disable GML self.opt_geoj = IntVar(self.FrFilters) # able/disable GeoJSON self.opt_gxt = IntVar(self.FrFilters) # able/disable GXT self.opt_egdb = IntVar(self.FrFilters) # able/disable Esri FileGDB self.opt_spadb = IntVar(self.FrFilters) # able/disable Spatalite DB self.opt_rast = IntVar(self.FrFilters) # able/disable rasters self.opt_cdao = IntVar(self.FrFilters) # able/disable CAO/DAO files self.opt_pdf = IntVar(self.FrFilters) # able/disable Geospatial PDF self.opt_lyr = IntVar(self.FrFilters) # able/disable Geospatial Lyr self.opt_mxd = IntVar(self.FrFilters) # able/disable Geospatial MXD self.opt_qgs = IntVar(self.FrFilters) # able/disable Geospatial QGS # format choosen: check buttons caz_shp = Checkbutton(self.FrFilters, text=u'.shp', variable=self.opt_shp) caz_tab = Checkbutton(self.FrFilters, text=u'.tab', variable=self.opt_tab) caz_kml = Checkbutton(self.FrFilters, text=u'.kml', variable=self.opt_kml) caz_gml = Checkbutton(self.FrFilters, text=u'.gml', variable=self.opt_gml) caz_geoj = Checkbutton(self.FrFilters, text=u'.geojson', variable=self.opt_geoj) caz_gxt = Checkbutton(self.FrFilters, text=u'.gxt', variable=self.opt_gxt) caz_egdb = Checkbutton(self.FrFilters, text=u'Esri FileGDB', variable=self.opt_egdb) caz_spadb = Checkbutton(self.FrFilters, text=u'Spatialite', variable=self.opt_spadb) caz_rast = Checkbutton(self.FrFilters, text=u'rasters ({0})'.format(', '.join( self.li_raster_formats)), variable=self.opt_rast) caz_cdao = Checkbutton(self.FrFilters, text=u'CAO/DAO', variable=self.opt_cdao) caz_pdf = Checkbutton(self.FrFilters, text=u'Geospatial PDF', variable=self.opt_pdf) self.caz_lyr = Checkbutton(self.FrFilters, text=u'.lyr', variable=self.opt_lyr) self.caz_mxd = Checkbutton(self.FrFilters, text=u'.mxd', variable=self.opt_mxd) caz_qgs = Checkbutton(self.FrFilters, text=u'.qgs', variable=self.opt_qgs) # widgets placement caz_shp.grid(row=1, column=0, sticky="NSWE", padx=2, pady=2) caz_tab.grid(row=1, column=1, sticky="NSWE", padx=2, pady=2) caz_kml.grid(row=1, column=2, sticky="NSWE", padx=2, pady=2) caz_gml.grid(row=1, column=3, sticky="NSWE", padx=2, pady=2) caz_geoj.grid(row=1, column=4, sticky="NSWE", padx=2, pady=2) caz_gxt.grid(row=1, column=7, sticky="NSWE", padx=2, pady=2) caz_pdf.grid(row=1, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_rast.grid(row=2, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_egdb.grid(row=2, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_cdao.grid(row=2, column=4, columnspan=1, sticky="NSWE", padx=2, pady=2) caz_spadb.grid(row=2, column=5, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_lyr.grid(row=3, column=0, columnspan=2, sticky="NSWE", padx=2, pady=2) self.caz_mxd.grid(row=3, column=1, columnspan=2, sticky="NSWE", padx=2, pady=2) caz_qgs.grid(row=3, column=2, columnspan=2, sticky="NSWE", padx=2, pady=2) # frames placement self.FrPath.grid(row=3, column=1, padx=2, pady=2, sticky="NSWE") self.FrFilters.grid(row=4, column=1, padx=2, pady=2, sticky="NSWE") def get_target_path(self, def_rep): """Browse and insert the path of target folder.""" print(self.target_path.get()) foldername = askdirectory(parent=self.p, initialdir=def_rep, mustexist=True, title="") # deactivate Go button # self.val.config(state=DISABLED) # check if a folder has been choosen if foldername: try: self.tab_files.ent_target.delete(0, END) self.tab_files.ent_target.insert(0, foldername) except Exception as e: logger.debug(e) showinfo(title=self.txt.get('nofolder'), message=self.txt.get('nofolder')) return else: pass # set the default output file self.output.delete(0, END) self.output.insert( 0, "DicoGIS_{0}_{1}.xlsx".format(path.split(self.target_path.get()), today)) # count geofiles in a separated thread proc = threading.Thread(target=self.ligeofiles, args=(foldername, )) proc.daemon = True proc.start() # end of function return foldername
class JobParameters(Toplevel): def __init__(self, parent=None, **kwargs): Toplevel.__init__(self, parent) self.title('Job Parameters') self.parent = parent self.main_frame = Frame(self) self.input_directory_gui = DirectorySelector(self.main_frame, 'Input Directory:') self.output_directory_gui = DirectorySelector(self.main_frame, 'Output Directory:', get_default=lambda: self.input_directory_gui.get_directory() + '/output/') self.input_directory_gui.set_notify(self.notify) self.beginning_year = kwargs['beginning_year'] if 'beginning_year' in kwargs else 1950 self.ending_year = kwargs['ending_year'] if 'ending_year' in kwargs else 2100 self.beginning_year_selector = YearSelector(self.main_frame, text="Beginning Year:", min_value=self.beginning_year, max_value=self.ending_year) self.ending_year_selector = YearSelector(self.main_frame, text="Ending Year:", min_value=self.beginning_year, max_value=self.ending_year) self.one_decade_range_var = IntVar() self.one_decade_range = Checkbutton(self.main_frame, text='Calculate 10 Year Range', variable=self.one_decade_range_var, command=self.on_change) self.two_decade_range_var = IntVar() self.two_decade_range = Checkbutton(self.main_frame, text='Calculate 20 Year Range', variable=self.two_decade_range_var, command=self.on_change) self.custom_range_var = IntVar() self.custom_range = Checkbutton(self.main_frame, text='Calculate Custom Year Range', variable=self.custom_range_var, command=self.on_change) self.custom_range_val = StringVar() self.custom_range_input = Spinbox(self.main_frame, from_=30, to=100, textvariable=self.custom_range_val, command=self.on_change, width=5) # Initialize widget values self.beginning_year_selector.set_value(self.beginning_year) self.beginning_year_selector.set_args(check_other_func=self.ending_year_selector.get_less_than) self.ending_year_selector.set_value(self.ending_year) self.ending_year_selector.set_args(check_other_func=self.beginning_year_selector.get_greater_than) self.one_decade_range_var.set(1) self.two_decade_range_var.set(1) self.custom_range_var.set(0) self.custom_range_input.config(state=Tkinter.DISABLED) self.button_frame = Frame(self.main_frame) self.ok_button = Button(self.button_frame, text='OK', command=self.on_submit) self.cancel_button = Button(self.button_frame, text='Cancel', command=self.on_close) self.job_id = kwargs['job_id'] if 'job_id' in kwargs else None self.entry = kwargs['entry'] if 'entry' in kwargs else None self.grab_set() self.resizable(width=False, height=False) def notify(self): self.output_directory_gui.notify() self.lift() def set_grid(self): # Layout child widgets self.main_frame.grid() self.input_directory_gui.set_grid(row=0, padx=6) self.output_directory_gui.set_grid(row=1, padx=6) self.beginning_year_selector.set_grid(row=2, padx=6) self.ending_year_selector.set_grid(row=3, padx=6) self.one_decade_range.grid(row=4, column=1, sticky='w', padx=6) self.two_decade_range.grid(row=5, column=1, sticky='w', padx=6) self.custom_range.grid(row=6, column=1, sticky='w', padx=6) self.custom_range_input.grid(row=6, column=2, sticky='w', padx=6) self.button_frame.grid(row=7, columnspan=3, sticky='nsew') self.ok_button.pack(side=Tkinter.RIGHT) self.cancel_button.pack(side=Tkinter.RIGHT) #self.ok_button.grid(row=7, column=1, pady=2) #self.cancel_button.grid(row=7, column=2, pady=2) def on_change(self): is_custom_range_checked = self.custom_range_var.get() == 1 if is_custom_range_checked: self.custom_range_input.config(state=Tkinter.NORMAL) else: self.custom_range_input.config(state=Tkinter.DISABLED) def on_submit(self): if self.input_directory_gui.get_directory() == '' or self.output_directory_gui.get_directory() == '': self.on_close() return # The job parameters are extracted from the GUI here and passed to the processing thread to run the requisite job. job = dict() job['job_id'] = self.job_id job['delimiter'] = '.' job['individual_files'] = False job['input_directory'] = self.input_directory_gui.get_directory() job['output_directory'] = self.output_directory_gui.get_directory() job['start'] = self.beginning_year_selector.get_value() job['end'] = self.ending_year_selector.get_value() job['calculate_one_decade'] = self.one_decade_range_var.get() == 1 job['calculate_two_decade'] = self.two_decade_range_var.get() == 1 job['calculate_custom_range'] = self.custom_range_var.get() == 1 job['custom_range'] = int(self.custom_range_val.get()) job['log'] = True if self.entry != None: self.entry.add_job(job) self.on_close() def on_close(self): if self.parent != None: self.parent.focus_set() self.withdraw() self.destroy() def on_focus(self): self.focus_force()
class SpineRegGui(Frame): def __init__(self, parent, param_filename=None): Frame.__init__(self, parent) self.title = 'SpineDTI' self.log = os.path.join(os.path.abspath('.'), 'log') self.parent = parent self.parameter_values = {} self.param = parameter.Parameter() self.initUI() self.init_variable() self.update_param_from_text() if param_filename is not None: self.read_param(param_filename) def init_variable(self): #self.txt_multiband.insert(0, '2') self.reset_entry(self.spin_multiband, 2) #self.txt_nitr.insert(0, '3') self.reset_entry(self.spin_nitr, 3) self.chk_nosearch.invoke() self.reset_entry(self.txt_b0_threshold, 90) self.reset_entry(self.txt_high_b_threshold, 400) dirname = os.path.dirname(os.path.realpath(__file__)) self.reset_entry(self.txt_topup_config, os.path.join(dirname, 'b02b0_ON_1_3mm.cnf')) self.reset_entry(self.txt_reg_config, os.path.join(dirname, 'xytrans.sch')) self.reset_entry(self.txt_topup_app, 'topup_2d') self.reset_entry(self.txt_eddy_app, 'eddy') if self.txt_working.get() == '': self.reset_entry(self.txt_working, os.path.abspath('.'), force=True) def update_parameter(self): if self.parameter_values.has_key('subject'): self.reset_entry(self.txt_subject, self.parameter_values['subject']) if self.parameter_values.has_key('dwi'): self.reset_entry(self.txt_dwi, self.parameter_values['dwi']) self.reset_entry( self.txt_bval, filename_wo_ext(self.parameter_values['dwi']) + '.bval') self.reset_entry( self.txt_bvec, filename_wo_ext(self.parameter_values['dwi']) + '.bvec') if self.parameter_values.has_key('b0'): self.reset_entry(self.txt_b0, self.parameter_values['b0']) if self.parameter_values.has_key('working'): self.reset_entry(self.txt_working, self.parameter_values['working'], force=True) def reset_entry(self, entry, text, force=False): entry.delete(0, len(entry.get())) dirname = self.txt_working.get() len_dirname = len(dirname) # print dirname, text if (not force) and type(text) == type( '') and len_dirname > 1 and dirname == text[:len_dirname]: entry.insert(0, text[len_dirname:].strip(os.path.sep)) else: entry.insert(0, text) def filenameDialog_text(self, text): fl = tkFileDialog.askopenfilename() if fl != '': self.reset_entry(text, fl) def dirnameDialog_text(self, text): fl = tkFileDialog.askdirectory(initialdir=text.get()) if fl != '': self.reset_entry(text, fl) def prefix(self): if self.txt_subject.get() == '': return '' else: return self.txt_subject.get() + '_' def update_param_from_text(self): self.param.subject = self.txt_subject.get() self.param.working_dir = self.txt_working.get() self.param.fn_bval = self.txt_bval.get() self.param.fn_bvec = self.txt_bvec.get() self.param.b0_threshold = self.txt_b0_threshold.get() #self.param.b0_threshold = self.txt_b0_threshold.get() #FIXME self.param.topup_app = self.txt_topup_app.get() self.param.topup_config = self.txt_topup_config.get() self.param.eddy_app = self.txt_eddy_app.get() self.param.fn_b0 = self.txt_b0.get() self.param.fn_b0_mask = self.txt_b0mask.get() self.param.fn_dwi = self.txt_dwi.get() self.param.fn_dwi_mask = self.txt_dwi_mask.get() self.param.fn_dwi_eddy_out = self.txt_output_eddy.get() self.param.multiband = self.spin_multiband.get() self.param.niter = self.spin_nitr.get() self.param.nosearch = self.nosearch.get() self.param.noresample = self.noresample.get() self.param.schedule = self.txt_reg_config.get() self.param.fn_dwi_eddy = self.txt_dwi_eddy.get() self.param.fn_reg_mask = self.txt_reg_mask.get() self.param.fn_reg_outlier = self.txt_reg_outlier.get() self.param.fn_reg_slices = self.txt_reg_slices.get() self.param.fn_reg_out = self.txt_output_reg.get() self.param.fn_dti = self.txt_dti.get() self.param.fn_dwi_dti = self.txt_dwi_dti.get() self.param.fn_dwi_dti_mask = self.txt_md_mask.get() self.param.fn_dwi_dti_outlier = self.txt_dti_outlier.get() self.param.fn_dti_value = self.txt_dti_value.get() self.param.fn_dti_value_roi = self.txt_dti_roi.get() self.param.fn_dti_value_out = self.txt_output_dti_value.get() self.param.set_variable_types() def update_text_from_param(self): self.reset_entry(self.txt_subject, self.param.subject) self.reset_entry(self.txt_working, self.param.working_dir, force=True) self.reset_entry(self.txt_bval, self.param.fn_bval) self.reset_entry(self.txt_bvec, self.param.fn_bvec) self.reset_entry(self.txt_b0_threshold, self.param.b0_threshold) self.reset_entry(self.txt_topup_app, self.param.topup_app) self.reset_entry(self.txt_topup_config, self.param.topup_config) self.reset_entry(self.txt_eddy_app, self.param.eddy_app) self.reset_entry(self.txt_b0, self.param.fn_b0) self.reset_entry(self.txt_b0mask, self.param.fn_b0_mask) self.reset_entry(self.txt_dwi, self.param.fn_dwi) self.reset_entry(self.txt_dwi_mask, self.param.fn_dwi_mask) self.reset_entry(self.txt_output_eddy, self.param.fn_dwi_eddy_out) self.reset_entry(self.spin_multiband, self.param.multiband) self.reset_entry(self.spin_nitr, self.param.niter) self.nosearch.set(self.param.nosearch) self.noresample.set(self.param.noresample) self.reset_entry(self.txt_reg_config, self.param.schedule) self.reset_entry(self.txt_dwi_eddy, self.param.fn_dwi_eddy) self.reset_entry(self.txt_reg_mask, self.param.fn_reg_mask) self.reset_entry(self.txt_reg_outlier, self.param.fn_reg_outlier) self.reset_entry(self.txt_reg_slices, self.param.fn_reg_slices) self.reset_entry(self.txt_output_reg, self.param.fn_reg_out) self.reset_entry(self.txt_dwi_dti, self.param.fn_dwi_dti) self.reset_entry(self.txt_dti, self.param.fn_dti) self.reset_entry(self.txt_md_mask, self.param.fn_dwi_dti_mask) self.reset_entry(self.txt_dti_outlier, self.param.fn_dwi_dti_outlier) self.reset_entry(self.txt_dti_value, self.param.fn_dti_value) self.reset_entry(self.txt_dti_roi, self.param.fn_dti_value_roi) self.reset_entry(self.txt_output_dti_value, self.param.fn_dti_value_out) def read_param(self, filename=None): if filename is None or not os.path.isfile(filename): fn = tkFileDialog.askopenfilename() else: fn = filename if os.path.isfile(fn): print 'Reading %s' % fn self.param.read(fn) self.update_text_from_param() self.reset_entry(self.txt_param, fn) else: sys.stderr.write('File not exist: %s\n' % fn) def save_param(self): self.update_param_from_text() if self.txt_param.get() != '': if os.path.dirname(self.txt_param.get()) == '': filename = tkFileDialog.asksaveasfilename( initialdir=self.txt_working.get(), initialfile=os.path.basename(self.txt_param.get())) else: filename = tkFileDialog.asksaveasfilename( initialdir=os.path.dirname(self.txt_param.get()), initialfile=os.path.basename(self.txt_param.get())) else: filename = tkFileDialog.asksaveasfilename( initialdir=self.txt_working.get()) if filename != '': self.param.save(filename) self.reset_entry(self.txt_param, filename) def initUI(self): self.parent.title(self.title) self.nosearch = BooleanVar(self) self.noresample = BooleanVar(self) i = 0 #frame_top = Frame(self) #frame_top.grid(row=i, column=0, columnspan=6, sticky=EW) #Label(frame_top, text='topframe').grid(row=0, column=0, sticky=EW) #Label(frame_top, text='topframe').grid(row=0, column=1, sticky=EW) #Label(frame_top, text='topframe').grid(row=1, column=0, sticky=EW) #Label(frame_top, text='topframe').grid(row=1, column=1, sticky=EW) #Entry(frame_top, text='topframe').grid(row=0, column=0, sticky=EW) #Entry(frame_top, text='topframe').grid(row=0, column=1, sticky=EW) #Entry(frame_top, text='topframe').grid(row=1, column=0, sticky=EW) #Entry(frame_top, text='topframe').grid(row=1, column=1, sticky=EW) #frame_top.grid_columnconfigure(0, weight=1) #frame_top.grid_columnconfigure(1, weight=1) dddWidth = 4 labelWidth = 10 i += 1 Label(self, text='Working dir', width=labelWidth).grid(row=i, column=0) self.txt_working = Entry(self) self.txt_working.grid(row=i, column=1, sticky=EW) btn_working = Button( self, text='...', width=dddWidth, command=lambda: self.dirnameDialog_text(self.txt_working)) btn_working.grid(row=i, column=2, sticky=W) i += 1 Label(self, text='Parameters', width=labelWidth).grid(row=i, column=0) self.txt_param = Entry(self) self.txt_param.grid(row=i, column=1, sticky=EW) btn_param_read = Button(self, text='Read', command=self.read_param) btn_param_read.grid(row=i, column=2) btn_param_save = Button(self, text='Save', command=self.save_param) btn_param_save.grid(row=i, column=3) i += 1 frm_prepa = Frame(self) ii = 0 Label(frm_prepa, text='Subject', width=labelWidth).grid(row=ii, column=0) self.txt_subject = Entry(frm_prepa) self.txt_subject.grid(row=ii, column=1, sticky=EW) btn_prepa = Button(frm_prepa, text='Prepare DWIs', command=self.run_prepare) btn_prepa.grid(row=ii, column=3) #btn_update = Button(frm_prepa, text='Update filenames', command=self.update_parameter); btn_update.grid(row=ii, column=4) btn_update = Button(frm_prepa, text='Update filenames', command=self.update_text_from_param) btn_update.grid(row=ii, column=4) ii += 1 Label(frm_prepa, text='bval', width=labelWidth).grid(row=ii, column=0) self.txt_bval = Entry(frm_prepa) self.txt_bval.grid(row=ii, column=1, sticky=EW) btn_bval = Button( frm_prepa, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_bval)) btn_bval.grid(row=ii, column=2, sticky=W) Label(frm_prepa, text='b0 threshold').grid(row=ii, column=3, sticky=E) self.txt_b0_threshold = Entry(frm_prepa, width=10) self.txt_b0_threshold.grid(row=ii, column=4) ii += 1 Label(frm_prepa, text='bvec', width=labelWidth).grid(row=ii, column=0) self.txt_bvec = Entry(frm_prepa) self.txt_bvec.grid(row=ii, column=1, sticky=EW) btn_bvec = Button( frm_prepa, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_bvec)) btn_bvec.grid(row=ii, column=2, sticky=W) Label(frm_prepa, text='high b threshold').grid(row=ii, column=3, sticky=E) self.txt_high_b_threshold = Entry(frm_prepa, width=10) self.txt_high_b_threshold.grid(row=ii, column=4) frm_prepa.grid_columnconfigure(1, weight=1) frm_prepa.grid(row=i, rowspan=ii + 1, column=0, columnspan=6, sticky=NSEW) ii += 1 i += ii # TOPUP/EDDY or Rigid registration i += 1 Label(self, text=' TOPUP/EDDY or Rigid registration').grid(row=i, column=0, columnspan=2, sticky=W) i += 1 frm_eddy = Frame(self) width = 10 ii = 0 jj = 0 Label(frm_eddy, text='TOPUP', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) jj += 1 self.txt_topup_app = Entry(frm_eddy, width=width) self.txt_topup_app.grid(row=ii, column=jj) jj += 1 Label(frm_eddy, text='Configure', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) jj += 1 self.txt_topup_config = Entry(frm_eddy) self.txt_topup_config.grid(row=ii, column=jj, sticky=EW) jj += 1 btn_topup_config = Button( frm_eddy, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_topup_config)) btn_topup_config.grid(row=ii, column=jj, sticky=W) jj += 1 Label(frm_eddy, text='EDDY', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) jj += 1 self.txt_eddy_app = Entry(frm_eddy, width=width) self.txt_eddy_app.grid(row=ii, column=jj) frm_eddy.grid(row=i, rowspan=ii + 1, column=0, columnspan=6, sticky=NSEW) frm_eddy.grid_columnconfigure(3, weight=1) i += ii i += 1 Label(self, text='B0', width=labelWidth).grid(row=i, column=0) self.txt_b0 = Entry(self) self.txt_b0.grid(row=i, column=1, sticky=EW) btn_b0 = Button(self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_b0)) btn_b0.grid(row=i, column=2, sticky=W) btn_topup = Button(self, text='TOPUP', command=self.run_topup) btn_topup.grid(row=i, column=4, rowspan=2, sticky=NS) btn_rigid = Button(self, text='Rigid\nReg', command=self.run_eddy) btn_rigid.grid(row=i, column=5, rowspan=4, sticky=NS) i += 1 Label(self, text='B0 mask', width=labelWidth).grid(row=i, column=0) self.txt_b0mask = Entry(self) self.txt_b0mask.grid(row=i, column=1, sticky=EW) btn_b0mask = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_b0mask)) btn_b0mask.grid(row=i, column=2, sticky=W) btn_b0mask_make = Button( self, text='Make', command=lambda: self.make_mask( self.txt_b0.get(), mask4d=True, rtn=self.txt_b0mask)) btn_b0mask_make.grid(row=i, column=3) i += 1 Label(self, text='DWI', width=labelWidth).grid(row=i, column=0) self.txt_dwi = Entry(self) self.txt_dwi.grid(row=i, column=1, sticky=EW) btn_dwi_eddy = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dwi)) btn_dwi_eddy.grid(row=i, column=2, sticky=W) btn_eddy = Button(self, text='EDDY', command=self.run_eddy) btn_eddy.grid(row=i, column=4, rowspan=2, sticky=NS) i += 1 Label(self, text='DWI mask', width=labelWidth).grid(row=i, column=0) self.txt_dwi_mask = Entry(self) self.txt_dwi_mask.grid(row=i, column=1, sticky=EW) btn_dwi_mask = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dwi_mask)) btn_dwi_mask.grid(row=i, column=2, sticky=W) btn_dwi_mask_make = Button( self, text='Make', command=lambda: self.make_mask(self.txt_dwi.get(), rtn=self.txt_dwi_mask)) btn_dwi_mask_make.grid(row=i, column=3) i += 1 Label(self, text='Output', width=labelWidth).grid(row=i, column=0) self.txt_output_eddy = Entry(self) self.txt_output_eddy.grid(row=i, column=1, sticky=EW) btn_output_eddy = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_output_eddy)) btn_output_eddy.grid(row=i, column=2, sticky=W) btn_output_eddy_auto = Button(self, text='Auto', command=self.gen_eddy_outputname) btn_output_eddy_auto.grid(row=i, column=3) # 2D registration i += 1 Label(self, text=' 2D registration (X-Y translation)').grid(row=i, column=0, columnspan=2, sticky=W) i += 1 frm_param = Frame(self) width = 12 width_half = 6 ii = 0 jj = 0 Label(frm_param, text='Multi band', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) #jj += 1; self.txt_multiband = Entry(frm_param, width=width_half); self.txt_multiband.grid(row=ii, column=jj) jj += 1 self.spin_multiband = Spinbox(frm_param, from_=0, to=1000, increment=1, width=width_half) self.spin_multiband.grid(row=ii, column=jj) jj += 1 Label(frm_param, text='#iteration', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) #jj += 1; self.txt_nitr = Entry(frm_param, width=width_half); self.txt_nitr.grid(row=ii, column=jj) jj += 1 self.spin_nitr = Spinbox(frm_param, from_=0, to=1000, increment=1, width=width_half) self.spin_nitr.grid(row=ii, column=jj) jj += 1 Label(frm_param, text='', width=width, justify=RIGHT, anchor=E).grid(row=ii, column=jj, sticky=E) jj += 1 self.chk_nosearch = Checkbutton(frm_param, text='nosearch', variable=self.nosearch, width=width) self.chk_nosearch.grid(row=ii, column=jj) jj += 1 self.chk_noresample = Checkbutton(frm_param, text='noresample', variable=self.noresample, width=width) self.chk_noresample.grid(row=ii, column=jj) ii += 1 jj = 0 Label(frm_param, text='Schedule').grid(row=ii, column=jj, sticky=E) jj += 1 self.txt_reg_config = Entry(frm_param) self.txt_reg_config.grid(row=ii, column=jj, sticky=EW, columnspan=4) jj += 4 btn_reg_config = Button( frm_param, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_reg_config)) btn_reg_config.grid(row=ii, column=jj, sticky=W) frm_param.grid_columnconfigure(4, weight=1) frm_param.grid(row=i, rowspan=ii + 1, column=0, columnspan=6, sticky=NSEW) i += ii i += 1 Label(self, text='DWI', width=labelWidth).grid(row=i, column=0) self.txt_dwi_eddy = Entry(self) self.txt_dwi_eddy.grid(row=i, column=1, sticky=EW) btn_dwi_eddy = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dwi_eddy)) btn_dwi_eddy.grid(row=i, column=2, sticky=W) btn_dwi_eddy_copy = Button( self, text='Copy', command=lambda: self.reset_entry(self.txt_dwi_eddy, self.txt_output_eddy.get())) btn_dwi_eddy_copy.grid(row=i, column=3) btn_dwi_eddy = Button(self, text='Save\nParam', command=self.save_reg_param) btn_dwi_eddy.grid(row=i, column=4, rowspan=2, sticky=NSEW) btn_dwi_eddy = Button(self, text='XY-Reg', command=self.run_xy_reg) btn_dwi_eddy.grid(row=i, column=5, rowspan=2, sticky=NSEW) i += 1 Label(self, text='Mask', width=labelWidth).grid(row=i, column=0) self.txt_reg_mask = Entry(self) self.txt_reg_mask.grid(row=i, column=1, sticky=EW) btn_reg_mask = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_reg_mask)) btn_reg_mask.grid(row=i, column=2, sticky=W) btn_reg_mask_make = Button( self, text='Make', command=lambda: self.make_mask(self.txt_dwi_eddy.get(), rtn=self.txt_reg_mask)) btn_reg_mask_make.grid(row=i, column=3) i += 1 Label(self, text='Slices', width=labelWidth).grid(row=i, column=0) self.txt_reg_slices = Entry(self) self.txt_reg_slices.grid(row=i, column=1, sticky=EW) i += 1 Label(self, text='Outlier', width=labelWidth).grid(row=i, column=0) self.txt_reg_outlier = Entry(self) self.txt_reg_outlier.grid(row=i, column=1, sticky=EW) btn_reg_outlier = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_reg_outlier)) btn_reg_outlier.grid(row=i, column=2, sticky=W) btn_reg_outlier_calculate = Button(self, text='Calculate', command=self.run_xy_reg_outlier) btn_reg_outlier_calculate.grid(row=i, column=3) btn_reg_apply = Button(self, text='Applywarp', command=self.run_applywarp) btn_reg_apply.grid(row=i, column=4, columnspan=2, sticky=EW) i += 1 Label(self, text='Output', width=labelWidth).grid(row=i, column=0) self.txt_output_reg = Entry(self) self.txt_output_reg.grid(row=i, column=1, sticky=EW) btn_output_reg = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_output_reg)) btn_output_reg.grid(row=i, column=2, sticky=W) btn_output_reg_auto = Button(self, text='Auto', command=self.gen_reg_outputname) btn_output_reg_auto.grid(row=i, column=3) # DTI i += 1 Label(self, text=' DTI map with outlier rejection').grid(row=i, column=0, columnspan=2, sticky=W) i += 1 Label(self, text='DWI_reg', width=labelWidth).grid(row=i, column=0) self.txt_dwi_dti = Entry(self) self.txt_dwi_dti.grid(row=i, column=1, sticky=EW) btn_dwi_dti = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dwi_dti)) btn_dwi_dti.grid(row=i, column=2, sticky=W) btn_dwi_dti_copy = Button( self, text='Copy', command=lambda: self.reset_entry(self.txt_dwi_dti, self.txt_output_reg.get())) btn_dwi_dti_copy.grid(row=i, column=3) btn_dti_maps = Button(self, text='Generate DTI maps', command=self.run_generate_dti_maps) btn_dti_maps.grid(row=i, column=4, columnspan=2, sticky=EW) i += 1 Label(self, text='DTI', width=labelWidth).grid(row=i, column=0) self.txt_dti = Entry(self) self.txt_dti.grid(row=i, column=1, sticky=EW) btn_dti = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dti)) btn_dti.grid(row=i, column=2, sticky=W) btn_dti_auto = Button(self, text='Auto', command=self.gen_dti_name) btn_dti_auto.grid(row=i, column=3) btn_dti_outlier_calc = Button(self, text='Calculate Outlier', command=self.run_dti_outlier) btn_dti_outlier_calc.grid(row=i, column=4, columnspan=2, rowspan=2, sticky=NSEW) i += 1 Label(self, text='Mask', width=labelWidth).grid(row=i, column=0) self.txt_md_mask = Entry(self) self.txt_md_mask.grid(row=i, column=1, sticky=EW) btn_md_mask = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_md_mask)) btn_md_mask.grid(row=i, column=2, sticky=W) btn_md_mask_make = Button(self, text='Make', command=self.run_md_mask) btn_md_mask_make.grid(row=i, column=3) i += 1 Label(self, text='Outlier', width=labelWidth).grid(row=i, column=0) self.txt_dti_outlier = Entry(self) self.txt_dti_outlier.grid(row=i, column=1, sticky=EW) btn_dti_outlier = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dti_outlier)) btn_dti_outlier.grid(row=i, column=2, sticky=W) btn_dti_maps_itr = Button( self, text='Generate DTI maps', command=lambda: self.run_generate_dti_maps(outlier=True)) btn_dti_maps_itr.grid(row=i, column=4, columnspan=2, sticky=EW) #i += 1 #Label(self, text='DWI' , width=labelWidth).grid(row=i, column=0) #self.txt_dwi_dti_itr = Entry(self); self.txt_dwi_dti_itr.grid(row=i, column=1, sticky=EW) #btn_dwi_dti_itr = Button(self, text='...', width=dddWidth, command=lambda:self.filenameDialog_text(self.txt_dwi_dti_itr)) #btn_dwi_dti_itr.grid(row=i, column=2, sticky=W) #i += 1; Label(self, text='Output' , width=labelWidth).grid(row=i, column=0) #self.txt_output_dti = Entry(self); self.txt_output_dti.grid(row=i, column=1, sticky=EW) #btn_output_dti = Button(self, text='...', width=dddWidth, command=lambda:self.filenameDialog_text(self.txt_output_dti)) #btn_output_dti.grid(row=i, column=2, sticky=W) #btn_output_dti_auto = Button(self, text='Auto', command=self.gen_dti_outputname); btn_output_dti_auto.grid(row=i, column=3) # DTI Values i += 1 Label(self, text=' DTI values').grid(row=i, column=0, columnspan=2, sticky=W) i += 1 Label(self, text='DTI', width=labelWidth).grid(row=i, column=0) self.txt_dti_value = Entry(self) self.txt_dti_value.grid(row=i, column=1, sticky=EW) btn_dti_value = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dti_value)) btn_dti_value.grid(row=i, column=2, sticky=W) btn_dwi_dti_value_copy = Button( self, text='Copy', command=lambda: self.reset_entry(self.txt_dti_value, self.txt_dti.get())) btn_dwi_dti_value_copy.grid(row=i, column=3) btn_dti_value_get = Button(self, text='Get DTI\nValues', command=self.run_get_dti_values) btn_dti_value_get.grid(row=i, column=4, rowspan=2, columnspan=2, sticky=NSEW) i += 1 Label(self, text='ROI', width=labelWidth).grid(row=i, column=0) self.txt_dti_roi = Entry(self) self.txt_dti_roi.grid(row=i, column=1, sticky=EW) btn_dti_roi = Button( self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text(self.txt_dti_roi)) btn_dti_roi.grid(row=i, column=2, sticky=W) btn_dti_roi = Button(self, text='Make') btn_dti_roi.grid(row=i, column=3) i += 1 Label(self, text='Output', width=labelWidth).grid(row=i, column=0) self.txt_output_dti_value = Entry(self) self.txt_output_dti_value.grid(row=i, column=1, sticky=EW) btn_output_dti_value = Button(self, text='...', width=dddWidth, command=lambda: self.filenameDialog_text( self.txt_output_dti_value)) btn_output_dti_value.grid(row=i, column=2, sticky=W) btn_output_dti_value_auto = Button( self, text='Auto', command=self.gen_dti_value_outputname) btn_output_dti_value_auto.grid(row=i, column=3) self.grid_columnconfigure(1, weight=1) ni = i + 1 for i in range(ni): self.grid_rowconfigure(i, weight=1, minsize=20) self.pack(fill=BOTH, expand=True) def initUI_1(self): self.parent.title("Review") self.pack(fill=BOTH, expand=True) frame1 = Frame(self) frame1.pack(fill=X) lbl1 = Label(frame1, text="Title", width=6) lbl1.pack(side=LEFT, padx=5, pady=5) entry1 = Entry(frame1) entry1.pack(fill=X, padx=5, expand=True) frame2 = Frame(self) frame2.pack(fill=X) #frame2.pack(fill=BOTH, expand=True) lbl2 = Label(frame2, text="Author", width=6) lbl2.pack(side=LEFT, padx=5, pady=5) entry2 = Entry(frame2) entry2.pack(fill=X, padx=5, expand=True) frame3 = Frame(self) frame3.pack(fill=BOTH, expand=True) lbl3 = Label(frame3, text="Review", width=6) lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5) txt = Entry(frame3) txt.pack(fill=BOTH, pady=5, padx=5, expand=True) def onOpen(self): ftypes = [('Python files', '*.py'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) fl = dlg.show() if fl != '': #text = self.readFile(fl) print fl def gen_eddy_outputname(self): fn = self.txt_output_eddy.get() if fn == '' or '_rigid.nii.gz' in fn: fn = filename_wo_ext(self.txt_dwi.get()) + '_eddy_unwarped.nii.gz' else: fn = filename_wo_ext(self.txt_dwi.get()) + '_rigid.nii.gz' self.reset_entry(self.txt_output_eddy, fn) def gen_reg_outputname(self): fn = filename_wo_ext(self.txt_dwi_eddy.get()) + '_xenc.nii.gz' self.reset_entry(self.txt_output_reg, fn) #def gen_dti_outputname(self): # fn = filename_wo_ext(self.txt_output_reg.get()) + '_dti.nii.gz' # self.reset_entry(self.txt_output_dti, fn) def gen_dti_name(self): self.reset_entry(self.txt_dti, filename_wo_ext(self.txt_dwi_dti.get()) + '_dti') def gen_dti_value_outputname(self): fn = filename_wo_ext(self.txt_dti_value.get()) + '.csv' self.reset_entry(self.txt_output_dti_value, fn) def check_dependency(self, dependency): dirname = self.txt_working.get() for entry in dependency: if not os.path.isfile(os.path.join(dirname, entry.get())): sys.stderr.write('File not exist: %s\n' % entry.get()) return False return True def run_prepare(self): #prep = Tk() #app = prepare_dwi_gui.PrepareDWI(prep, subject=self.txt_subject.get(), output_dir=self.txt_working.get(), return_value=self.parameter_values, make_param=False) #prep.mainloop() self.prep_window = Toplevel(self.parent) self.prep_app = prepare_dwi_gui.PrepareDWI( self.prep_window, subject=self.txt_subject.get(), output_dir=self.txt_working.get(), return_value=self.parameter_values, obj_return_value=self, make_param=False) #app.mainloop() #self.update_parameter() #tkMessageBox.showinfo(self.title, 'Done: DWI preparation') def make_mask(self, filename=None, mask4d=False, rtn=None): import gui_mask root = Tk() #current_pwd = os.path.abspath(os.path.curdir()) working = self.txt_working.get() #os.chdir(working) if filename is None or filename == '': app = gui_mask.CreateMask(root, filename=None, dirname=working, mask4d=mask4d, obj_return_value=rtn) else: app = gui_mask.CreateMask(root, filename=os.path.join(working, filename), dirname=working, mask4d=mask4d, obj_return_value=rtn) root.mainloop() #os.chdir(current_pwd) #tkMessageBox.showinfo(self.title, 'Done: Making mask') def run_topup(self): dependency = [ self.txt_b0, self.txt_b0mask, ] if not self.check_dependency(dependency): return working = self.txt_working.get() fn_b0 = os.path.join(working, self.txt_b0.get()) fn_b0mask = os.path.join(working, self.txt_b0mask.get()) fn_b0masked = filename_wo_ext(fn_b0) + '_masked.nii.gz' fn_out = os.path.join(working, self.prefix() + 'topup') run_command('fslmaths %s -mas %s %s' % (fn_b0, fn_b0mask, fn_b0masked)) topup_command = [self.txt_topup_app.get()] if self.txt_topup_config.get() != '': topup_command.append('--config=%s' % self.txt_topup_config.get()) topup_command.append('--datain=%s' % (os.path.join(working, self.prefix() + 'acqparams.txt'))) topup_command.append('--imain=%s' % fn_b0masked) topup_command.append('--out=%s' % fn_out) topup_command.append('--iout=%s_warped' % fn_out) topup_command.append('--fout=%s_field' % fn_out) topup_command.append('--logout=%s_log' % fn_out) topup_command.append('1> %s_topup_log.out' % self.txt_subject.get()) cmd = ' '.join(topup_command) append_text(self.log, cmd, 'run_topup') run_command(cmd) print 'Done: TOPUP' tkMessageBox.showinfo(self.title, 'Done: TOPUP') def run_eddy(self): dependency = [ self.txt_dwi, self.txt_dwi_mask, ] if not self.check_dependency(dependency): return working = self.txt_working.get() eddy_command = [self.txt_eddy_app.get()] eddy_command.append('--flm=quadratic') eddy_command.append('--acqp=%s' % (os.path.join(working, self.prefix() + 'acqparams.txt'))) eddy_command.append('--bvals=%s' % (os.path.join(working, self.txt_bval.get()))) eddy_command.append('--bvecs=%s' % (os.path.join(working, self.txt_bvec.get()))) eddy_command.append('--imain=%s' % (os.path.join(working, self.txt_dwi.get()))) eddy_command.append('--index=%s' % (os.path.join(working, self.prefix() + 'index.txt'))) eddy_command.append('--mask=%s' % (os.path.join(working, self.txt_dwi_mask.get()))) eddy_command.append('--topup=%s' % (os.path.join(working, self.prefix() + 'topup'))) eddy_command.append('1> %s_eddy_log.out' % self.txt_subject.get()) if self.txt_output_eddy.get() == '': self.gen_eddy_outputname() eddy_command.append( '--out=%s' % (os.path.join(working, self.txt_output_eddy.get()))) cmd = ' '.join(eddy_command) append_text(self.log, cmd, 'run_eddy') run_command(cmd) print 'Done: Eddy' self.reset_entry(self.txt_dwi_eddy, self.txt_output_eddy.get()) tkMessageBox.showinfo(self.title, 'Done: EDDY') def run_rigid_reg(self): dependency = [ self.txt_b0, self.txt_dwi_mask, ] if not self.check_dependency(dependency): return tkMessageBox.showinfo(self.title, 'Non implemented yet') #tkMessageBox.showinfo(self.title, 'Done: Rigid registration') def save_reg_param(self): dependency = [ self.txt_dwi_eddy, self.txt_reg_mask, ] if not self.check_dependency(dependency): return filename = tkFileDialog.asksaveasfilename( initialdir=self.txt_working.get(), initialfile='reg_2d.params') if filename == '': return self.update_param_from_text() param_2d = parameter.Parameter_reg2d(param_object=self.param) param_2d.save_param(filename) def run_xy_reg(self): dependency = [self.txt_dwi_eddy, self.txt_reg_mask] if not self.check_dependency(dependency): return self.update_param_from_text() param_2d = parameter.Parameter_reg2d(param_object=self.param) spine_reg.set_print_cmd( os.path.join(self.txt_working.get(), self.prefix() + 'xy_reg_cmd')) cmd = '\n'.join( [str(vars(param_2d)), 'spine_reg.run_registration(param_2d)']) append_text(self.log, cmd, 'run_xy_reg') sub_slices = self.txt_reg_slices.get() if sub_slices != '': try: slices = [ value.strip() for value in sub_slices.strip().split(',') ] slices = [int(value) for value in slices if value != ''] sub_slices = slices except: sub_slices = None else: sub_slices = None fn_out = spine_reg.run_registration(param_2d, sub_slices=sub_slices) self.reset_entry(self.txt_dwi_dti, fn_out) os.chdir(self.txt_working.get()) print 'Done: XY-Reg' tkMessageBox.showinfo(self.title, 'Done: XY-registration') def run_applywarp(self): dependency = [ self.txt_dwi_eddy, self.txt_reg_mask, ] if not self.check_dependency(dependency): return param_2d = parameter.Parameter_reg2d(param_object=self.param) spine_reg.set_print_cmd( os.path.join(self.txt_working.get(), self.prefix() + 'xy_reg_cmd')) fn_out = spine_reg.run_applywarp(param_2d) self.reset_entry(self.txt_dwi_dti, fn_out) print 'Done: Applywarp' tkMessageBox.showinfo(self.title, 'Done: Applywarp') def run_xy_reg_outlier(self, param_2d=None): dependency = [self.txt_dwi_eddy, self.txt_reg_mask, self.txt_bval] #if not self.check_dependency(dependency): # return self.update_param_from_text() if param_2d is None: param_2d = parameter.Parameter_reg2d(param_object=self.param) spine_reg.generate_xy_trans(param_2d) os.chdir(self.txt_working.get()) print 'Done: XY-Reg outlier calculation' def run_generate_dti_maps(self, outlier=False): cmd = 'generate_dti_maps(%s)' % (', '.join([ self.txt_dwi_dti.get(), 'bval_bvec=None', 'bval=%s' % os.path.join(self.txt_working.get(), self.txt_bval.get()), 'bvec=%s' % os.path.join(self.txt_working.get(), self.txt_bvec.get()), 'prefix=%s' % self.prefix(), 'outlier=%s' % outlier ])) append_text(self.log, cmd, 'run_generate_dti_maps') fn_out = generate_dti_maps(self.txt_dwi_dti.get(), bval_bvec=None, bval=os.path.join(self.txt_working.get(), self.txt_bval.get()), bvec=os.path.join(self.txt_working.get(), self.txt_bvec.get()), prefix=self.prefix(), outlier=outlier) print 'Done: Generate DTI maps' self.reset_entry(self.txt_dti_value, fn_out) tkMessageBox.showinfo(self.title, 'Done: Generating DTI maps') def run_md_mask(self): if not os.path.isfile( os.path.join(self.txt_working.get(), self.txt_dwi_dti.get())): sys.stderr.write('File not exist: %s\n' % self.txt_dwi_dti.get()) return working = self.txt_working.get() if os.path.isfile(os.path.join(working, self.txt_dti_value.get())): fn_md = filename_wo_ext(self.txt_dti_value.get()) + '_MD.nii.gz' else: fn_md = filename_wo_ext(self.txt_dwi_dti.get()) + '_dti_MD.nii.gz' fn_mask = create_md_mask(os.path.join(working, fn_md), fn_out=None, thr_min=0.1, thr_max=1.1) print 'Done: Making MD mask' self.reset_entry(self.txt_md_mask, os.path.basename(fn_mask)) #tkMessageBox.showinfo(self.title, 'Done: MD mask') def run_dti_outlier(self): import outlier_4dfp_gui root = Tk() working = self.txt_working.get() filename = os.path.join( working, filename_wo_ext(self.txt_dwi_dti.get()) + '_res.nii.gz') filename_roi = os.path.join(working, self.txt_md_mask.get()) filename_csv = os.path.join(working, self.txt_dti_outlier.get()) if filename_csv == '': filename_csv = filename_wo_ext(filename) + '.csv' print filename, filename_roi, filename_csv app = outlier_4dfp_gui.Outlier4dfp( root, filename=filename, filename_roi=filename_roi, filename_csv=filename_csv, dirname=working, obj_return_value=self.txt_dti_outlier) root.mainloop() #tkMessageBox.showinfo(self.title, 'Done: Making mask') def run_get_dti_values(self): filenames = [ '%s_%s' % (self.txt_dti_value.get(), tmp) for tmp in ['MD', 'FA', 'RD', 'RA', 'Eig1', 'Eig2', 'Eig3'] ] filename_roi = self.txt_dti_roi.get() filename_csv = self.txt_output_dti_value.get() if filename_csv == '': self.gen_dti_value_outputname() filename_csv = self.txt_output_dti_value.get() value_matrix = calculate_voxel_values(filenames, filename_roi, filename_csv=filename_csv) print 'Done: Getting DTI values'
def __init__(self, parent, txt=dict(), switcher=None): """Instanciating the output workbook.""" self.parent = parent Frame.__init__(self) # subframes self.FrOptProxy = Frame(self, name='settings_proxy') self.FrOptIsogeo = Frame(self, name='settings_isogeo') # options values self.opt_proxy = IntVar(self) # proxy option self.opt_isogeo = IntVar(self) # Isogeo option # Options form widgets caz_prox = Checkbutton( self, text=u'Proxy', variable=self.opt_proxy, command=lambda: switcher(self.opt_proxy, self.FrOptProxy)) caz_isogeo = Checkbutton( self, text=u'Isogeo', variable=self.opt_isogeo, command=lambda: switcher(self.opt_isogeo, self.FrOptIsogeo)) # positionning caz_prox.grid(row=0, column=0, sticky="NSWE", padx=2, pady=2) self.FrOptProxy.grid(row=0, column=1, columnspan=8, sticky="NSWE", padx=2, pady=2, rowspan=3) caz_isogeo.grid(row=3, column=0, sticky="NSWE", padx=2, pady=2) self.FrOptIsogeo.grid(row=3, column=1, columnspan=8, sticky="NSWE", padx=2, pady=2, rowspan=4) # ------------------------------------------------------------------------ # proxy specific variables self.opt_ntlm = IntVar(self.FrOptProxy, 0) # proxy NTLM protocol option self.prox_server = StringVar(self.FrOptProxy, 'proxy.server.com') self.prox_port = IntVar(self.FrOptProxy, 80) self.prox_user = StringVar(self.FrOptProxy, 'proxy_user') self.prox_pswd = StringVar(self.FrOptProxy, '****') # widgets self.prox_ent_H = Entry(self.FrOptProxy, textvariable=self.prox_server) self.prox_ent_P = Entry(self.FrOptProxy, textvariable=self.prox_port) self.prox_ent_M = Entry(self.FrOptProxy, textvariable=self.prox_pswd, show='*') self.prox_lb_H = Label(self.FrOptProxy, text=txt.get('gui_prox_server', "Host")) self.prox_lb_P = Label(self.FrOptProxy, text=txt.get('gui_port', "Port")) caz_ntlm = Checkbutton(self.FrOptProxy, text=u'NTLM', variable=self.opt_ntlm) self.prox_lb_M = Label(self.FrOptProxy, text=txt.get('gui_mdp', "Password")) # proxy widgets position self.prox_lb_H.grid(row=1, column=0, sticky="NSEW", padx=2, pady=2) self.prox_ent_H.grid(row=1, column=1, columnspan=2, sticky="NSEW", padx=2, pady=2) self.prox_lb_P.grid(row=1, column=2, sticky="NSEW", padx=2, pady=2) self.prox_ent_P.grid(row=1, column=3, columnspan=2, sticky="NSEW", padx=2, pady=2) caz_ntlm.grid(row=2, column=0, sticky="NSEW", padx=2, pady=2) self.prox_lb_M.grid(row=2, column=1, sticky="NSEW", padx=2, pady=2) self.prox_ent_M.grid(row=2, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2) # ------------------------------------------------------------------------ # Isogeo application variables self.isog_app_id = StringVar(self.FrOptIsogeo, 'application_id') self.isog_app_tk = StringVar(self.FrOptIsogeo, 'secret') # widgets isog_ent_id = Entry(self.FrOptIsogeo, textvariable=self.isog_app_id) isog_ent_tk = Entry(self.FrOptIsogeo, textvariable=self.isog_app_tk) isog_lb_id = Label(self.FrOptIsogeo, text="Application ID") isog_lb_tk = Label(self.FrOptIsogeo, text="Application secret") # Isogeo widgets position isog_lb_id.grid(row=1, column=1, sticky="NSEW", padx=2, pady=2) isog_ent_id.grid(row=1, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2) isog_lb_tk.grid(row=2, column=1, sticky="NSEW", padx=2, pady=2) isog_ent_tk.grid(row=2, column=2, columnspan=2, sticky="NSEW", padx=2, pady=2)
def initUI(self): # Configures the GUI self.parent.title("Neural Networks for Handwritten Digit Recognition") self.style = Style() self.pack(fill=BOTH, expand=1) # Creates a grid 5x4 in to which we will place elements. self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=0) self.columnconfigure(3, weight=0) self.columnconfigure(4, weight=0) self.columnconfigure(5, weight=0) self.columnconfigure(6, weight=0) self.columnconfigure(7, weight=0) self.columnconfigure(8, weight=0) self.rowconfigure(1, weight=1) self.rowconfigure(2, weight=0) self.rowconfigure(3, weight=0) self.rowconfigure(4, weight=0) # Create explanation text for app explanation = """ "This program is capable of utilizing different learning algorithms as a mean to achieve a +90% accuracy in recognizing MNIST digits based on Neural Networks as a way of detecting the different numbers and classifying them correctly" \n Select the checkboxes that you wish to utilize ([ ] Learn from starting random values, [X] Learn from preexisting data / [ ] Do not save the results [X] Save the final values of the Weights and Biases), Press the Run button to start the Neural Network\n""" self.exp = Label(self, text=explanation) self.exp.grid( row=2, column=1, columnspan=4, padx=2, pady=2, ) # Creates the Y scrollbar that is spawned through the whole grid yscrollbar = Scrollbar(self, orient=VERTICAL) yscrollbar.grid(row=1, column=8, sticky=N + S) # Creates the text area and spawns it through the whole window self.textarea = Text(self, wrap=NONE, bd=0, yscrollcommand=yscrollbar.set) self.textarea.grid(row=1, column=1, columnspan=4, rowspan=1, padx=0, sticky=E + W + S + N) yscrollbar.config(command=self.textarea.yview) # Creates the run button in the lower row self.runButton = Button(self, text="Run Neural Network") self.runButton.grid(row=4, column=1, padx=5, pady=5, sticky=W) self.runButton.bind("<ButtonRelease-1>", self.runNN) # Creates the variable initialization checkbox in the lower row self.initvalVar = StringVar() initvalCheck = Checkbutton(self, text="Learn from Initial Values", variable=self.initvalVar, onvalue="-l", offvalue="") initvalCheck.grid(row=4, column=2, padx=5, pady=5) # Creates the save variables checkbox in the lower row self.saveValVar = StringVar() saveVal = Checkbutton(self, text="Save final Weights & Biases", variable=self.saveValVar, onvalue="-s", offvalue="") saveVal.grid(row=4, column=3, padx=5, pady=5) # Creates the clear button for the textbox self.clearButton = Button(self, text="Clear") self.clearButton.grid(row=4, column=4, padx=5, pady=5) self.clearButton.bind("<ButtonRelease-1>", self.clearText) # Defines the tags that are used to colorise the text added to the text widget. self.textarea.tag_config("errorstring", foreground="#CC0000") # Red Color self.textarea.tag_config("infostring", foreground="#008800") # Green Color
def modifyUI(self): frame_bottom = self.frame_bottom frame_main = self.frame_main self.sliceView = [ ImshowMplCanvas(frame_main) for k in range(self.shape[2]) ] self.sliceSpin = [ MySpinBox(frame_main, k) for k in range(self.shape[2]) ] #Layout self.parent.title('CreateMask') max_spin = 0 if self.mask4d: max_spin = self.shape[3] - 1 self.spin_volume = Spinbox(frame_bottom, from_=0, to=max_spin, increment=1, command=self.change_volume, width=8) self.reset_box(self.spin_volume, 0) buttonMask = Button(frame_bottom, text='B0 from Bval...', command=self.createBaseImage) buttonMaskCreate = Button(frame_bottom, text='Create', command=self.createMaskAll) buttonSave = Button(frame_bottom, text='Save', command=self.saveMask) self.drawmask = BooleanVar() buttonDrawMask = Checkbutton(frame_bottom, text='Draw Mask', variable=self.drawmask, command=self.drawSlice) num_col = 3 num_row = 6 for col in range(self.shape[2] / num_row): for k in range(num_row): ind = col * num_row + k if ind >= self.shape[2]: break self.sliceView[ind].get_tk_widget().grid(row=k, column=col * num_col, sticky=NSEW) self.sliceSpin[ind].grid(row=k, column=col * num_col + 1) self.frame_main.grid_columnconfigure(col * num_col, weight=1) for k in range(num_row): self.frame_main.grid_rowconfigure(k, weight=1) self.spin_volume.grid(row=0, column=0) buttonMask.grid(row=0, column=1) buttonMaskCreate.grid(row=0, column=2) buttonSave.grid(row=0, column=3) buttonDrawMask.grid(row=0, column=5) frame_bottom.pack(side=BOTTOM) frame_main.pack(fill=BOTH, expand=TRUE) self.pack(fill=BOTH, expand=True)