def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10+self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10+self.labelName.winfo_width()+10,y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = ['UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized'] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10+self.labelCategory.winfo_width()+10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton(self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10+self.getImageButton.winfo_width()+10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230)
def __init__(self, root): super().__init__() self.root = root self.exception = None self.list_string = StringVar() self.listbox = Listbox(root, listvariable=self.list_string, font='TkFixedFont', width=30) self.write_cache = '' self.logfile = None self.enable_logging = BooleanVar() self.enable_logging_checkbox = Checkbutton( root, var=self.enable_logging, text='Enable logging', command=self.enable_logging_changed) self.logfile_label = Label(root, text='Logfile name:') self.logfile_name = StringVar() self.logfile_name_entry = Entry(root, textvar=self.logfile_name) self.load()
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 __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 _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 setup_general(self): '''add options part''' dct = self.user_input dct['min_age'] = self.general_component('Minimum age', 3, 0) dct['max_age'] = self.general_component('Maximum age', 4, 0) dct['begin_interval'] = self.general_component('First interval day', 5, 0, help_txt='') dct['end_interval'] = self.general_component('Last interval day', 6, 0, help_txt='') dct['ID_column'] = self.general_component('ID column name', 7, 0, init_val='patientnummer') enrich_val = BooleanVar() dct['enrich'] = enrich_val Checkbutton(self, text='semantic enrichment', variable=enrich_val).grid(row=8, column=0, columnspan=2, sticky=W) dct['mapping_dir'] = self.button_component('Browse', 'semantic enrichment dir', 9, 0) # verbose_val = BooleanVar() # dct['verbose'] = verbose_val # Checkbutton(self,text='verbose (N/A)', variable=verbose_val, state=DISABLED).grid(row=10, column=0, columnspan=2, sticky=W) survival_val = BooleanVar() dct['survival'] = survival_val Checkbutton(self, text='activate survival', variable=survival_val).grid(row=10, column=0, columnspan=2, sticky=W) already_processed_val = BooleanVar() dct['already_processed'] = already_processed_val Checkbutton(self, text='already_processed', variable=already_processed_val).grid(row=11, column=0, columnspan=2, sticky=W)
def __init__(self, master, track, sequencer): TrackFrame.__init__(self, master, track) self.id_label = Label(self, text=str(track.id)) self.id_label.pack(side='left') self.instrument_label = Label(self, text=str(track.instrument_tone), width=3) self.instrument_label.pack(side='left') mute_var = IntVar() self.mute_toggle = Checkbutton(self, command=lambda: check_cmd(track, mute_var), variable=mute_var) self.mute_toggle.pack(side='left') mute_var.set(not track.mute) rhythm_frame = Frame(self) rhythm_frame.pack(side='right') subdivision = sequencer.measure_resolution / sequencer.beats_per_measure self.buttons = [] for b in range(0, len(self.track.rhythms)): button = RhythmButton(rhythm_frame, track, b, not b % subdivision) self.buttons.append(button) button.grid(row=0, column=b, padx=1) self.beat = 0
def __init__(self, master, name=None, scrollregion=(0, 0, '5i', '5i'), items=[], window_size=[160, 30], **canvaskw): Frame.__init__(self, master, name=name) self.scrollcanvas = Canvas(self, name='scrollcanvas', scrollregion=scrollregion, **canvaskw) self.yscroll = Scrollbar(self, name='yscroll', command=self.scrollcanvas.yview) self.scrollcanvas['yscrollcommand'] = self.yscroll.set self.yscroll.pack(side=RIGHT, fill=Y) self.scrollcanvas.pack(side=LEFT, fill=BOTH, expand=YES) self.items = dict.fromkeys(items) for n, i in enumerate(items): self.items[i] = {'frame': Frame(self, name=(i.lower() + '_frame'))} self.items[i]['frame'].config(relief=GROOVE, padding=5) self.items[i]['chbx'] = Checkbutton(self.items[i]['frame'], name=(i.lower() + '_chbx')) self.items[i]['chbx']['text'] = i self.items[i]['chbx'].pack(side=LEFT, fill=X) y = window_size[1] / 2 + window_size[1] * n self.items[i]['window'] = self.scrollcanvas.create_window(0, y) self.scrollcanvas.itemconfigure(self.items[i]['window'], window=self.items[i]['frame'], anchor=W, width=window_size[0], height=window_size[1])
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 __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 main1(): main_window = Tk() main_window.geometry("500x500") main_window.iconbitmap(os.path.abspath( os.curdir + "\Assets\Alien_robot.ico")) #r"C:\Users\ofer\Desktop\github files\project\Alien_robot.ico") main_window.wm_title("Personal Helper!") l = Label(text="Personal helper!") CheckVal1 = IntVar() w = Checkbutton(main_window, text="work", variable=CheckVal1, \ onvalue=1, offvalue=0, height=5, \ width=20) b = Button(main_window, text="start scanning for programs", command=scan_computer_programs) #c = Button(main_window, text="block all gaming apps", command=running_programs(main_window,True)) l.pack() b.pack() c.pack() w.pack() print CheckVal1 main_window.mainloop()
def main1(): main_window = Tk() main_window.geometry("500x500") main_window.iconbitmap( os.path.abspath(os.curdir + "\Assets\Alien_robot.ico") ) #r"C:\Users\ofer\Desktop\github files\project\Alien_robot.ico") main_window.wm_title("Personal Helper!") l = Label(text="Personal helper!") CheckVal1 = IntVar() w = Checkbutton(main_window, text="work", variable=CheckVal1, \ onvalue=1, offvalue=0, height=5, \ width=20) b = Button(main_window, text="start scanning for programs", command=scan_computer_programs) #c = Button(main_window, text="block all gaming apps", command=running_programs(main_window,True)) l.pack() b.pack() c.pack() w.pack() print CheckVal1 main_window.mainloop()
def insert_checkbutton(self, text, frame_name, side, varname, stick=None, default=None, callback=None): """Inserts a check button widget in the specified frame. ARGS: * var: a TKinter supported variable, such as IntVar(), StrVar(), and etc.""" # create a variable for this task var = BooleanVar() if default is not None: var.set(default) # create the widget frame = self.frames[frame_name] check = Checkbutton(frame, text=text, variable=var, command=callback) check.pack(side=self.TkSide[side], anchor=stick) # save data regarding the widget if self.checkbuttons.get(frame_name, None) == None: self.checkbuttons[frame_name] = {} self.checkbuttons[frame_name][varname] = {'button':check, 'var':var}
def label_1to1_bool_checkbutton(self, name="", default_bool=True, default_text="Yes"): self.vb_name.append(name.split()[0]) self.all_comp.append(Label(self.master, text=name)) #self.all_comp[-1].pack(anchor='w') self.all_comp[-1].grid(row=self.row, sticky=E) # self.get_comp.append(BooleanVar(self.master, default_bool)) self.all_comp.append( Checkbutton(self.master, text=default_text, variable=self.get_comp[-1], offvalue=False, onvalue=True)) #self.all_comp[-1].pack() self.all_comp[-1].grid(row=self.row, column=1, sticky=W) # self.row += 1 #
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_ui(self): self.parent.title("Image enhancement") self.pack(fill=BOTH, expand=1) self.center_window() openFileButton = Button(self, text="Choose image", command=self.open_file) openFileButton.place(x=50, y=50) self.runButton = Button(self, text="Enhance", command=self.run, state="disabled") self.runButton.place(x=200, y=50) membershipLabel = Label(text="Membership passes:") membershipLabel.place(x=50, y=120) self.membershipPassScale = LabeledScale(self, from_=1, to=10) self.membershipPassScale.place(x=250, y=100) intensifyLabel = Label(text="1st intensify passes:") intensifyLabel.place(x=50, y=170) self.intensifyPassScale = LabeledScale(self, from_=1, to=10) self.intensifyPassScale.place(x=250, y=150) convolveLabel = Label(text="Convolve:") convolveLabel.place(x=50, y=220) self.convolveCheckbutton = Checkbutton(self) self.convolveCheckbutton.place(x=250, y=220) self.convolveCheckbutton.invoke() secondIntensifyLabel = Label(text="2nd intensify passes:") secondIntensifyLabel.place(x=50, y=270) self.secondIntensifyPassScale = LabeledScale(self, from_=1, to=10) self.secondIntensifyPassScale.place(x=250, y=250) thresholdLabel = Label(text="Threshold:") thresholdLabel.place(x=50, y=320) self.thresholdScale = LabeledScale(self, from_=1, to=10) self.thresholdScale.place(x=250, y=300) self.thresholdScale.scale.set(5) powerLabel = Label(text="Power:") powerLabel.place(x=50, y=370) self.powerScale = LabeledScale(self, from_=2, to=5) self.powerScale.place(x=250, y=350)
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 __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.parent.title("Simple") self.pack(fill=BOTH, expand=True) self.centerWindow() sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() frame1 = Frame(self, relief=RAISED, borderwidth=1) frame1.pack(fill=X) button1 = Button(frame1, text=u"<", command=self.prevDocument) button1.pack(side=LEFT, padx=5, pady=5) button2 = Button(frame1, text=u">", command=self.nextDocument) button2.pack(side=LEFT, padx=5, pady=5) self.selCategory = StringVar(self) self.categoryOption = OptionMenu(frame1, self.selCategory, *["Categories"], command=self.changeCategory) self.categoryOption.pack(side=LEFT, padx=5, pady=5) self.entry1 = Entry(frame1) self.entry1.pack(side=LEFT, padx=5, pady=5) self.ignoreActualDocVar = IntVar(self) checkButton1 = Checkbutton(frame1, text="Ignored", variable=self.ignoreActualDocVar) checkButton1.pack(side=LEFT, padx=5, pady=5) button3 = Button(frame1, text=u"Save document", command=self.prevDocument) button3.pack(side=LEFT, padx=5, pady=5) #entry1 = Entry(frame1) #entry1.pack(fill=X, padx=5, expand=True) frame2 = PanedWindow(self, orient=HORIZONTAL) frame2.pack(fill=BOTH, expand=1) self.txt1 = Text(frame2, width=sw/22) frame2.add(self.txt1) self.txt2 = Text(frame2) self.txt2.bind("<Button-3>", self.popup) frame2.add(self.txt2) frame3 = Frame(self, relief=RAISED, borderwidth=1) frame3.pack(fill=X) #lbl3 = Label(frame3, text="Author", width=6) #lbl3.pack(side=LEFT, padx=5, pady=5) #entry3 = Entry(frame3) #entry3.pack(fill=X, padx=5, expand=True) self.swVar = IntVar(self) checkButton1 = Checkbutton(frame3, text="Remove stop words", variable=self.swVar) checkButton1.pack(side=LEFT, padx=5, pady=5) self.lowerVar = IntVar(self) checkButton1 = Checkbutton(frame3, text="Convert to lower case", variable=self.lowerVar) checkButton1.pack(side=LEFT, padx=5, pady=5) button3 = Button(frame3, text=u"Apply", command=self.applyProcessing) button3.pack(side=LEFT, padx=5, pady=5) #self.readCorpus() # create a toplevel menu menubar = Menu(self) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Quit", command=self.parent.quit) filemenu.add_command(label="Open corpus", command=self.loadCorpus) menubar.add_cascade(label="Project", menu=filemenu) #menubar.add_command(label="Quit!") # , command=root.quit # display the menu self.parent.config(menu=menubar) self.popupmenu = Menu(self.parent, tearoff=0) self.popupmenu.add_command(label="Undo", command=self.hello) self.popupmenu.add_command(label="Redo", command=self.hello)
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)
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): #Parent Frame self.parent.title("Test Stand Control Panel") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) # Frame 1 (top) frame1 = Frame(self) frame1.pack(fill=X, expand=1) #Start motor button startButton = Button(frame1, text="Start Motor", command=self.startMotor) startButton.pack(side=LEFT, padx=5, pady=5) #Throttle slider lbl1 = Label(frame1, text="Throttle (0-100):", width=14) lbl1.pack(side=LEFT, padx=5, pady=5) self.scale = Scale(frame1, from_=0, to=100, command=self.onScaleThrottle) self.scale.pack(side=LEFT, padx=15) self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5) self.label.pack(side=LEFT) #Throttlesweep checkbutton self.autovar = BooleanVar() cb = Checkbutton(frame1, text="Throttle Sweep", variable=self.autovar, command=self.onClickAuto) cb.pack(side=LEFT, padx=15) #Com port selection field droplbl = Label(frame1, text="Serial Port:", width=10) droplbl.pack(side=LEFT, padx=5, pady=5) self.selected_s_Port = StringVar() self.s_Ports = [] self.drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports) self.drop.pack(side=LEFT, padx=5) #baudrate selection field (disabled) ## drop2lbl = Label(frame1, text="Baudrate:", width=9) ## drop2lbl.pack(side=LEFT, padx=5, pady=5) ## self.baudrate = StringVar() ## baudrates = [9600, 19200, 38400, 57600, 115200] ## drop2 = OptionMenu(frame1,self.baudrate,*baudrates) ## drop2.pack(side=LEFT, padx=5) #Start serial button comsButton = Button(frame1, text="Start Serial", command=self.startSerial) comsButton.pack(side=LEFT, padx=5, pady=5) #Stop serial button comsStopButton = Button(frame1, text="Stop Serial", command=self.stopSerial) comsStopButton.pack(side=LEFT, padx=5, pady=5) # Frame 2 (second line) frame2 = Frame(self) frame2.pack(fill=X, expand=1) #Amperage entry lbl2 = Label(frame2, text="Max Motor Current (A):", width=21) lbl2.pack(side=LEFT, padx=5, pady=5) self.MaxA_Entry = Entry(frame2) self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False) self.MaxA_Entry.insert(0, 10) #Voltage entry lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20) lbl3.pack(side=LEFT, padx=5, pady=5) self.MaxV_Entry = Entry(frame2) self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False) self.MaxV_Entry.insert(0, 14) #Update button updateButton = Button(frame2, text="Update Values", command=self.updateValues) updateButton.pack(side=LEFT, padx=5, pady=5) # Graph Frame framegraph = Frame(self) framegraph.pack(fill=X, expand=1) #Init figures f = Figure(figsize=(4,4), dpi=100) self.a = f.add_subplot(2, 2, 1) self.d = f.add_subplot(2, 2, 4) self.c = f.add_subplot(2, 2, 3) self.b = f.add_subplot(2, 2, 2) f.set_tight_layout(True) self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) #Display Toolbar toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) # Frame 0 (Bottom text) frame0 = Frame(self) frame0.pack(side="bottom", fill="x", expand=1) #Display text (allows to give user information) self.textboxvar = StringVar() self.info = Label(frame0, textvariable=self.textboxvar) self.info.pack(side=LEFT, padx=5, pady=5) # Button Frame (large buttons, near bottom) s = Style() #has its own style s.configure('My.TFrame',background='#f7edc3') #fancy colors framered = Frame(self, style='My.TFrame') framered.pack(side="bottom", fill="x", expand=1) #used the tk instead of ttk library for this, allows font and color mods #Save Button self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'), command=self.saveData) self.saveButton.pack(side="left", padx=5, pady=5) #Log button self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'), command=self.logData) self.logButton.pack(side="left", padx=5, pady=5) #Stop button self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'), command=self.stopMotor) self.stopButton.pack(side="right", padx=5, pady=5)
def __init__(self, model): self.model = model self.model_config = self.model.get_config() self.channels_num = 0 self.channels_amount = 0 self.root = Tk() self.root.resizable(width=FALSE, height=FALSE) self.root.title("RaaS. event_proxy configurator") #: self.root.iconbitmap('resourse/vit.ico') self.config_route = self.model.get_config_route() self.panelFrame = Frame(self.root, height=60) self.canvas = Canvas(self.root, borderwidth=0) self.textFrame = Frame(self.canvas, height=340, width=600) self.mainFrame = LabelFrame(self.root, width=200, text="Main:", height=340, relief=RAISED, borderwidth=1) self.chanelFrame = LabelFrame(self.root, width=370, text="Channels:", height=340, relief=RAISED, borderwidth=1) #: self.vsb = Scrollbar(self.root, orient="horizontal", #: command=self.canvas.xview) #:self.canvas.configure(xscrollcommand=self.vsb.set) #:self.vsb.pack(side="bottom", fill="x") self.canvas.pack(side="bottom", fill="both", expand=True) self.canvas.configure(scrollregion=self.canvas.bbox("all")) self.root.protocol("WM_DELETE_WINDOW", self.quit_handler) self.tabs = Notebook(self.root) self.in_channel_text = [] self.out_port_text = [] self.out_channel_text = [] self.c = self.model.get_channels().keys() self.channels_len = len(self.model.get_channels()) #:print self.model.get_channels() self.panelFrame.pack(side='top', fill='x') self.textFrame.pack(side='bottom', fill='both', expand=1) self.mainFrame.place(x=10, y=60) self.chanelFrame.place(x=220, y=60) self.tabs.place(x=230, y=80) x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2 y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2 self.root.geometry("+%d+%d" % (x-150, y-150)) for i in range(self.channels_len): self.channels_num += 1 self.channels_amount += 1 self.f1 = Frame(self.tabs, height=290, width=350) self.tabs.add(self.f1, text='Channel {0}'.format(i + 1)) self.in_channel = Label(self.f1, text="In channel") self.out_port = Label(self.f1, text="Out port") self.out_channel = Label(self.f1, text="Out channel") self.in_channel_text.append(Entry(self.f1, width=20, bd=3)) self.in_channel_text[i].insert(0, self.c[i]) self.out_port_text.append(Entry(self.f1, width=20, bd=3)) self.out_port_text[i].insert(0, self.model.get_channels()[ self.c[i]].out_port) self.out_channel_text.append(Entry(self.f1, width=20, bd=3)) self.out_channel_text[i].insert(0, self.model.get_channels()[ self.c[i]].out_channel) self.in_channel.place(x=5, y=10) self.in_channel_text[i].place(x=5, y=30) self.out_port.place(x=5, y=50) self.out_port_text[i].place(x=5, y=70) self.out_channel.place(x=5, y=90) self.out_channel_text[i].place(x=5, y=110) self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format( self.channels_amount), command= lambda: self.del_channel(i)) self.del_ch_btn.bind("<Button-1>") self.del_ch_btn.place(x=5, y=140, width=100, height=30) self.server_host_label = Label(self.root, text="Server host") self.server_port_label = Label(self.root, text="Server port") self.raas_port_label = Label(self.root, text="Raas port") self.encoding_label = Label(self.root, text='Encoding') self.levenshtein_distance_label = Label(self.root, text='Levenshtein distance') self.window_time_label = Label(self.root, text='Window time') self.server_host_entity = Entry(self.root, width=20, bd=3) self.server_host_entity.insert(0, self.model_config['server_host']) self.server_port_entity = Entry(self.root, width=20, bd=3) self.server_port_entity.insert(0, self.model_config['server_port']) self.raas_port_entity = Entry(self.root, width=20, bd=3) self.raas_port_entity.insert(0, self.model_config['raas_port']) self.encoding_entry = Entry(self.root, width=20, bd=3) self.encoding_entry.insert(0, self.model_config['encoding']) self.levenshtein_distance_entry = Entry(self.root, width=20, bd=3) self.levenshtein_distance_entry.insert(0, self.model_config[ 'levenshtein_distance']) self.window_time_entry = Entry(self.root, width=20, bd=3) self.window_time_entry.insert(0, self.model_config['window_time']) self.var = IntVar() self.cfg_debug = self.model_config['debug'] if self.cfg_debug == 'True': self.var.set(1) else: self.var.set(0) self.check_debug = Checkbutton(self.root, text='Debug', variable=self.var) self.filter_var = IntVar() self.cfg_use_filter = self.model_config['use_filter'] if self.cfg_use_filter == 'True': self.filter_var.set(1) else: self.filter_var.set(0) self.check_use_filter = Checkbutton(self.root, text='Use filter', variable=self.filter_var) self.addBtn = Button(self.panelFrame, text='Add channel') self.saveBtn = Button(self.panelFrame, text='Save') self.quitBtn = Button(self.panelFrame, text='Quit') self.saveBtn.bind("<Button-1>", self.SaveFile) self.quitBtn.bind("<Button-1>", self.Quit) self.addBtn.bind("<Button-1>", self.add_channel) self.saveBtn.place(x=10, y=10, width=40, height=40) self.quitBtn.place(x=60, y=10, width=40, height=40) self.addBtn.place(x=220, y=10, width=80, height=40) self.server_host_label.place(x=20, y=80) self.server_host_entity.place(x=20, y=100) self.server_port_label.place(x=20, y=120) self.server_port_entity.place(x=20, y=140) self.raas_port_label.place(x=20, y=160) self.raas_port_entity.place(x=20, y=180) self.encoding_label.place(x=20, y=200) self.encoding_entry.place(x=20, y=220) self.check_debug.place(x=20, y=250) self.f = Frame(self.root, height=1, width=190, bg='grey') self.f.place(x=15, y=275) self.levenshtein_distance_label.place(x=20, y=280) self.levenshtein_distance_entry.place(x=20, y=300) self.window_time_label.place(x=20, y=320) self.window_time_entry.place(x=20, y=340) self.check_use_filter.place(x=20, y=370)
class SetupBoard(Dialog): def __init__(self, parent, title, gameManager): self._master = parent self._manager = gameManager self._load_entry_box_vars() self.result = False Dialog.__init__(self, parent, title) def body(self, master): self._npLFrame = LabelFrame(master, text='No. of players:') self._npFrameEx1 = Frame(self._npLFrame, width=30) self._npFrameEx1.pack(side=LEFT, pady=5, expand=1) self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)', value=0, variable=self._num_players, command=self._disable_player_color) self._npButton1.pack(side=LEFT, pady=5, expand=1) self._npButton2 = Radiobutton(self._npLFrame, text='One', value=1, variable=self._num_players, command=self._enable_player_color) self._npButton2.pack(side=LEFT, pady=5, expand=1) self._npButton3 = Radiobutton(self._npLFrame, text='Two', value=2, variable=self._num_players, command=self._disable_player_color) self._npButton3.pack(side=LEFT, pady=5, expand=1) self._npFrameEx2 = Frame(self._npLFrame, width=30) self._npFrameEx2.pack(side=LEFT, pady=5, expand=1) self._npLFrame.pack(fill=X) self._playerFrame = LabelFrame(master, text='Player color:') self._playerFrameEx1 = Frame(self._playerFrame, width=50) self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbColor1 = Radiobutton(self._playerFrame, text='Black', value=BLACK, variable=self._player_color) self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbColor2 = Radiobutton(self._playerFrame, text='White', value=WHITE, variable=self._player_color) self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1) self._playerFrameEx2 = Frame(self._playerFrame, width=50) self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1) self._playerFrame.pack(fill=X) self._rbFrame = LabelFrame(master, text='Next to move:') self._rbFrameEx1 = Frame(self._rbFrame, width=50) self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbTurn1 = Radiobutton(self._rbFrame, text='Black', value=BLACK, variable=self._player_turn) self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbTurn2 = Radiobutton(self._rbFrame, text='White', value=WHITE, variable=self._player_turn) self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbFrameEx2 = Frame(self._rbFrame, width=50) self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1) self._rbFrame.pack(fill=X) self._bcFrame = LabelFrame(master, text='Board configuration') self._wmFrame = Frame(self._bcFrame, borderwidth=0) self._wmLabel = Label(self._wmFrame, text='White men:') self._wmLabel.pack(side=LEFT, padx=7, pady=10) self._wmEntry = Entry(self._wmFrame, width=40, textvariable=self._white_men) self._wmEntry.pack(side=LEFT, padx=10) self._wmFrame.pack() self._wkFrame = Frame(self._bcFrame, borderwidth=0) self._wkLabel = Label(self._wkFrame, text='White kings:') self._wkLabel.pack(side=LEFT, padx=5, pady=10) self._wkEntry = Entry(self._wkFrame, width=40, textvariable=self._white_kings) self._wkEntry.pack(side=LEFT, padx=10) self._wkFrame.pack() self._bmFrame = Frame(self._bcFrame, borderwidth=0) self._bmLabel = Label(self._bmFrame, text='Black men:') self._bmLabel.pack(side=LEFT, padx=7, pady=10) self._bmEntry = Entry(self._bmFrame, width=40, textvariable=self._black_men) self._bmEntry.pack(side=LEFT, padx=10) self._bmFrame.pack() self._bkFrame = Frame(self._bcFrame, borderwidth=0) self._bkLabel = Label(self._bkFrame, text='Black kings:') self._bkLabel.pack(side=LEFT, padx=5, pady=10) self._bkEntry = Entry(self._bkFrame, width=40, textvariable=self._black_kings) self._bkEntry.pack(side=LEFT, padx=10) self._bkFrame.pack() self._bcFrame.pack(fill=X) self._bsState = IntVar() self._bsFrame = Frame(master, borderwidth=0) self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState, text='Start new game with the current setup?') self._bsCheck.pack() self._bsFrame.pack(fill=X) if self._num_players.get() == 1: self._enable_player_color() else: self._disable_player_color() def validate(self): self.wm_list = self._parse_int_list(self._white_men.get()) self.wk_list = self._parse_int_list(self._white_kings.get()) self.bm_list = self._parse_int_list(self._black_men.get()) self.bk_list = self._parse_int_list(self._black_kings.get()) if (self.wm_list == None or self.wk_list == None or self.bm_list == None or self.bk_list == None): return 0 # Error occurred during parsing if not self._all_unique(self.wm_list, self.wk_list, self.bm_list, self.bk_list): return 0 # A repeated index occurred return 1 def apply(self): mgr = self._manager model = mgr.model view = mgr.view state = model.curr_state mgr.player_color = self._player_color.get() mgr.num_players = self._num_players.get() mgr.model.curr_state.to_move = self._player_turn.get() # only reset the BoardView if men or kings have new positions if (sorted(self.wm_list) != sorted(self._orig_white_men) or sorted(self.wk_list) != sorted(self._orig_white_kings) or sorted(self.bm_list) != sorted(self._orig_black_men) or sorted(self.bk_list) != sorted(self._orig_black_kings) or self._bsState.get() == 1): state.clear() sq = state.squares for item in self.wm_list: idx = squaremap[item] sq[idx] = WHITE | MAN for item in self.wk_list: idx = squaremap[item] sq[idx] = WHITE | KING for item in self.bm_list: idx = squaremap[item] sq[idx] = BLACK | MAN for item in self.bk_list: idx = squaremap[item] sq[idx] = BLACK | KING state.to_move = self._player_turn.get() state.reset_undo() view.reset_view(mgr.model) if self._bsState.get() == 1: mgr.filename = None mgr.parent.set_title_bar_filename() state.ok_to_move = True self.result = True self.destroy() def cancel(self, event=None): self.destroy() def _load_entry_box_vars(self): self._white_men = StringVar() self._white_kings = StringVar() self._black_men = StringVar() self._black_kings = StringVar() self._player_color = IntVar() self._player_turn = IntVar() self._num_players = IntVar() self._player_color.set(self._manager.player_color) self._num_players.set(self._manager.num_players) model = self._manager.model self._player_turn.set(model.curr_state.to_move) view = self._manager.view self._white_men.set(', '.join(view.get_positions(WHITE | MAN))) self._white_kings.set(', '.join(view.get_positions(WHITE | KING))) self._black_men.set(', '.join(view.get_positions(BLACK | MAN))) self._black_kings.set(', '.join(view.get_positions(BLACK | KING))) self._orig_white_men = map(int, view.get_positions(WHITE | MAN)) self._orig_white_kings = map(int, view.get_positions(WHITE | KING)) self._orig_black_men = map(int, view.get_positions(BLACK | MAN)) self._orig_black_kings = map(int, view.get_positions(BLACK | KING)) def _disable_player_color(self): self._rbColor1.configure(state=DISABLED) self._rbColor2.configure(state=DISABLED) def _enable_player_color(self): self._rbColor1.configure(state=NORMAL) self._rbColor2.configure(state=NORMAL) def _all_unique(self, *lists): s = set() total_list = [] for i in lists: total_list.extend(i) s = s.union(i) return sorted(total_list) == sorted(s) def _parse_int_list(self, parsestr): try: lst = parsestr.split(',') except AttributeError: return None if lst == ['']: return [] try: lst = [int(i) for i in lst] except ValueError: return None if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)): return None return lst
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 AvionicsLogger(KRCCModule): def __init__(self, root): super().__init__() self.root = root self.exception = None self.list_string = StringVar() self.listbox = Listbox(root, listvariable=self.list_string, font='TkFixedFont', width=30) self.write_cache = '' self.logfile = None self.enable_logging = BooleanVar() self.enable_logging_checkbox = Checkbutton( root, var=self.enable_logging, text='Enable logging', command=self.enable_logging_changed) self.logfile_label = Label(root, text='Logfile name:') self.logfile_name = StringVar() self.logfile_name_entry = Entry(root, textvar=self.logfile_name) self.load() def write(self, string): if self.enable_logging.get() and self.logfile is None: if self.logfile_name.get() == '': self.logfile_name.set('logs/{}.log'.format(time.time())) self.logfile = io.open(self.logfile_name.get(), 'a') self.logfile.write(self.write_cache) self.write_cache = '' self.logfile.write(string) def cache(self, string): self.write_cache += string def enable_logging_changed(self): if not self.enable_logging.get(): self.logfile_name_entry.configure(state=NORMAL) if self.logfile is not None: self.logfile.close() self.logfile = None self.logfile_name.set('') else: self.logfile_name_entry.configure(state=DISABLED) def establish_connection_and_run(self): error = None dots = 0 connection = None while not self.terminate: try: if connection is None: connection = krpc.connect(name=self.name) self.run_with_connection(connection) error = None dots = 0 except Exception as e: if error != e.args[0]: error = e.args[0] print('\n') print(traceback.format_exc()) sys.stdout.write('Retrying') if dots > 80: dots = 0 sys.stdout.write('\n') sys.stdout.write('.') dots += 1 sys.stdout.flush() time.sleep(1) if connection is not None: connection.close() def run_with_connection(self, connection): logging.debug('KRPC connection established') vessel = connection.space_center.active_vessel ref = vessel.orbit.body.reference_frame flight = connection.add_stream(vessel.flight, ref) floats = [ 'mean_altitude', 'atmosphere_density', 'ballistic_coefficient', 'drag_coefficient', ] vectors = [ 'velocity', ] colon_pos_float = max([len(v) for v in floats]) colon_pos_vec = max([len(v) + 3 for v in vectors]) self.listbox.configure(width=max(colon_pos_float, colon_pos_vec) + 11) # Write the log file header. self.cache('time\t' + '\t'.join(floats) + '\t') s = '{}\t' + '\t'.join('{{}}[{}]'.format(x) for x in [0, 1, 2]) self.cache('\t'.join( s.format(*(v for _ in [0, 1, 2, 3])) for v in vectors)) self.cache('\n') log_sample_interval = 0.01 next_log_sample = time.time() while not self.terminate: values = [time.time()] strings = [] for name in floats: value = flight().__getattribute__(name) values.append(value) padding = colon_pos_float - len(name) + 9 format_string = '{{}}: {{:>{}.3f}}'.format(padding) strings.append(format_string.format(name, value)) for name in vectors: value = flight().__getattribute__(name) magnitude = value[0] padding = colon_pos_float - len(name) + 9 format_string = '{{}}: {{:>{}.3f}}'.format(padding) strings.append(format_string.format(name, magnitude)) values.append(magnitude) padding = colon_pos_vec - len(name) + 2 format_string = '{{}}[{{}}]: {{:>{}.3f}}'.format(padding) for i in [0, 1, 2]: values.append(value[i]) strings.append(format_string.format(name, i, value[i])) if self.enable_logging.get() and time.time() > next_log_sample: self.write('\t'.join(['{}'.format(v) for v in values]) + '\n') next_log_sample = time.time() + log_sample_interval self.list_string.set(tuple(strings)) def run(self): try: self.establish_connection_and_run() self.logfile_name_entry.destroy() self.logfile_label.destroy() self.enable_logging_checkbox.destroy() self.listbox.destroy() except RuntimeError: # Should only happen when KeyboardInterrupt is thrown in the MainThread. pass if self.logfile is not None: self.logfile.close() @property def name(self): return 'Avionics Logger' def load(self): self.listbox.pack(side=LEFT, fill=BOTH) self.logfile_label.pack(side=LEFT, anchor=NW) self.logfile_name_entry.pack(side=LEFT, anchor=NE, fill=X, expand=True) self.enable_logging_checkbox.pack(side=LEFT, anchor=NW)
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.initUI() self.setGeometry() self.component = NewComponent() def setGeometry(self): x = 300 y = 100 self.master.geometry("400x300+%d+%d" % (x, y)) self.master.update() def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10 + self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10 + self.labelName.winfo_width() + 10, y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = [ 'UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized' ] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10 + self.labelCategory.winfo_width() + 10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton( self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10 + self.getImageButton.winfo_width() + 10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230) # open file picker for selecting an icon def getImage(self): ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')), ('All files', '*')] self.component.imgFile = askopenfilename(filetypes=ftypes, title="Select an Icon file") # update component name and image name for component by lowercasing first letter def nameChanged(self, sv): s = sv.get() self.component.compName = s self.component.compImgName = s[:1].lower() + s[1:] if s else '' self.imgNameVar.set('imageName: %s' % self.component.compImgName) # tries to create component def create(self): # sets parameters for new component based on input values self.component.visibleComponent = bool(self.cbVar.get()) self.component.resizeImage = bool(self.resizeVar.get()) self.component.category = self.catBox.get().upper() self.component.compName = self.nameField.get() try: # check if component already exists try: open( '../../components/src/com/google/appinentor/components/runtime/%s.java', 'r') tkMessageBox.showerror( "Duplicate Component", "%s already exists" % self.component.compName) # if doesnt exist will raise error except IOError: # check for name input if not self.component.compImgName: tkMessageBox.showerror("Missing Name", "Please enter component name") return #check for category selection if not self.component.category: tkMessageBox.showerror("Missing Category", "Please select a category") return # check if selected an icon if not self.component.imgFile: tkMessageBox.showerror("Missing Icon", "Please select an icon image") return # copy image file to folder, can get error if user checked resize and doest have PIL installed try: self.component.copyImageToFolder() except ImportError, e: tkMessageBox.showerror( "Unable to import PIL", "Please install PIL or unselect checkbox") return # add references to the image file, can get error if component already exists try: self.component.addImageReference() except DuplicateError, e: tkMessageBox.showerror( "Duplicate Component", "%s already exists" % self.component.compName) return # will create mock component if is visible and add references to SimpleComponentDescriptor self.component.createMockComponent() # will create the actual component file self.component.createComponent() tkMessageBox.showinfo('Success', 'Component created successfully')
def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10 + self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10 + self.labelName.winfo_width() + 10, y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = [ 'UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized' ] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10 + self.labelCategory.winfo_width() + 10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton( self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10 + self.getImageButton.winfo_width() + 10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230)
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 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)
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
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 View(Toplevel): def __init__(self, model): self.model = model self.model_config = self.model.get_config() self.channels_num = 0 self.channels_amount = 0 self.root = Tk() self.root.resizable(width=FALSE, height=FALSE) self.root.title("RaaS. event_proxy configurator") #: self.root.iconbitmap('resourse/vit.ico') self.config_route = self.model.get_config_route() self.panelFrame = Frame(self.root, height=60) self.canvas = Canvas(self.root, borderwidth=0) self.textFrame = Frame(self.canvas, height=340, width=600) self.mainFrame = LabelFrame(self.root, width=200, text="Main:", height=340, relief=RAISED, borderwidth=1) self.chanelFrame = LabelFrame(self.root, width=370, text="Channels:", height=340, relief=RAISED, borderwidth=1) #: self.vsb = Scrollbar(self.root, orient="horizontal", #: command=self.canvas.xview) #:self.canvas.configure(xscrollcommand=self.vsb.set) #:self.vsb.pack(side="bottom", fill="x") self.canvas.pack(side="bottom", fill="both", expand=True) self.canvas.configure(scrollregion=self.canvas.bbox("all")) self.root.protocol("WM_DELETE_WINDOW", self.quit_handler) self.tabs = Notebook(self.root) self.in_channel_text = [] self.out_port_text = [] self.out_channel_text = [] self.c = self.model.get_channels().keys() self.channels_len = len(self.model.get_channels()) #:print self.model.get_channels() self.panelFrame.pack(side='top', fill='x') self.textFrame.pack(side='bottom', fill='both', expand=1) self.mainFrame.place(x=10, y=60) self.chanelFrame.place(x=220, y=60) self.tabs.place(x=230, y=80) x = (self.root.winfo_screenwidth() - self.root.winfo_reqwidth()) / 2 y = (self.root.winfo_screenheight() - self.root.winfo_reqheight()) / 2 self.root.geometry("+%d+%d" % (x-150, y-150)) for i in range(self.channels_len): self.channels_num += 1 self.channels_amount += 1 self.f1 = Frame(self.tabs, height=290, width=350) self.tabs.add(self.f1, text='Channel {0}'.format(i + 1)) self.in_channel = Label(self.f1, text="In channel") self.out_port = Label(self.f1, text="Out port") self.out_channel = Label(self.f1, text="Out channel") self.in_channel_text.append(Entry(self.f1, width=20, bd=3)) self.in_channel_text[i].insert(0, self.c[i]) self.out_port_text.append(Entry(self.f1, width=20, bd=3)) self.out_port_text[i].insert(0, self.model.get_channels()[ self.c[i]].out_port) self.out_channel_text.append(Entry(self.f1, width=20, bd=3)) self.out_channel_text[i].insert(0, self.model.get_channels()[ self.c[i]].out_channel) self.in_channel.place(x=5, y=10) self.in_channel_text[i].place(x=5, y=30) self.out_port.place(x=5, y=50) self.out_port_text[i].place(x=5, y=70) self.out_channel.place(x=5, y=90) self.out_channel_text[i].place(x=5, y=110) self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format( self.channels_amount), command= lambda: self.del_channel(i)) self.del_ch_btn.bind("<Button-1>") self.del_ch_btn.place(x=5, y=140, width=100, height=30) self.server_host_label = Label(self.root, text="Server host") self.server_port_label = Label(self.root, text="Server port") self.raas_port_label = Label(self.root, text="Raas port") self.encoding_label = Label(self.root, text='Encoding') self.levenshtein_distance_label = Label(self.root, text='Levenshtein distance') self.window_time_label = Label(self.root, text='Window time') self.server_host_entity = Entry(self.root, width=20, bd=3) self.server_host_entity.insert(0, self.model_config['server_host']) self.server_port_entity = Entry(self.root, width=20, bd=3) self.server_port_entity.insert(0, self.model_config['server_port']) self.raas_port_entity = Entry(self.root, width=20, bd=3) self.raas_port_entity.insert(0, self.model_config['raas_port']) self.encoding_entry = Entry(self.root, width=20, bd=3) self.encoding_entry.insert(0, self.model_config['encoding']) self.levenshtein_distance_entry = Entry(self.root, width=20, bd=3) self.levenshtein_distance_entry.insert(0, self.model_config[ 'levenshtein_distance']) self.window_time_entry = Entry(self.root, width=20, bd=3) self.window_time_entry.insert(0, self.model_config['window_time']) self.var = IntVar() self.cfg_debug = self.model_config['debug'] if self.cfg_debug == 'True': self.var.set(1) else: self.var.set(0) self.check_debug = Checkbutton(self.root, text='Debug', variable=self.var) self.filter_var = IntVar() self.cfg_use_filter = self.model_config['use_filter'] if self.cfg_use_filter == 'True': self.filter_var.set(1) else: self.filter_var.set(0) self.check_use_filter = Checkbutton(self.root, text='Use filter', variable=self.filter_var) self.addBtn = Button(self.panelFrame, text='Add channel') self.saveBtn = Button(self.panelFrame, text='Save') self.quitBtn = Button(self.panelFrame, text='Quit') self.saveBtn.bind("<Button-1>", self.SaveFile) self.quitBtn.bind("<Button-1>", self.Quit) self.addBtn.bind("<Button-1>", self.add_channel) self.saveBtn.place(x=10, y=10, width=40, height=40) self.quitBtn.place(x=60, y=10, width=40, height=40) self.addBtn.place(x=220, y=10, width=80, height=40) self.server_host_label.place(x=20, y=80) self.server_host_entity.place(x=20, y=100) self.server_port_label.place(x=20, y=120) self.server_port_entity.place(x=20, y=140) self.raas_port_label.place(x=20, y=160) self.raas_port_entity.place(x=20, y=180) self.encoding_label.place(x=20, y=200) self.encoding_entry.place(x=20, y=220) self.check_debug.place(x=20, y=250) self.f = Frame(self.root, height=1, width=190, bg='grey') self.f.place(x=15, y=275) self.levenshtein_distance_label.place(x=20, y=280) self.levenshtein_distance_entry.place(x=20, y=300) self.window_time_label.place(x=20, y=320) self.window_time_entry.place(x=20, y=340) self.check_use_filter.place(x=20, y=370) def del_channel(self, numb): rwidth = self.root.winfo_width() rheight = self.root.winfo_height() if self.channels_num > 6: self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 65) self.root.geometry("%dx%d" % (rwidth - 65, rheight)) if self.channels_num == 6: self.chanelFrame.config(width=self.chanelFrame.winfo_width() - 20) self.root.geometry("%dx%d" % (rwidth - 20, rheight)) dvar = self.tabs.tabs().index(self.tabs.select()) self.in_channel_text.pop(dvar) self.out_channel_text.pop(dvar) self.out_port_text.pop(dvar) self.channels_num -= 1 self.tabs.forget(self.tabs.select()) tabs_list = self.tabs.tabs() self.root.update() def add_channel(self, env): if self.channels_num > 15: tkMessageBox.showerror('Error', 'You can not add more than 16 channels') return False rwidth = self.root.winfo_width() rheight = self.root.winfo_height() if self.channels_num == 5: self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 20) self.root.geometry("%dx%d" % (rwidth + 20, rheight)) if self.channels_num > 5: self.chanelFrame.config(width=self.chanelFrame.winfo_width() + 65) self.root.geometry("%dx%d" % (rwidth + 65, rheight)) self.f1 = Frame(self.tabs, height=290, width=350) self.tabs.add(self.f1, text='Channel {0}'.format(self.channels_amount + 1)) self.in_channel = Label(self.f1, text="In channel") self.out_port = Label(self.f1, text="Out port") self.out_channel = Label(self.f1, text="Out channel") self.in_channel_text.append(Entry(self.f1, width=20, bd=3)) self.out_port_text.append(Entry(self.f1, width=20, bd=3)) self.out_channel_text.append(Entry(self.f1, width=20, bd=3)) self.in_channel.place(x=5, y=10) self.in_channel_text[self.channels_num].place(x=5, y=30) self.out_port.place(x=5, y=50) self.out_port_text[self.channels_num].place(x=5, y=70) self.out_channel.place(x=5, y=90) self.out_channel_text[self.channels_num].place(x=5, y=110) self.del_ch_btn = Button(self.f1, text='Delete channel {0}'.format( self.channels_num + 1), command= lambda: self.del_channel(self.channels_num)) self.del_ch_btn.bind("<Button-1>") self.del_ch_btn.place(x=5, y=140, width=100, height=30) self.channels_num += 1 self.channels_amount += 1 def Quit(self, env): if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'): self.SaveFile(env) self.root.destroy() def quit_handler(self): if tkMessageBox.askyesno('Quit', 'Whant to save config before quit?'): self.save_handler() self.root.destroy() def validate_int(self, var, text, channel): if not var.isdigit(): tkMessageBox.showerror("Error", "Error in {1}. Value of field '{0}' must be int.".format(text, channel)) return False return True def validate_empty(self, var, text): if not var: tkMessageBox.showerror("Error", "Field {0} must be not empty.".format(text)) return False return True def validate_channels(self): if not self.channels_num: tkMessageBox.showerror("Error", "You must add at least one channel") return False return True def validate_change_field(self): self.validating_config = self.model.get_updated_config() self.flag = False if self.server_host_entity.get() != str(self.validating_config['server_host']): self.flag = True if self.server_port_entity.get() != str(self.validating_config['server_port']): self.flag = True if self.raas_port_entity.get() != str(self.validating_config['raas_port']): self.flag = True if self.encoding_entry.get() != str(self.validating_config['encoding']): self.flag = True if str(self.levenshtein_distance_entry.get()) != str(self.validating_config['levenshtein_distance']): self.flag = True if str(self.window_time_entry.get()) != str(self.validating_config['window_time']): self.flag = True self.tmp = IntVar() if self.validating_config['debug'] == 'True': self.tmp.set(1) else: self.tmp.set(0) if self.tmp.get() != self.var.get(): self.flag = True self.tmp_filter = IntVar() if self.validating_config['use_filter'] == 'True': self.tmp_filter.set(1) else: self.tmp_filter.set(0) if self.tmp_filter.get() != self.filter_var.get(): self.flag = True #TODO: add validating of channels if self.channels_num != self.channels_amount or self.channels_len != self.channels_num: return True for i in range(self.channels_num): if self.in_channel_text[i].get() != str(self.c[i]): self.flag = True if self.out_port_text[i].get() != str(self.model.get_channels()[ self.c[i]].out_port): self.flag = True if self.out_channel_text[i].get() != str(self.model.get_channels()[ self.c[i]].out_channel): self.flag = True return self.flag def validate_all(self): #if not self.validate_change_field(): # return False if not self.validate_channels(): return False if not self.validate_empty(self.server_host_entity.get(), 'Server host'): return False if not self.validate_empty(self.encoding_entry.get(), 'Encoding'): return False if not self.validate_empty(self.levenshtein_distance_entry.get(), 'Levenshtein distance'): return False if not self.validate_int(self.server_port_entity.get(), 'Server port', ''): return False if not self.validate_int(self.raas_port_entity.get(), 'Raas port', ''): return False if not self.validate_int(self.levenshtein_distance_entry.get(), 'Levenshtein distance', ''): return False if not self.validate_int(self.window_time_entry.get(), 'Window time', ''): return False for i in range(self.channels_num): if not self.validate_int(self.in_channel_text[i].get(), 'In channel', ' Channel {0}'.format(i + 1)): return False if not self.validate_int(self.out_port_text[i].get(), 'Out port', ' Channel {0}'.format(i + 1)): return False if not self.validate_int(self.out_channel_text[i].get(), 'Out channel', ' Channel {0}'.format(i + 1)): return False return True def SaveFile(self, env): self.save_handler() def save_handler(self): if not self.validate_all(): return False config = ConfigParser.RawConfigParser() config.add_section('Main') config.set('Main', 'server_host', self.server_host_entity.get()) config.set('Main', 'server_port', self.server_port_entity.get()) config.set('Main', 'raas_port', self.raas_port_entity.get()) result = 'False' if self.var.get(): result = 'True' config.set('Main', 'debug', result) config.set('Main', 'encoding', self.encoding_entry.get()) config.set('Main', 'levenshtein_distance', self.levenshtein_distance_entry.get()) config.set('Main', 'window_time', self.window_time_entry.get()) result_filter = 'False' if self.filter_var.get(): result_filter = 'True' config.set('Main', 'use_filter', result_filter) for i in range(self.channels_num): config.add_section('Channel{0}'.format(i + 1)) config.set('Channel{0}'.format(i + 1), 'in_channel', self.in_channel_text[i].get()) config.set('Channel{0}'.format(i + 1), 'out_port', self.out_port_text[i].get()) config.set('Channel{0}'.format(i + 1), 'out_channel', self.out_channel_text[i].get()) with open(self.config_route, 'wb') as configfile: config.write(configfile) tkMessageBox.showinfo("Info", "Successfully saved.") def run(self): self.root.mainloop()
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 body(self, master): self._npLFrame = LabelFrame(master, text='No. of players:') self._npFrameEx1 = Frame(self._npLFrame, width=30) self._npFrameEx1.pack(side=LEFT, pady=5, expand=1) self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)', value=0, variable=self._num_players, command=self._disable_player_color) self._npButton1.pack(side=LEFT, pady=5, expand=1) self._npButton2 = Radiobutton(self._npLFrame, text='One', value=1, variable=self._num_players, command=self._enable_player_color) self._npButton2.pack(side=LEFT, pady=5, expand=1) self._npButton3 = Radiobutton(self._npLFrame, text='Two', value=2, variable=self._num_players, command=self._disable_player_color) self._npButton3.pack(side=LEFT, pady=5, expand=1) self._npFrameEx2 = Frame(self._npLFrame, width=30) self._npFrameEx2.pack(side=LEFT, pady=5, expand=1) self._npLFrame.pack(fill=X) self._playerFrame = LabelFrame(master, text='Player color:') self._playerFrameEx1 = Frame(self._playerFrame, width=50) self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbColor1 = Radiobutton(self._playerFrame, text='Black', value=BLACK, variable=self._player_color) self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbColor2 = Radiobutton(self._playerFrame, text='White', value=WHITE, variable=self._player_color) self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1) self._playerFrameEx2 = Frame(self._playerFrame, width=50) self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1) self._playerFrame.pack(fill=X) self._rbFrame = LabelFrame(master, text='Next to move:') self._rbFrameEx1 = Frame(self._rbFrame, width=50) self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbTurn1 = Radiobutton(self._rbFrame, text='Black', value=BLACK, variable=self._player_turn) self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbTurn2 = Radiobutton(self._rbFrame, text='White', value=WHITE, variable=self._player_turn) self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbFrameEx2 = Frame(self._rbFrame, width=50) self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1) self._rbFrame.pack(fill=X) self._bcFrame = LabelFrame(master, text='Board configuration') self._wmFrame = Frame(self._bcFrame, borderwidth=0) self._wmLabel = Label(self._wmFrame, text='White men:') self._wmLabel.pack(side=LEFT, padx=7, pady=10) self._wmEntry = Entry(self._wmFrame, width=40, textvariable=self._white_men) self._wmEntry.pack(side=LEFT, padx=10) self._wmFrame.pack() self._wkFrame = Frame(self._bcFrame, borderwidth=0) self._wkLabel = Label(self._wkFrame, text='White kings:') self._wkLabel.pack(side=LEFT, padx=5, pady=10) self._wkEntry = Entry(self._wkFrame, width=40, textvariable=self._white_kings) self._wkEntry.pack(side=LEFT, padx=10) self._wkFrame.pack() self._bmFrame = Frame(self._bcFrame, borderwidth=0) self._bmLabel = Label(self._bmFrame, text='Black men:') self._bmLabel.pack(side=LEFT, padx=7, pady=10) self._bmEntry = Entry(self._bmFrame, width=40, textvariable=self._black_men) self._bmEntry.pack(side=LEFT, padx=10) self._bmFrame.pack() self._bkFrame = Frame(self._bcFrame, borderwidth=0) self._bkLabel = Label(self._bkFrame, text='Black kings:') self._bkLabel.pack(side=LEFT, padx=5, pady=10) self._bkEntry = Entry(self._bkFrame, width=40, textvariable=self._black_kings) self._bkEntry.pack(side=LEFT, padx=10) self._bkFrame.pack() self._bcFrame.pack(fill=X) self._bsState = IntVar() self._bsFrame = Frame(master, borderwidth=0) self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState, text='Start new game with the current setup?') self._bsCheck.pack() self._bsFrame.pack(fill=X) if self._num_players.get() == 1: self._enable_player_color() else: self._disable_player_color()
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)
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack(fill=BOTH, expand=1) self.initUI() self.setGeometry() self.component = NewComponent() def setGeometry(self): x = 300 y = 100 self.master.geometry("400x300+%d+%d" % (x, y)) self.master.update() def initUI(self): #setup title self.master.title("Component Creator") self.style = Style() self.style.theme_use("clam") #indicator label self.labelName = Label(self, text="Component Name:") self.labelName.place(x=10, y=10) self.master.update() # create variable and namefield for input of component name sv = StringVar() sv.trace("w", lambda name, index, mode, sv=sv: self.nameChanged(sv)) self.nameField = Entry(self, textvariable=sv) self.nameField.place(x=10+self.labelName.winfo_width() + 10, y=10) self.master.update() # label for image name that will show img name for a given component name self.imgNameVar = StringVar() self.imgNameVar.set('imageName:') self.labelImageName = Label(self, textvariable=self.imgNameVar) self.labelImageName.place(x=10+self.labelName.winfo_width()+10,y=40) # checkbox for visible component or not self.cbVar = IntVar() self.cb = Checkbutton(self, text="Visible Component", variable=self.cbVar) self.cb.place(x=10, y=70) # dropdown list for category self.labelCategory = Label(self, text="Category:") self.labelCategory.place(x=10, y=110) self.master.update() acts = ['UserInterface', 'Layout', 'Media', 'Animation', 'Sensors', 'Social', 'Storage', 'Connectivity', 'LegoMindStorms', 'Experimental', 'Internal', 'Uninitialized'] self.catBox = Combobox(self, values=acts) self.catBox.place(x=10+self.labelCategory.winfo_width()+10, y=110) # button to select icon image self.getImageButton = Button(self, text="Select icon", command=self.getImage) self.getImageButton.place(x=10, y=150) self.master.update() # explanation for resizing self.resizeVar = IntVar() self.resizeCB = Checkbutton(self, text="ON=Resize Image (Requires PIL)\nOFF=Provide 16x16 Image", variable=self.resizeVar) self.resizeCB.place(x=10+self.getImageButton.winfo_width()+10, y=150) # create button self.createButton = Button(self, text="Create", command=self.create) self.createButton.place(x=10, y=230) #cancel button self.cancelButton = Button(self, text="Cancel", command=self.quit) self.cancelButton.place(x=200, y=230) # open file picker for selecting an icon def getImage(self): ftypes = [('All Picture Files', ('*.jpg', '*.png', '*.jpeg', '*.bmp')), ('All files', '*')] self.component.imgFile = askopenfilename(filetypes=ftypes, title="Select an Icon file") # update component name and image name for component by lowercasing first letter def nameChanged(self, sv): s = sv.get() self.component.compName = s self.component.compImgName = s[:1].lower() + s[1:] if s else '' self.imgNameVar.set('imageName: %s' % self.component.compImgName) # tries to create component def create(self): # sets parameters for new component based on input values self.component.visibleComponent = bool(self.cbVar.get()) self.component.resizeImage = bool(self.resizeVar.get()) self.component.category = self.catBox.get().upper() self.component.compName = self.nameField.get() try: # check if component already exists try: open('../../components/src/com/google/appinentor/components/runtime/%s.java', 'r') tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName) # if doesnt exist will raise error except IOError: # check for name input if not self.component.compImgName: tkMessageBox.showerror("Missing Name","Please enter component name") return #check for category selection if not self.component.category: tkMessageBox.showerror("Missing Category","Please select a category") return # check if selected an icon if not self.component.imgFile: tkMessageBox.showerror("Missing Icon","Please select an icon image") return # copy image file to folder, can get error if user checked resize and doest have PIL installed try: self.component.copyImageToFolder() except ImportError, e: tkMessageBox.showerror("Unable to import PIL","Please install PIL or unselect checkbox") return # add references to the image file, can get error if component already exists try: self.component.addImageReference() except DuplicateError, e: tkMessageBox.showerror("Duplicate Component","%s already exists" % self.component.compName) return # will create mock component if is visible and add references to SimpleComponentDescriptor self.component.createMockComponent() # will create the actual component file self.component.createComponent() tkMessageBox.showinfo('Success', 'Component created successfully')
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 search_text_dialog(widget,widget_scroll): widget.tag_configure("search", background="green") def color_tagger_thread(name, back, case): start = 1.0 while start != widget.index(CURRENT): pos = widget.search(name, start, stopindex=END, nocase=case) b = pos.find('.') pos2 = pos[b+1:] if not pos: break pos2 = pos[:b]+'.'+str(int(pos2)+int(countVar.get())) widget.tag_add("search", pos, pos2) start = pos + "+1c" def text_finder(*arg): if t_findtext_old.get() != t_findtext.get() or t_match_case_old != t_match_case: widget.tag_remove("search",1.0,END) widget.tag_remove("sel",1.0,END) ftext = t_findtext.get() t_findtext_old.set(ftext) t_match_case_old.set(t_match_case) if t_match_case.get() == 1: nocase = 0 else: nocase = 1 if t_search_backward.get() == 1: startVar,stopindex, back = start.get(),'1.0', True else: startVar,stopindex, back = start.get(), 'END', False if t_wrap_around.get() == 0: pos = widget.search(ftext, startVar, stopindex=stopindex, count=countVar, backwards=back, nocase=nocase) else: pos = widget.search(ftext, startVar, count=countVar, backwards=back, nocase=nocase) if pos != '': widget.see(pos) b = pos.find('.') pos2 = pos[b+1:] pos2 = pos[:b]+'.'+str(int(pos2)+int(countVar.get())) widget.tag_add(SEL, pos, pos2) widget.tag_raise("sel") if back == True: start.set(pos) else: start.set(pos2) color_tagger_thread(ftext,back,nocase) else: T_ins_warning(widget, widget_scroll, 'Nothing found') topwin = Toplevel() set_winicon(topwin,'icon_grey') topwin.title("Search dialog") topwin.minsize(600,80) topwin.resizable(FALSE,FALSE) frame4 = Frame(topwin, height=100,width=120, relief=SUNKEN,bg='') frame4.pack_propagate(0) frame4.pack(side=RIGHT) frame1 = Frame(topwin, height=40,width=480, relief=SUNKEN,bg='') frame1.pack_propagate(0) frame1.pack(side=TOP) frame2 = Frame(topwin, height=40,width=480, relief=SUNKEN,bg='') frame2.pack_propagate(0) frame2.pack(side=TOP) frame3 = Frame(topwin, height=40,width=480, relief=SUNKEN,bg='') frame3.pack_propagate(0) frame3.pack(side=TOP) start = StringVar() countVar = StringVar() t_match_case = IntVar() t_match_case_old = IntVar() t_wrap_around = IntVar() t_findtext = StringVar() t_findtext_old = StringVar() t_search_backward = IntVar() t_findtext.set('') t_findtext_old.set('') t_match_case.set(0) t_match_case_old.set(0) t_wrap_around.set(1) t_search_backward.set(0) start.set("1.0") Label(frame1, text="Find text: ").pack(side=LEFT) tEntry = Entry(frame1,textvariable=t_findtext,width=50) tEntry.pack(side=LEFT) tEntry.focus_set() Label(frame2, text="Options: ").pack(side=LEFT) Checkbutton(frame2, text="Match case", variable=t_match_case).pack(side=LEFT,padx=5) Checkbutton(frame2, text="Wrap around", variable=t_wrap_around).pack(side=LEFT,padx=5) Checkbutton(frame2, text="Search backwards", variable=t_search_backward).pack(side=LEFT,padx=5) def close_func(*arg): widget.tag_remove("search",1.0,END) topwin.destroy() button = Button(frame4, text='Find', command=text_finder).pack(side=TOP,pady=15, padx=10) button = Button(frame4, text='Close', command=close_func).pack(side=TOP, padx=10) topwin.protocol('WM_DELETE_WINDOW', close_func) topwin.bind('<Escape>', close_func) topwin.bind('<Return>', text_finder)
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()
def __init__(self): Frame.__init__(self) self.style = Style() self.style.theme_use("default") self.master.title("Log viewer") self.pack(fill=BOTH, expand=True) self.used = [] # List of currently plotted series ([str]) self.series = {} # List of all series ({str -> [number]}) self.names = [] # List of all nodes in tree view ([str]) self.queues = [] # List of all queues ([str]) self.logs = {} # List of all text logs ({str -> [str]}) self.rowconfigure(1, weight=1) self.columnconfigure(6, weight=3) self.columnconfigure(11, weight=1) # Series selection takes row 1-2, col 0-2 self.series_ui = Treeview(self) self.series_ui.grid(row=1, column=0, columnspan=2, rowspan=2, sticky=N+S) self.series_ui.configure(show="tree") self.series_ui.bind("<Double-Button-1>", self.onselect) self.series_ui.tag_configure("graphall", foreground="#070") self.series_ui.tag_configure("graphnone", foreground="#000") self.series_ui.tag_configure("graphsome", foreground="#007") series_ui_scroll = Scrollbar(self, command=self.series_ui.yview, orient=VERTICAL) series_ui_scroll.grid(row=1, column=2, rowspan=2, sticky=N+S) self.series_ui["yscrollcommand"] = series_ui_scroll.set # The plot takes row 1-2, col 3-6 move_mode = StringVar() move_mode.set("pan") show_path = IntVar() show_path.set(0) event_bars = IntVar() event_bars.set(1) show_debug = IntVar() show_debug.set(1) show_error = IntVar() show_error.set(1) show_warning = IntVar() show_warning.set(1) show_info = IntVar() show_info.set(1) self.plot = HackPlot(self, move_mode, show_path, event_bars, [(show_debug, "[DEBUG]"), (show_error, "[ERROR]"), (show_warning, "[WARNING]"), (show_info, "[INFO]")]) self.plot.canvas.grid(row=1, column=3, columnspan=4, rowspan=2, sticky=N+S+E+W) # Text logs take row 1-2, col 7-12 self.plot.listbox.grid(row=1, column=7, columnspan=5, sticky=N+S+E+W) listbox_yscroll = Scrollbar(self, command=self.plot.listbox.yview, orient=VERTICAL) listbox_yscroll.grid(row=1, column=12, sticky=N+S) self.plot.listbox["yscrollcommand"] = listbox_yscroll.set listbox_xscroll = Scrollbar(self, command=self.plot.listbox.xview, orient=HORIZONTAL) listbox_xscroll.grid(row=2, column=7, columnspan=5, sticky=E+W) self.plot.listbox["xscrollcommand"] = listbox_xscroll.set # Controls take row 0, col 0-12 Button(self, text="Load Directory", command=self.loaddir).grid(row=0, column=0) Button(self, text="Load File", command=self.loadfile).grid(row=0, column=1) Button(self, text="Fit X", command=self.plot.fit_x).grid(row=0, column=3, sticky=W) Button(self, text="Fit Y", command=self.plot.fit_y).grid(row=0, column=4, sticky=W) Button(self, text="Fit Auto", command=self.plot.fit_auto).grid(row=0, column=5, sticky=W) Button(self, text="Fit Tele", command=self.plot.fit_tele).grid(row=0, column=6, sticky=W) # Plot controls in a subframe to manage padding so it doesn't look awful move_mode_control = Frame(self, padx=10) Radiobutton(move_mode_control, text="Pan", value="pan", variable=move_mode).grid(row=0, column=0, sticky=W) Radiobutton(move_mode_control, text="Zoom In", value="zoomin", variable=move_mode).grid(row=0, column=1, sticky=W) Radiobutton(move_mode_control, text="Zoom Out", value="zoomout", variable=move_mode).grid(row=0, column=2, sticky=W) move_mode_control.grid(row=0, column=7, sticky=W) Checkbutton(self, text="Event Bars", variable=event_bars, command=self.plot.show_textlogs).grid(row=0, column=8, sticky=W) Checkbutton(self, text="Debug", variable=show_debug, command=self.plot.show_textlogs).grid(row=0, column=9, sticky=W) Checkbutton(self, text="Error", variable=show_error, command=self.plot.show_textlogs).grid(row=0, column=10, sticky=W) Checkbutton(self, text="Warning", variable=show_warning, command=self.plot.show_textlogs).grid(row=0, column=11, sticky=W) Checkbutton(self, text="Info", variable=show_info, command=self.plot.show_textlogs).grid(row=0, column=12, sticky=W) Checkbutton(self, text="Directories", variable=show_path, command=self.plot.show_textlogs).grid(row=0, column=13, sticky=E)
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'])
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 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()
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 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 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 __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 __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 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 AppGui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.init_ui() def run(self): while True: tmpPath = "%s-%05d.png" % (os.path.splitext(self.path)[0], randint(1, 99999)) if not os.path.exists(tmpPath): break mem = int(self.membershipPassScale.scale.get()) ins = int(self.intensifyPassScale.scale.get()) con = self.convolveCheckbutton.instate(['selected']) in2 = int(self.secondIntensifyPassScale.scale.get()) thr = float(int(self.thresholdScale.scale.get())) / 10 pow = int(self.powerScale.scale.get()) process_image(self.path, tmpPath, mem, ins, con, in2, thr, pow) f = pylab.figure() for n, fname in enumerate((tmpPath, self.path)): image = Image.open(fname).convert("L") arr = np.asarray(image) f.add_subplot(1, 2, n) pylab.imshow(arr, cmap=cm.Greys_r) if con: pylab.title("membership passes=%d, 1st intensify passes=%d, convolve=Yes, 2nd intensify passes=%d, " "threshold=%0.1f, power=%d" % (mem, ins, in2, thr, pow)) else: pylab.title("membership passes=%d, 1st intensify passes=%d, convolve=No, " "threshold=%0.1f, power=%d" % (mem, ins, thr, pow)) pylab.show() def open_file(self): self.path = tkFileDialog.askopenfilename(parent=self, filetypes=[("PNG Images", "*.png")]) if self.path != '': self.preview_input_file(self.path) self.runButton.configure(state="normal") else: tkMessageBox.showerror("Error", "Could not open file") def preview_input_file(self, path): self.img = Image.open(path) imgTk = ImageTk.PhotoImage(self.img) self.label = Label(image=imgTk) self.label.image = imgTk self.label.place(x=400, y=50, width=self.img.size[0], height=self.img.size[1]) def center_window(self): w = 1024 h = 600 x = (self.parent.winfo_screenwidth() - w) / 2 y = (self.parent.winfo_screenheight() - h) / 2 self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y)) def init_ui(self): self.parent.title("Image enhancement") self.pack(fill=BOTH, expand=1) self.center_window() openFileButton = Button(self, text="Choose image", command=self.open_file) openFileButton.place(x=50, y=50) self.runButton = Button(self, text="Enhance", command=self.run, state="disabled") self.runButton.place(x=200, y=50) membershipLabel = Label(text="Membership passes:") membershipLabel.place(x=50, y=120) self.membershipPassScale = LabeledScale(self, from_=1, to=10) self.membershipPassScale.place(x=250, y=100) intensifyLabel = Label(text="1st intensify passes:") intensifyLabel.place(x=50, y=170) self.intensifyPassScale = LabeledScale(self, from_=1, to=10) self.intensifyPassScale.place(x=250, y=150) convolveLabel = Label(text="Convolve:") convolveLabel.place(x=50, y=220) self.convolveCheckbutton = Checkbutton(self) self.convolveCheckbutton.place(x=250, y=220) self.convolveCheckbutton.invoke() secondIntensifyLabel = Label(text="2nd intensify passes:") secondIntensifyLabel.place(x=50, y=270) self.secondIntensifyPassScale = LabeledScale(self, from_=1, to=10) self.secondIntensifyPassScale.place(x=250, y=250) thresholdLabel = Label(text="Threshold:") thresholdLabel.place(x=50, y=320) self.thresholdScale = LabeledScale(self, from_=1, to=10) self.thresholdScale.place(x=250, y=300) self.thresholdScale.scale.set(5) powerLabel = Label(text="Power:") powerLabel.place(x=50, y=370) self.powerScale = LabeledScale(self, from_=2, to=5) self.powerScale.place(x=250, y=350)
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 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_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 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 __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.parent.title("Jo Ion Picker") self.pack(fill=BOTH, expand=1) self.compounds = deisotope(filename=input_file) self.error_label = Label(self, text="Error in ppm") self.error_label.place(x=20, y=730) self.entry = Entry(self, text='error in ppm') self.entry.place(x=20, y=750) self.entry.insert(10,'5') self.b = Button(self, text="ReCalc Error", width=15, \ command=self.callback) self.b.place(x=20, y=770) self.b_output = Button(self, text="Export", width=10, command=self.write_output) self.b_output.place(x=20, y=800) #self.b_output = Button(self, text="Allowed", width=10, command=self.only_allowed_ions) #self.b_output.place(x=20, y=830) self.gaps=IntVar() self.check_gaps = Checkbutton(self, text='Remove Gaps', variable=self.gaps,onvalue=1, offvalue=0, command=self.remove_gaps_call) #self.check.pack() self.check_gaps.place(x=20, y=830) self.scrollbar = Scrollbar(self, orient=VERTICAL) self.lb = Listbox(self, height=46, yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.lb.yview) self.scrollbar.pack(side=LEFT, fill=Y) for compound in self.compounds: print "found", compound.get_base_peak() mzs = compound.get_mz_list() num_mzs = len(mzs) entry = str(mzs[0]) + " " + str(num_mzs) self.lb.insert(END, entry) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=20, y=20) self.var = StringVar() #self.label = Label(self, text=0, textvariable=self.var) #self.label.place(x=20, y=710) self.mz_label = Label(self, text="M/Z Num Ions") self.mz_label.place(x=20, y=0) f = Figure(figsize=(8,11), dpi=100) self.ax = f.add_subplot(111) mass_list = self.compounds[0].get_mz_list() print mass_list intensity_list = self.compounds[0].get_intensity_list() mass_spec_plot = self.ax.bar(mass_list, intensity_list,\ width=0.05) min_mz = mass_list[0] max_mz = mass_list[-1] self.ax.set_xlim([min_mz-1, max_mz+1]) self.ax.set_ylim([0, 1.1*max(intensity_list)]) self.ax.set_xticks(mass_list) self.ax.set_xticklabels(mass_list, rotation=45) self.ax.set_title("Base Ion:" + str(mass_list[0])) self.canvas = FigureCanvasTkAgg(f, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=RIGHT)