def create_issue_window(self): """Create the results window.""" self.issue_window = Toplevel(self.master) self.issue_window.title("SCM Helper - Issue Window") self.reports = StringVar() self.reports.set("All Reports") top_frame = Frame(self.issue_window) top_frame.grid(row=0, column=0, sticky=W + E) label = Label(top_frame, text="Select Report: ") label.grid(row=0, column=0, pady=10, padx=10) rpts = [resp.title() for resp in REPORTS] all_reports = ["All Reports"] + rpts menu = OptionMenu( top_frame, self.reports, *all_reports, command=self.process_issue_option, ) menu.grid(row=0, column=1, pady=10, padx=10) self.grouping = StringVar() self.grouping.set("Error") label = Label(top_frame, text="Group Report by: ") label.grid(row=0, column=2, pady=10, padx=10) menu = OptionMenu( top_frame, self.grouping, "Error", "Member", command=self.process_issue_option, ) menu.grid(row=0, column=3, pady=10, padx=10) txt = "Analysis..." top_group = LabelFrame(self.issue_window, text=txt, pady=5, padx=5) top_group.grid(row=1, column=0, columnspan=4, pady=10, padx=10, sticky=NSEW) self.issue_window.columnconfigure(0, weight=1) self.issue_window.rowconfigure(1, weight=1) top_group.columnconfigure(0, weight=1) top_group.rowconfigure(0, weight=1) self.issue_text = scrolledtext.ScrolledText(top_group, width=100, height=40) self.issue_text.grid(row=0, column=0, sticky=NSEW) self.issue_window.protocol("WM_DELETE_WINDOW", self.close_issue_window)
def init_video_canvas(self): videoLabelFont = font.Font(size=20) videoFrame = LabelFrame(self, text='Video Player', font=videoLabelFont) videoFrame.columnconfigure(1, weight=1) videoFrame.rowconfigure(1, weight=1) videoFrame.grid(column=1, row=1, columnspan=8, rowspan=12, sticky=E+W+S+N, padx=20) imageCanvas = tk.Canvas(videoFrame, bg='#000000') imageCanvas.grid(column=1, row=1, sticky=E+W+S+N, padx=5, pady=5)
def create_main_window(self): """Create the main window.""" top_frame = Frame(self.master) top_frame.grid(row=0, column=0, sticky=W + E) label = Label(top_frame, text="Password: "******"") password = Entry(top_frame, show="*", textvariable=self.__password, width=20) password.grid(row=0, column=1, pady=10, padx=10) msg = "Analyse" self.button_analyse = Button(top_frame, text=msg, command=self.analyse_window) self.button_analyse.grid(row=0, column=2, pady=10, padx=10) self.master.bind("<Return>", self.analyse_enter) self.button_backup = Button(top_frame, text="Backup", command=self.backup) self.button_backup.grid(row=0, column=3, pady=10, padx=10) self.button_fixit = Button(top_frame, text="Fixit", command=self.fixit) self.button_fixit.config(state=DISABLED) self.button_fixit.grid(row=0, column=4, pady=10, padx=10) top_group = LabelFrame(self.master, text="Notifications...", pady=5, padx=5) top_group.grid(row=1, column=0, columnspan=5, pady=10, padx=10, sticky=NSEW) self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) top_group.columnconfigure(0, weight=1) top_group.rowconfigure(0, weight=1) self.notify_text = scrolledtext.ScrolledText(top_group, width=60, height=20) self.notify_text.grid(row=0, column=0, sticky=NSEW)
def _addUpperTemplate(self) : lblFrame = LabelFrame(self,text=" Documents ") lblFrame.grid(row=0,column=0,sticky="new",padx=15,pady=15,columnspan=2); frame = Frame(lblFrame); Label(frame,text="Limit Documents").grid(row=0,column=0,sticky="w",pady=5,padx=10); self.combo = ttk.Combobox(frame,values=["None"] + [i for i in range(1,20)] , state="readonly"); def chooseLim(event) : self.combo.config(state="disabled");self.docsLim=self.combo.get();print(self.docsLim); self.combo.bind("<<ComboboxSelected>>", chooseLim); self.combo.grid(row=0,column=1,sticky="w") self.combo.current(0) frame.grid(row=0,column=0,sticky="w") frame = Frame(lblFrame) xscrollbar = Scrollbar(frame , orient="horizontal") xscrollbar.grid(row=1, column=0, sticky="snew") yscrollbar = Scrollbar(frame) yscrollbar.grid(row=0, column=1, sticky="snew") self.text = Text(frame , height=10 , font=("Consolas",12) , wrap="none" , xscrollcommand=xscrollbar.set , yscrollcommand=yscrollbar.set) self.text.grid(row=0,column=0,sticky="snew") xscrollbar.config(command=self.text.xview) yscrollbar.config(command=self.text.yview) frame.grid(row=1,column=0,sticky="snew",padx=10,pady=(5,0)) self.fileChoose = Label(lblFrame,text="Import from a text file",font=("consolas",10),fg="blue",cursor="hand2"); self.fileChoose.grid(row=2,column=0,sticky="w",padx=10) self.fileChoose.bind("<Button-1>",lambda event : self._importText()); rightFrame = Frame(lblFrame); Button(rightFrame,text="Add as a Document",relief="groove",command=self._addDoc).grid(row=0,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Remove all Documents",relief="groove",command=self._removeDocs).grid(row=1,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Past a Document",relief="groove",command=self._pastDoc).grid(row=2,column=0,ipady=4,padx=(5,15),pady=2,sticky="we") Button(rightFrame,text="Show Documents",relief="groove",command=self._showDocs).grid(row=3,column=0,ipady=4,padx=(5,15),pady=2,sticky="we"); rightFrame.grid(row=1,column=1) frame2 = Frame(lblFrame); Label(frame2,text="Search Engine Mode").grid(row=0,column=0,sticky="w",pady=5,padx=10); self.combo2 = ttk.Combobox(frame2,values=["Boolean Retrival Model","Inverted Index Model","Vector Space Model"] , state="readonly"); self.combo2.grid(row=0,column=1,sticky="we",columnspan=2,padx=(10,10)) self.combo2.current(0) frame2.grid(row=3,column=0,sticky="snew",pady=15); frame2.columnconfigure(2,weight=1) frame.columnconfigure(0,weight=1); self.columnconfigure(0,weight=1); self.rowconfigure(0,weight=1); frame.rowconfigure(0,weight=1); lblFrame.rowconfigure(0,weight=4); lblFrame.columnconfigure(0,weight=1);
def __init__(self, parent, filename, scm, gui): """Initialise.""" Frame.__init__(self, parent) self.parent = parent self.file = filename self.scm = scm self.gui = gui self.edit_win = Toplevel(self.master) self.edit_win.title("SCM Helper - Edit Config") top_frame = Frame(self.edit_win) top_frame.grid(row=0, column=0, sticky=W + E) abtn = Button(top_frame, text="Save", command=self.save_command) abtn.grid(row=0, column=0, pady=10, padx=10) cbtn = Button(top_frame, text="Close", command=self.on_exit) cbtn.grid(row=0, column=1, pady=10, padx=10) top_group = LabelFrame(self.edit_win, text=filename, pady=5, padx=5) top_group.grid(row=1, column=0, columnspan=2, pady=10, padx=10, sticky=NSEW) self.edit_win.columnconfigure(0, weight=1) self.edit_win.rowconfigure(1, weight=1) top_group.columnconfigure(0, weight=1) top_group.rowconfigure(0, weight=1) self.text_pad = scrolledtext.ScrolledText(top_group, width=80, height=40) self.text_pad.grid(row=0, column=0, sticky=NSEW) with open(self.file, FILE_READ, encoding="utf8") as file: contents = file.read() self.text_pad.insert("1.0", contents) file.close() self.text_pad.edit_modified(False) self.edit_win.protocol("WM_DELETE_WINDOW", self.on_exit)
def create_report_window(self): """Create the reports window.""" self.report_window = Toplevel(self.master) self.report_window.title("SCM Helper - Report Window") top_frame = Frame(self.report_window) top_frame.grid(row=0, column=0, sticky=W + E) txt = "Report..." top_group = LabelFrame(self.report_window, text=txt, pady=5, padx=5) top_group.grid(row=0, column=0, pady=10, padx=10, sticky=NSEW) self.report_window.columnconfigure(0, weight=1) self.report_window.rowconfigure(0, weight=1) top_group.columnconfigure(0, weight=1) top_group.rowconfigure(0, weight=1) self.report_text = scrolledtext.ScrolledText(top_group, width=80, height=40) self.report_text.grid(row=0, column=0, sticky=NSEW) self.report_window.protocol("WM_DELETE_WINDOW", self.close_report_window)
class OptimizerMainWindow(): ''' classdocs ''' #TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W+E+N+S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W+E+N+S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W+E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W+E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W+E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W+E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) #generate color tags for textboxes for i in range(101): #green for normal codons (r,g,b) = colorsys.hsv_to_rgb(210/360, i/100, 1.0) colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255)) self.textSourceSeq.tag_config("normal"+str(i), background=colorHex) self.textResultSequence.tag_config("normal"+str(i), background=colorHex) #red for codons with restriction sites (r,g,b) = colorsys.hsv_to_rgb(5/360, i/100, 1.0) colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255)) self.textSourceSeq.tag_config("restrict"+str(i), background=colorHex) self.textResultSequence.tag_config("restrict"+str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError : # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ['A', 'C', 'G', 'T']) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal"+str(int(sc*100))) #print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict"+str(int(sc*100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal"+str(int(sc*100))) #print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict"+str(int(sc*100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode='w') as fd: fd.write(self.optimizer.optimizedSequence)
class Editor(object): """ Finestra per l'editor di condice assembly """ def __init__(self, master, calcolatore): """ Inizializza i frame della finestra dell'Editor """ self.master = master self.CD = calcolatore # Codice Assembly self.codice = LabelFrame( self.master, text="Codice Assembly", relief=RIDGE, borderwidth=5, labelanchor="n", pady=5, ) self.codice.rowconfigure(0, weight=1) self.codice.columnconfigure(0, weight=1) self.codice.grid(row=1, column=0, rowspan=3, columnspan=5, sticky=W + E + N + S) self.menubar = Menu(self.master) self.create_widgets(self.menubar) def create_widgets(self, menubar): """ Crea il layout del programma, finestra dell'Editor """ # Menu self.filemenu = Menu(menubar, tearoff=0) self.filemenu.add_command(label="Apri", command=self.aprifile) self.filemenu.add_command(label="Salva", command=self.salvafile) self.filemenu.add_command(label="Cancella", command=self.cancella) self.filemenu.add_separator() self.filemenu.add_command(label="Esci", command=self.exit) menubar.add_cascade(label="Opzioni", menu=self.filemenu) self.master.config(menu=self.menubar) self.helpmenu = Menu(menubar, tearoff=0) self.helpmenu.add_command(label="Informazioni", command=self.infor) self.helpmenu.add_command(label="Legenda", command=self.leg) self.helpmenu.add_command(label="Guida", command=self.guida) menubar.add_cascade(label="Aiuto", menu=self.helpmenu) # Codice Assembly self.Inserisci = Text(self.codice, width=50, height=30, wrap=WORD) self.Inserisciscrollbar = Scrollbar(self.codice) self.Inserisciscrollbar.config(command=self.Inserisci.yview) self.Inserisci.config(yscrollcommand=self.Inserisciscrollbar.set) self.Inserisciscrollbar.grid(row=0, column=1, sticky=N + S) self.Inserisci.grid(row=0, column=0, sticky=W) def exit(self): """ Esce dal programma """ if askquestion("Exit", "Sicuro di voler uscire?") == YES: self.master.quit() self.master.destroy() else: showinfo( "Suggerimento", """Forse e' meglio fare una pausa!""", icon=WARNING ) def aprifile(self): """ Apre un file assembly e lo mostra a video per essere modificato """ path = askopenfilename( title="Apri codice assembly", filetypes=[("Assembly", ".asm"), ("Testo", ".txt"), ("All", "*")], ) if path != "": with open(path, "r") as cur_file: self.Inserisci.delete(1.0, END) self.Inserisci.insert(INSERT, cur_file.read()) def cancella(self): """ Cancella l'attuale file assembly caricato """ if ( askquestion("Cancella", "Si vuole cancellare tutto il codice assembly?") == YES ): self.Inserisci.delete(1.0, END) def salvafile(self): """ Salva il file assembly su cui si sta lavorando """ contenuto = self.Inserisci.get(1.0, END) contenuto = contenuto.encode("ascii", "ignore") path = asksaveasfilename( title="Salva codice assembly", defaultextension=[("Assembly", ".asm"), ("Testo", ".txt"), ("All", "*")], filetypes=[("Assembly", ".asm"), ("Testo", ".txt"), ("All", "*")], ) if path != "": file = open(path, "w") file.write(str(contenuto)) file.close() @staticmethod def infor(): """ Visualizza le informazioni riguardante il programma """ nome = """pdp8 emulator""" stringa = """ Pdp8 Emulator °°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°° Version = 1.6.2 Tested with = python 2.6 & 2.7 ------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015 Mirco Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------- Contact: [email protected] Collaborators : Walter Valentini """ showinfo(nome, stringa) @staticmethod def leg(): """ Visualizza le informazioni riguardanti colori """ nome = """pdp8 Legenda""" stringa = """ Rosso = indirizzo puntato da PC Giallo = indirizzo puntato da MAR Verde = ultima istruzione eseguita """ showinfo(nome, stringa) @staticmethod def guida(): """ Piccola guida """ nome = """pdp8 Guida""" stringa = """ LOAD = Carica il assembly nella memoria del Calcolatore Didattico (CD). STEP = Avanza del numero di step indicato (di default 1). Uno step equivale all'esecuzione di una singola istruzione. mini STEP = Esegue un singolo ciclo in base alle variabili F ed R dell'unità di controllo. micro STEP = Esegue ogni singola microistruzione. Set n STEP = Setta il numero di step. Set Delay = Setta il tempo di aggiornamento del CD. START = Avvia il CD, ma non l'esecuzione del codice. Per eseguire il codice, utilizzare step o esegui una volta avviata la macchina. RESET = Resetta il CD allo stato iniziale. STOP = Ferma il CD e quindi anche l'esecuzione del codice. BREAK = Aggiunge o toglie un break alla cella indicata in esadecimale. CONTINUA = Continua l'esecuzione del programma dopo un break. Equivale a premere in sequenza START ed ESEGUI. ESEGUI = Esegue il codice fino all'istruzione HLT, che arresta la macchina. """ showinfo(nome, stringa)
class App(): """ Start of the applications """ def __init__(self): self.__version__ = '0.2.1' # Larch self.mylarch = larch.Interpreter() self.root = Tk(className='EXAFS Neo GUI') self.root.wm_title("Graphical User Interface for EXAFS Analysis (Beta)") # Standard default geometry self.root.geometry("750x500") self.padx = 5 self.pady = 3 self.os = get_platform() base_folder = os.path.dirname(os.path.join(os.getcwd(),__file__)) icon_loc = os.path.join(base_folder,'media/icon.png') img = PhotoImage(file=icon_loc) self.root.tk.call('wm','iconphoto',self.root._w,img) # Set default font self.entryFont = Font(family="TkFixedFont", size=10) self.menuFont = Font(family="TkMenuFont",size=10) self.labelFont = Font(family="TkTextFont", size=11) # Generate the mainframe self.mainframe = ttk.Notebook(self.root,height=40,padding="5") self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) # Initalize variable self.initialize_var() self.initialize_tab() self.Build_tabs() def initialize_var(self): """ Initalize all possible variables in the gui. Future additions starts here. """ # Inputs self.data_file = StringVar(self.root,'Please choose a file') self.temp_data_file = StringVar(self.root,'Please choose a file') self.output_file = StringVar(self.root,'Please choose a file') self.ncomp = IntVar(self.root,'0') # Number of compounds self.feff_file = StringVar(self.root,'Please choose a directory') self.series = BooleanVar(self.root,'False') # Populations self.populations = IntVar(self.root,1000) self.num_gen = IntVar(self.root,100) self.best_sample = IntVar(self.root,20) self.lucky_few = IntVar(self.root,20) # Mutations self.chance_of_mutation = IntVar(self.root,20) self.orginal_chance_of_mutation = IntVar(self.root,20) self.chance_of_mutation_e0 = IntVar(self.root,20) self.mutation_options = IntVar(self.root,0) # Paths self.individual_path = BooleanVar(self.root,True) self.path_range = IntVar(self.root,20) temp_list = ",".join(np.char.mod('%i', np.arange(1,self.path_range.get()+1))) self.path_list = StringVar(self.root,temp_list) self.path_optimize = BooleanVar(self.root,False) self.path_optimize_pert = DoubleVar(self.root,0.01) self.path_optimize_only = BooleanVar(self.root,False) # Larch Paths self.kmin = DoubleVar(self.root,2.5) self.kmax = DoubleVar(self.root,15) self.k_weight = DoubleVar(self.root,2) self.delta_k = DoubleVar(self.root,0.05) self.r_bkg = DoubleVar(self.root,1.0) self.bkg_kw = DoubleVar(self.root, 1.0) self.bkg_kmax = DoubleVar(self.root, 15) #Outputs self.print_graph = BooleanVar(self.root, False) self.num_output_paths = BooleanVar(self.root, True) self.steady_state_exit = BooleanVar(self.root, True) # Pertubutuions self.n_ini = IntVar(self.root,100) def initialize_tab(self): """ Initialize tab for the main frame. more tabs """ s = ttk.Style() s.configure('TNotebook.Tab', font=('TkHeadingFont','11') ) height=1 self.tab_Inputs = tk.Frame(self.mainframe,height=height) self.tab_Populations = tk.Frame(self.mainframe,height=height) self.tab_Paths = tk.Frame(self.mainframe,height=height) self.tab_Mutation = tk.Frame(self.mainframe,height=height) self.tab_Larch = tk.Frame(self.mainframe,height=height) self.tab_Bkg = tk.Frame(self.mainframe,height=height) self.tab_Output = tk.Frame(self.mainframe,height=height) self.tab_Analysis = tk.Frame(self.mainframe,height=height) self.tab_Expert = tk.Frame(self.mainframe,height=height) # Add all the secondary tabs on the top window self.mainframe.add(self.tab_Inputs, text="Inputs") self.mainframe.add(self.tab_Populations, text="Populations") self.mainframe.add(self.tab_Paths, text="Paths") self.mainframe.add(self.tab_Mutation, text="Mutations") self.mainframe.add(self.tab_Larch, text="Larch") self.mainframe.add(self.tab_Bkg, text="Background Plots") self.mainframe.add(self.tab_Output, text="Outputs") self.mainframe.add(self.tab_Analysis, text='Analysis') self.mainframe.add(self.tab_Expert, text='Expert') self.mainframe.grid(row=0,column=0,columnspan=4,padx=self.padx,pady=self.pady,sticky=E+W+N+S) def description_tabs(self,arr,tabs,sticky=(W,E),row=None,return_description=False): # Rows = index of rows description_list = [] if row is not None: assert len(row) == len(arr); for i,inputs in enumerate(arr): entry = ttk.Label(tabs,text=inputs,font=self.labelFont) if row is not None: k = row[i] else: k = i entry.grid_configure(column=0,row=k,sticky=sticky,padx=self.padx,pady=self.pady) description_list.append(entry) if description_list: return description_list def Build_tabs(self): """ Build tabs """ # Building all arrays self.Build_global() self.Build_inputs_tab() self.Build_population_tab() self.Build_path_tab() self.Build_mutations_tab() self.Build_larch_tab() self.Build_background_tab() self.Build_output_tab() self.Build_analysis_tab() self.Build_expert_tab() self.mainframe.grid_rowconfigure(0,weight=1) self.mainframe.grid_columnconfigure(0,weight=1) self.mainframe.grid_columnconfigure(1,weight=1) def Write_ini(self,filename): """ Write the ini for the specific file """ inputs = ("[Inputs] \nnum_compounds = {compound} \ncsv_file = {data} \noutput_file = {out} \nfeff_file = {feff}\ncsv_series = {series}" .format(compound=str(self.ncomp.get()), data=str(self.data_file.get()), out=str(self.output_file.get()), feff=str(self.feff_file.get()), series=str(self.series.get()))) populations = ("\n\n[Populations] \npopulation = {pop} \nnum_gen = {numgen} \nbest_sample = {best} \nlucky_few = {luck}" .format(pop=str(self.populations.get()), numgen=str(self.num_gen.get()), best=str(self.best_sample.get()), luck=str(self.lucky_few.get()))) mutations = ("\n\n[Mutations] \nchance_of_mutation = {chance} \noriginal_chance_of_mutation = {original} \nchance_of_mutation_e0 = {e0} \nmutated_options = {opt}" .format(chance=str(self.chance_of_mutation.get()), original=str(self.orginal_chance_of_mutation.get()), e0=str(self.chance_of_mutation_e0.get()), opt=str(self.mutation_options.get()))) paths = ("\n\n[Paths] \nindividual_path = {tf} \npath_range = {range} \npath_list = {list} \npath_optimize = {optimize} \noptimize_percent = {optimize_pert} \noptimize_only = {optimize_only}" .format(tf=str(self.individual_path.get()), range=str(self.path_range.get()), list=str(self.path_list.get().replace(" ","")), optimize=str(self.path_optimize.get()), optimize_pert = str(self.path_optimize_pert.get()), optimize_only = str(self.path_optimize_only.get()) )) larch_paths = ("\n\n[Larch_Paths] \nkmin = {min} \nkmax = {max} \nkweight = {weight} \ndeltak = {delk} \nrbkg = {rb} \nbkgkw = {bk} \nbkgkmax = {bmax}" .format(min=self.kmin.get(), max=self.kmax.get(), weight=self.k_weight.get(), delk=self.delta_k.get(), rb=self.r_bkg.get(), bk=self.bkg_kw.get(), bmax=self.bkg_kmax.get())) outputs = ("\n\n[Outputs] \nprint_graph = {pg} \nnum_output_paths = {outpath}\nsteady_state_exit = {steady}" .format(pg=self.print_graph.get(), outpath=self.num_output_paths.get(), steady=self.steady_state_exit.get())) with open(filename,'w') as writer: writer.write(str(inputs)) writer.write(str(populations)) writer.write(str(mutations)) writer.write(str(paths)) writer.write(str(larch_paths)) writer.write(str(outputs)) def Generate_ini(self): os.chdir("..") #change the working directory from gui to EXAFS # while proceed == False: ini_file= filedialog.asksaveasfilename(initialdir = os.getcwd(), title = "Choose output ini file", filetypes = [("ini files","*.ini")]) if ini_file is None: return if isinstance(ini_file,tuple) == False: if len(ini_file) != 0: self.Write_ini(ini_file) messagebox.showinfo('','Ini file written to {fileloc}'.format(fileloc=ini_file)) os.chdir("gui") def stop_term(self): if hasattr(self,'proc'): # print("Stopped EXAFS") self.proc.kill() def run_term(self,file = 'test_temp.i'): """ if hasattr(self,'terminal'): # Need to close previous threads self.terminal.destroy() # command = ['exafs','-i','test.ini'] self.Write_ini('test_temp.i') command = 'exafs -i test_temp.i'.split(' ') # print(command) self.terminal = Console(self.txtbox,command) """ self.Write_ini('test_temp.i') self.stop_term() # command = 'exafs -i test_temp.i' command = ['exafs','-i',file] if self.os == 'Windows': print(' '.join(command)) self.proc = subprocess.Popen(' '.join(command),shell=True) else: self.proc = subprocess.Popen("exec " + ' '.join(command),shell=True) def run_ini(self,file = 'test_temp.i'): command = ['exafs','-i',file] self.proc = subprocess.Popen("exec " + ' '.join(command),shell=True) self.proc.wait() def Build_global(self): ''' Create global generate ini ''' def about_citation(): """ Create about popup """ popup = tk.Toplevel() popup.wm_title("About: Ver: " + str(self.__version__)) popup.resizable(False,False) cite = tk.Label(popup,text='Citation:',font='TkTextFont') cite.grid(column=0,row=0,sticky=N,padx=self.padx,pady=self.pady) citation = scrolledtext.ScrolledText(popup, width = 75, height = 10, font="TkTextFont") citation.grid(column=0,row=1,sticky=N,padx=self.padx,pady=self.pady) citation.configure(state ='disabled') with open('media/Citation') as f: citation.insert(tk.END,f.read()) License_Label = tk.Label(popup,text='License:',font='TkTextFont') License_Label.grid(column=0,row=2,sticky=N,padx=self.padx,pady=self.pady) license = scrolledtext.ScrolledText(popup, width = 75, font = "TkTextFont") license.grid(column=0,row=3,sticky=N,padx=self.padx,pady=self.pady) license.configure(state ='disabled') with open('../LICENSE') as f: license.insert(tk.END,f.read()) B1 = ttk.Button(popup, text="Okay", command = popup.destroy) B1.grid(column=0,row=4,padx=self.padx,pady=self.pady) # popup.grid_columnconfigure((1,3),weight=1) # popup.grid_rowconfigure((1,3),weight=1) popup.grid_columnconfigure((0,2),weight=1) popup.grid_rowconfigure((0,2),weight=1) popup.protocol('WM_DELETE_WINDOW', popup.destroy) self.generate_button = tk.Button(self.root, text="Generate Input", command=self.Generate_ini) self.generate_button.grid(column=3,row=2,sticky=E,padx=self.padx,pady=self.pady) self.run_button = tk.Button(self.root,text='Run',command=self.run_term) self.run_button.grid(column=1,row=2,columnspan=1,sticky=E,padx=self.padx,pady=self.pady) self.stop_button = tk.Button(self.root,text='Stop',command=self.stop_term) self.stop_button.grid(column=2,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) if self.os == 'Windows': self.stop_button.config(state='disabled') self.about_button = tk.Button(self.root,text='About',command=about_citation) self.about_button.grid(column=0,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) self.root.grid_columnconfigure(1, weight=1) self.root.grid_columnconfigure(2, weight=1) self.root.grid_rowconfigure(0,weight=1) # Create a empty frame self.label_frame = LabelFrame(self.root, text="Terminal", padx=5, pady=5) self.label_frame.grid(column=0,row=1, columnspan=4, padx=self.padx, pady=self.pady, sticky=E+W+N+S) # Create the textbox self.label_frame.rowconfigure(0,weight=1) self.label_frame.columnconfigure(0,weight=1) self.txtbox = scrolledtext.ScrolledText(self.label_frame, width=40, height=10) self.txtbox.grid(row=0, column=0, sticky=E+W+N+S) def Build_inputs_tab(self): arr_input = ["Data file", "Output File","Number of FEFF folder"] #FEFF Folder self.description_tabs(arr_input,self.tab_Inputs,row = [0,1,3]) self.tab_Inputs.grid_columnconfigure(1,weight=1) entry_data_file = ttk.Combobox(self.tab_Inputs, textvariable=self.temp_data_file, font=self.entryFont) entry_data_file.grid(column=1, row=0, sticky=(W, E),padx=self.padx,pady=self.pady) entry_output_file = tk.Entry(self.tab_Inputs,textvariable=self.output_file,font=self.entryFont) entry_output_file.grid(column=1,row=1,sticky=(W,E),padx=self.padx,pady=self.pady) separator = ttk.Separator(self.tab_Inputs, orient='horizontal') separator.grid(column=0, row=2,columnspan=4,sticky=W+E,padx=self.padx) comp_list = list(range(1,6)) entry_ncomp = ttk.Combobox(self.tab_Inputs, width=7, values=comp_list,textvariable=self.ncomp, font=self.entryFont) entry_ncomp.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def select_data_file(): os.chdir("..") #change the working directory from gui to EXAFS file_name = filedialog.askopenfilenames(initialdir = os.getcwd(), title = "Choose xmu/csv", filetypes = (("xmu files", "*.xmu"),("csv files","*.csv"),("all files","*.*"))) if not file_name: self.data_file.set('Please choose file/s') self.temp_data_file.set('Please choose file/s') else: if isinstance(file_name,tuple): if len(file_name)==1: self.data_file.set(str(file_name[0])) self.temp_data_file.set(str(file_name[0])) else: file_list = list(self.root.splitlist(file_name)) separator = ' ' self.data_file.set(separator.join(file_list)) entry_data_file['value'] = file_list self.series.set(True) os.chdir("gui") def select_output_file(): os.chdir("..") #change the working directory from gui to EXAFS file_name = filedialog.asksaveasfilename(initialdir = os.getcwd(), title = "Choose data_file", filetypes = (("csv files","*.csv"),("all files","*.*"))) if not file_name: self.output_file.set('Please choose a file') else: self.output_file.set(file_name) os.chdir("gui") def feff_trace(var,indx,mode): # Todo: Need to add assertion to make sure every folder is not normal raw_str = [] for i in range(len(self.feff_file_list)): raw_str.append(self.feff_file_list[i].get()) raw_feff = ','.join(raw_str) self.feff_file.set(raw_feff) # print(raw_feff) def gen_feff_folder(var,indx,mode): ncomp = self.ncomp.get() self.feff_file_toggle = [True for i in range(self.ncomp.get())] k = 4 try: self.arr_feff # self.input_list except AttributeError: pass else: for i in range(len(self.feff_input_list)): self.feff_input_list[i].destroy() self.feff_button_list[i].destroy() self.feff_description_list[i].destroy() self.feff_file_list = [] self.arr_feff= [] arr_row = [] # parameter sets self.feff_input_list = [] self.feff_button_list = [] self.feff_description_list = [] # Need to remove previous one for i in range(ncomp): self.arr_feff.append('FEFF Folder (' + str(i+1) +")") arr_row.append(i+k) # Generate a list of variables temp_var = StringVar(self.root,'Please choose a directory') self.feff_file_list.append(temp_var) # Add trace back temp_var.trace_add('write',feff_trace) # Setup each entry temp_entry = tk.Entry(self.tab_Inputs,textvariable=temp_var, font=self.entryFont) temp_entry.grid(column=1,row=k+i,sticky=(W,E), padx=self.padx,pady=self.pady) self.feff_input_list.append(temp_entry) # setup each button temp_button = ttk.Button(self.tab_Inputs,text="Choose", command=lambda x=i:select_feff_folder(self.feff_file_list[x]), style='my.TButton') temp_button.grid(column=3, row=k+i, sticky=W,padx=self.padx,pady=self.pady) self.feff_button_list.append(temp_button) self.feff_description_list = self.description_tabs(self.arr_feff,self.tab_Inputs,row=arr_row,return_description=True) def check_feff_folder(pathlib_Path): feff_inp_exists = False num_feff_file = 0 folder_Path = pathlib.Path(pathlib_Path) for i in folder_Path.iterdir(): file = pathlib.Path(i).name if fnmatch.fnmatch(file,'feff????.dat'): num_feff_file +=1 if num_feff_file == 0: # Check no scattering paths for i in folder_Path.iterdir(): file = pathlib.Path(i).name if fnmatch.fnmatch(file,'feff.inp'): feff_inp_exists = True feff_inp_loc = file abs_feff_inp_loc = folder_Path.joinpath('feff.inp') create_feff_folder(abs_feff_inp_loc) else: # self.txtbox.insert('No feff.inp in folder') self.txtbox.insert(tk.END,"No feff.inp in folder\n") # return False def select_feff_folder(var): os.chdir("..") #change the working directory from gui to EXAFS # select folder name folder_name = filedialog.askdirectory(initialdir = os.getcwd(), title = "Select folder") if not folder_name: var.set('Please choose a directory') else: check_feff_folder(folder_name) folder_name = os.path.join(folder_name,'feff') var.set(folder_name) os.chdir("gui") # add trace back self.ncomp.trace_add('write',gen_feff_folder) self.ncomp.set(1) button_data_file = ttk.Button(self.tab_Inputs, text="Choose", command=select_data_file, style='my.TButton') button_data_file.grid(column=3, row=0, sticky=W,padx=self.padx,pady=self.pady) button_output_file = ttk.Button(self.tab_Inputs,text="Choose", command=select_output_file, style='my.TButton') button_output_file.grid(column=3, row=1, sticky=W,padx=self.padx,pady=self.pady) def Build_population_tab(self): arr_pop = ["Population", "Number of Generations", "Best Individuals(%)", "Lucky Survivor(%)"] self.description_tabs(arr_pop,self.tab_Populations) self.tab_Populations.grid_columnconfigure(1,weight=1) entry_population = tk.Entry(self.tab_Populations, textvariable=self.populations, font=self.entryFont) entry_population.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_num_gen = tk.Entry(self.tab_Populations, textvariable=self.num_gen, font=self.entryFont) entry_num_gen.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_best_sample = tk.Entry(self.tab_Populations, textvariable=self.best_sample, font=self.entryFont) entry_best_sample.grid(column=1, row=2, sticky=(W, E),padx=self.padx) entry_lucky_few = tk.Entry(self.tab_Populations, textvariable=self.lucky_few, font=self.entryFont) entry_lucky_few.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def Build_path_tab(self): """ Build path tabs """ arr_paths = ['Path Optimize','Multi-Path Optimize','Path Optimize Percentage'] self.description_tabs(arr_paths,self.tab_Paths,row = [0,1,2]) def checkbox_individual_paths(): if self.individual_path.get() == True: entry_path_range.config(state='disabled') entry_path_list.config(state='normal') else: entry_path_range.config(state='normal') entry_path_list.config(state='disabled') # def path_list_cb(var, indx, mode): # """ # Path_list call-back for the number of lists # """ # if self.individual_path.get()== True: # self.path_list.set(self.path_list_call.get()) # counts = 0 # test_list = self.path_list.get().split(",") # for i in range(len(test_list)): # if test_list[i] != '': # counts += 1 # self.path_range_call.set(counts) # entry_individual_paths = ttk.Checkbutton(self.tab_Paths, # variable = self.individual_path,command = checkbox_individual_paths) # entry_individual_paths.grid(column=1,row=0,sticky=(W),padx=self.padx) # self.path_range_call = StringVar(self.tab_Paths,str(self.path_range.get())) # self.path_range_call.trace_add("write",path_range_cb) # entry_path_range = ttk.Entry(self.tab_Paths, width=7, # textvariable=self.path_range_call, font=self.entryFont) # entry_path_range.grid(column=1, row=1, sticky=(W),padx=self.padx) # self.path_list_call = StringVar(self.tab_Paths,self.path_list.get()) # self.path_list_call.trace_add('write',path_list_cb) # entry_path_list = ttk.Entry(self.tab_Paths, # textvariable=self.path_list_call, font=self.entryFont) # entry_path_list.grid(column=1, row=2, sticky=(W, E),padx=self.padx) # entry_path_list.config(state='disabled') # def path_range_cb(var, indx, mode): # if self.individual_path.get()==False: # if self.path_range_call.get() == '': # int_test = 0 # else: # int_test = int(float(self.path_range_call.get())) # self.path_range_call.set(int_test) # self.path_range.set(int_test) # # custom_path_list = ",".join(np.char.mod('%i', np.arange(1,self.path_range.get()+1))) # self.path_list_call.set(custom_path_list) # self.path_list.set(custom_path_list) # def test_str(var): def output_var_trace(var,indx,mode): """ Updates the variables whenever it gets changes """ raw_str = [] # compounds if self.ncomp.get() > 1: for i in range(len(self.path_file_list)): # print(self.path_file_list[i].get()) # create the internal brackets # base_str = list(self.path_file_list[i].get()) var = self.path_file_list[i].get() if var == str(0) or var == "": base_str = '' # del the corresponding one from the final output self.feff_file_toggle[i] = False else: base_str = "[" + var + "]" self.feff_file_toggle[i] = True raw_str.append(base_str) # call back for path and feff temp_path_list = [] temp_feff_list = [] for i in range(len(self.path_file_list)): if self.feff_file_toggle[i] == True: temp_path_list.append(raw_str[i]) temp_feff_list.append(self.feff_file_list[i].get()) raw_path = ','.join(temp_path_list) raw_feff = ','.join(temp_feff_list) self.path_list.set(raw_path) self.feff_file.set(raw_feff) self.individual_path.set(True) # else calculate compounds else: self.path_list.set(self.path_file_list[0].get()) # print("-----------------------") # print(self.feff_file_toggle) # print(self.feff_file.get()) # print(self.path_list.get()) def ncomp_trace_cb(var, indx, mode): """ Trace the number of components, if changes, recomputed """ ncomp = self.ncomp.get() k = 5 # Starting components # Check if arr_pathlist exists try: self.arr_pathlist except AttributeError: pass else: # Destory all in the current list for i in range(len(self.path_input_list)): self.path_description_list[i].destroy() self.path_input_list[i].destroy() # Create the list self.arr_pathlist = [] self.path_input_list = [] self.path_file_list = [] arr_row = [] for i in range(ncomp): self.arr_pathlist.append('Pathlist Folder ('+ str(i+1) + ")") arr_row.append(i+k) # Create the entry variable temp_path_var = StringVar(self.root,'Path_list') temp_path_var.trace_add('write',output_var_trace) # temp_path_var.trace_add('write',) self.path_file_list.append(temp_path_var) # Create the entry temp_entry = tk.Entry(self.tab_Paths,textvariable=self.path_file_list[i], font=self.entryFont) # lock to the grid temp_entry.grid(column=1,columnspan=2,row=k+i,sticky=(W,E), padx=self.padx,pady=self.pady) self.path_input_list.append(temp_entry) # create the descriptions for it. self.path_description_list = self.description_tabs(self.arr_pathlist,self.tab_Paths,row=arr_row,return_description=True) entry_path_optimize = ttk.Checkbutton(self.tab_Paths, variable = self.path_optimize) entry_path_optimize.grid(column=1,row=0,sticky=(W,E),padx=self.padx) entry_path_optimize_only = ttk.Checkbutton(self.tab_Paths, variable = self.path_optimize_only) entry_path_optimize_only.grid(column=1,row=1,sticky=(W,E),padx=self.padx) entry_optimize_perc= ttk.Entry(self.tab_Paths, textvariable=self.path_optimize_pert, font=self.entryFont) entry_optimize_perc.grid(column=1, row=2, sticky=(W, E),padx=self.padx) separator = ttk.Separator(self.tab_Paths, orient='horizontal') separator.grid(column=0, row=3,columnspan=4,sticky=(W,E),padx=self.padx) self.tab_Paths.columnconfigure(4,weight=1) # add the call back for it to modify if it get changes self.ncomp.trace_add('write',ncomp_trace_cb) # inital default value self.ncomp.set(1) def Build_mutations_tab(self): arr_muts = ["Mutation Chance (%)", "Original chance of mutation (%)", "E0 Mutation Chance (%)", "Mutation Options"] self.description_tabs(arr_muts,self.tab_Mutation) mut_list = list(range(101)) # self.tab_Inputs.grid_columnconfigure(1,weight=1) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.chance_of_mutation, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.orginal_chance_of_mutation, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.chance_of_mutation_e0, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=2, sticky=(W, E),padx=self.padx) mut_list = list(range(3)) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.mutation_options, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def Build_larch_tab(self): arr_larch = ["Kmin", "Kmax", "Kweight", "Delta k", "R Bkg", "Bkg Kw", "Bkg Kmax"] self.description_tabs(arr_larch,self.tab_Larch) entry_kmin = ttk.Entry(self.tab_Larch, textvariable=self.kmin, font=self.entryFont) entry_kmin.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_kmax = ttk.Entry(self.tab_Larch, textvariable=self.kmax, font=self.entryFont) entry_kmax.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_k_weight = ttk.Entry(self.tab_Larch, textvariable=self.k_weight, font=self.entryFont) entry_k_weight.grid(column=1, row=2, sticky=(W, E),padx=self.padx) entry_delta_k = ttk.Entry(self.tab_Larch, textvariable=self.delta_k, font=self.entryFont) entry_delta_k.grid(column=1, row=3, sticky=(W, E),padx=self.padx) entry_r_bkg = ttk.Entry(self.tab_Larch, textvariable=self.r_bkg, font=self.entryFont) entry_r_bkg.grid(column=1, row=4, sticky=(W, E),padx=self.padx) entry_bkg_kw = ttk.Entry(self.tab_Larch, textvariable=self.bkg_kw, font=self.entryFont) entry_bkg_kw.grid(column=1, row=5, sticky=(W, E),padx=self.padx) entry_bkg_kmax = ttk.Entry(self.tab_Larch, textvariable=self.bkg_kmax, font=self.entryFont) entry_bkg_kmax.grid(column=1, row=6, sticky=(W, E),padx=self.padx) def Build_background_tab(self): def button_bkg_draw(): # TODO: # Makes it so bkg_plot.inital_parameters(self.temp_data_file,self.r_bkg,self.bkg_kw,self.bkg_kmax,self.kmin,self.kmax,self.delta_k,self.k_weight) bkg_plot.draw_background() arr_bkg = ["R Bkg", "K min","K max","Bkg Kw", "Bkg Kmax"] self.description_tabs(arr_bkg,self.tab_Bkg,sticky=(W,E,N)) # self.tab_Bkg.grid_rowconfigure(3,weight=1) # self.tab_Bkg.grid_rowconfigure(4,weight=1) # self.tab_Bkg.grid_rowconfigure(5,weight=1) # self.tab_Bkg.grid_rowconfigure(6,weight=1) self.tab_Bkg.rowconfigure(8,weight=1) self.tab_Bkg.columnconfigure(2,weight=1) entry_r_bkg = ttk.Entry(self.tab_Bkg, textvariable=self.r_bkg, font=self.entryFont) entry_r_bkg.grid(column=1, row=0, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_k_min = ttk.Entry(self.tab_Bkg, textvariable=self.kmin, font=self.entryFont) entry_k_min.grid(column=1, row=1, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_k_max = ttk.Entry(self.tab_Bkg, textvariable=self.kmax, font=self.entryFont) entry_k_max.grid(column=1, row=2, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_bkg_kw = ttk.Entry(self.tab_Bkg, textvariable=self.bkg_kw, font=self.entryFont) entry_bkg_kw.grid(column=1, row=3, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_bkg_kmax = ttk.Entry(self.tab_Bkg, textvariable=self.bkg_kmax, font=self.entryFont) entry_bkg_kmax.grid(column=1, row=4, sticky=(W,E,N),padx=self.padx,pady=self.pady) bkg_plot = BKG_plot(self.tab_Bkg,self.mylarch) button_bkg_mu = ttk.Button(self.tab_Bkg, text="Plot Background and Mu", command=button_bkg_draw) button_bkg_mu.grid(column=0, row=5,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_kspace = ttk.Button(self.tab_Bkg, text="K space", command=bkg_plot.draw_kspace) button_kspace.grid(column=0, row=6,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_rspace = ttk.Button(self.tab_Bkg, text="R space", command=bkg_plot.draw_rspace) button_rspace.grid(column=0, row=7,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) def Build_output_tab(self): pop_min = IntVar(self.tab_Output,100) pop_max = IntVar(self.tab_Output,5001) gen_min = IntVar(self.tab_Output,20) gen_max = IntVar(self.tab_Output,501) mut_min = IntVar(self.tab_Output,20) mut_max = IntVar(self.tab_Output,51) pertub_check = IntVar(self.tab_Output,0) def generate_multi_ini(): # os.chdir("..") pop_range = np.arange(pop_min.get(),pop_max.get(),100) gen_range = np.arange(gen_min.get(),gen_max.get(),5) mut_range = np.arange(mut_min.get(),mut_max.get(),10) # exit() multi_folder = filedialog.askdirectory(initialdir = os.getcwd(),title = 'Select folder') if not multi_folder: return else: og_pop = self.populations.get() og_gen = self.num_gen.get() og_mut = self.chance_of_mutation.get() og_out_file = self.output_file.get() for i in range(self.n_ini.get()): pop_select = np.random.choice(pop_range) gen_select = np.random.choice(gen_range) mut_select = np.random.choice(mut_range) base_file = os.path.splitext(og_out_file)[0] self.output_file.set(os.path.join(base_file +"_"+str(i).zfill(3) +".ini")) self.populations.set(pop_select) self.num_gen.set(gen_select) self.chance_of_mutation.set(mut_select) self.Write_ini(multi_folder + "/file_" + str(i).zfill(3)+'.i') # set back og ini self.populations.set(og_pop) self.num_gen.set(og_gen) self.chance_of_mutation.set(og_mut) self.output_file.set(og_out_file) # os.chdir("gui") return multi_folder def run_multi_ini(): """ Run multiple ini file """ folder_loc = generate_multi_ini() full_file_list = [] file_list = glob.glob(folder_loc + "/*.i") for i in file_list: full_file_list.append(os.path.join(folder_loc,i)) full_file_list.sort(key=natural_keys) for i in full_file_list: print(bcolors.BOLD + str(i) + bcolors.ENDC) self.run_ini(i) def checkbox_multi(): widget_lists=[ entry_n_ini, entry_pertub_pop_min, entry_pertub_pop_max, entry_pertub_gen_min, entry_pertub_gen_max, entry_pertub_mut_min, entry_pertub_mut_max, button_gen_nini, button_run_nini] if pertub_check.get() == 0: for i in widget_lists: i.config(state='disabled') elif pertub_check.get() == 1: for i in widget_lists: i.config(state='normal') arr_out = ["Print graph", "Steady state exit"] self.description_tabs(arr_out,self.tab_Output) checkbutton_print_graph = ttk.Checkbutton(self.tab_Output, var=self.print_graph) checkbutton_print_graph.grid(column=1, row=0,sticky=W+E,padx=self.padx) checkbutton_steady_state= ttk.Checkbutton(self.tab_Output, var=self.steady_state_exit) checkbutton_steady_state.grid(column=1, row=1,sticky=W+E,padx=self.padx) # Create separators separator = ttk.Separator(self.tab_Output, orient='horizontal') separator.grid(column=0, row=2,columnspan=4,sticky=W+E,padx=self.padx) self.tab_Output.columnconfigure(3,weight=1) arr_out = ["Create Multiple Input Files","Number of Ini Files","Pertubutions-Population(min,max)", "Pertubutions-Generation(min,max)","Pertubutions-Mutation(min,max)"] self.description_tabs(arr_out,self.tab_Output,row=[3,5,6,7,8]) # Create New pertubutuions checkbutton_pertub= ttk.Checkbutton(self.tab_Output, var=pertub_check,command=checkbox_multi) checkbutton_pertub.grid(column=1, row=3,sticky=W+E,padx=self.padx) pertub_list = list(range(1,101)) text ='Each entry allows user to control perturbation percentage of the desire variables.' entry = ttk.Label(self.tab_Output,text=text,font=self.labelFont) entry.grid_configure(column=0,row=4,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) entry_n_ini = tk.Entry(self.tab_Output,textvariable=self.n_ini,font=self.entryFont) entry_n_ini.grid(column=1, row=5,columnspan=2,sticky=(W, E),padx=self.padx) entry_n_ini.config(state='disabled') width = 5 # -------------- entry_pertub_pop_min= ttk.Entry(self.tab_Output, width=width,textvariable=pop_min, font=self.entryFont) entry_pertub_pop_min.grid(column=1, row=6, sticky=(W, E),padx=self.padx) entry_pertub_pop_max= ttk.Entry(self.tab_Output, width=width,textvariable=pop_max, font=self.entryFont) entry_pertub_pop_max.grid(column=2, row=6, sticky=(W, E),padx=self.padx) entry_pertub_pop_min.config(state='disabled') entry_pertub_pop_max.config(state='disabled') # -------------- entry_pertub_gen_min= ttk.Entry(self.tab_Output, width=width,textvariable=gen_min, font=self.entryFont) entry_pertub_gen_min.grid(column=1, row=7, sticky=(W, E),padx=self.padx) entry_pertub_gen_max= ttk.Entry(self.tab_Output, width=width,textvariable=gen_max, font=self.entryFont) entry_pertub_gen_max.grid(column=2, row=7, sticky=(W, E),padx=self.padx) entry_pertub_gen_min.config(state='disabled') entry_pertub_gen_max.config(state='disabled') # -------------- entry_pertub_mut_min= ttk.Entry(self.tab_Output, width=width,textvariable=mut_min, font=self.entryFont) entry_pertub_mut_min.grid(column=1, row=8, sticky=(W, E),padx=self.padx) entry_pertub_mut_max= ttk.Entry(self.tab_Output, width=width,textvariable=mut_max, font=self.entryFont) entry_pertub_mut_max.grid(column=2, row=8, sticky=(W, E),padx=self.padx) entry_pertub_mut_min.config(state='disabled') entry_pertub_mut_max.config(state='disabled') # -------------- button_gen_nini = tk.Button(self.tab_Output,text="Generate Input Files",command=generate_multi_ini) button_gen_nini.grid(column=0, row=9,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) button_gen_nini.config(state='disabled') button_run_nini = tk.Button(self.tab_Output,text="Run Multiple Input Files",command=run_multi_ini) button_run_nini.grid(column=0, row=10,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) button_run_nini.config(state='disabled') def Build_analysis_tab(self): def select_analysis_folder(): os.chdir("..") #change the working directory from gui to EXAFS folder_name = filedialog.askdirectory(initialdir = os.getcwd(), title = "Select folder") if not folder_name: analysis_folder.set('Please choose a directory') else: # folder_name = os.path.join(folder_name,'feff') analysis_folder.set(folder_name) # print(self.feff_file.get()) os.chdir("gui") def run_analysis(): params = {} # params['base'] = Path(os.getcwd()).parent params['base'] = '' params['Kmin'] = self.kmin.get() params['Kmax'] = self.kmax.get() params['kweight'] = self.k_weight.get() params['deltak'] = self.delta_k.get() params['rbkg'] = self.r_bkg.get() params['bkgkw'] = self.bkg_kw.get() params['bkgkmax'] = self.bkg_kmax.get() params['front'] = self.feff_file.get().split(',') params['CSV'] = self.data_file.get() params['optimize'] = self.path_optimize.get() params['series_index'] = series_index.get() params['series'] = self.series.get() # set up the params self.txtbox.insert(tk.END,"Running Analysis...\n") analysis_plot.setup_params(params) paths = '[' + self.path_list.get() + ']' paths_list = ast.literal_eval(paths) # analysis_plot.setup_paths(paths) print(paths) print(paths_list) print(type(paths_list)) analysis_plot.setup_paths(ast.literal_eval(paths)) analysis_plot.setup_dirs(analysis_folder.get()) arr_str,latex_str = analysis_plot.extract_and_run(analysis_folder) self.txtbox.insert(tk.END,arr_str) self.txtbox.insert(tk.END,"-------------\n") self.txtbox.insert(tk.END,latex_str) self.txtbox.insert(tk.END,"\n-------------\n") self.txtbox.insert(tk.END,"Done") def plot_occurances(): # plot the self_occurances, and then plot the others """ To do: occurances only works with one """ analysis_plot.plot_occurances(analysis_folder.get(),self.path_optimize_pert.get(),self.path_list.get()) analysis_folder = StringVar(self.tab_Analysis,'Please choose a directory') series_index = IntVar(self.tab_Analysis,0) self.tab_Analysis.columnconfigure(1,weight=1) self.tab_Analysis.columnconfigure(2,weight=1) self.tab_Analysis.rowconfigure(10,weight=1) arr_out = ["Select folder"] self.description_tabs(arr_out,self.tab_Analysis) entry_analysis_folder = tk.Entry(self.tab_Analysis,textvariable=analysis_folder,font=self.entryFont) entry_analysis_folder.grid(column=1,row=0,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_analysis_folder = ttk.Button(self.tab_Analysis,text="Choose", command=select_analysis_folder, style='my.TButton') button_analysis_folder.grid(column=3, row=0, sticky=W+E,padx=self.padx,pady=self.pady) separator = ttk.Separator(self.tab_Analysis, orient='horizontal') separator.grid(column=0, row=1,columnspan=4,sticky=W+E,padx=self.padx) analysis_plot = Analysis_Plot(self.tab_Analysis,self.mylarch) # ---------------------------------------------------------------------- button_Run_Analysis = ttk.Button(self.tab_Analysis,text="Run Analysis", command=run_analysis, style='my.TButton') button_Run_Analysis.grid(column=0, row=2,columnspan=4, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_kR = ttk.Button(self.tab_Analysis,text="Plot K and R Spectrum", command=analysis_plot.plot_k_r_space, style='my.TButton') button_plot_kR.grid(column=0, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_individual = ttk.Button(self.tab_Analysis,text='Plot K Individual', command=analysis_plot.plot_individual, style='my.TButton') button_plot_individual.grid(column=1, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_error = ttk.Button(self.tab_Analysis,text="Plot Error", command=analysis_plot.plot_error, style='my.TButton') button_plot_error.grid(column=2, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_occurances = ttk.Button(self.tab_Analysis,text='Plot Occurances', command=plot_occurances, style='my.TButton') button_plot_occurances.grid(column=3,row=3,columnspan=1,sticky=W+E,padx=self.padx,pady=self.pady) def Build_expert_tab(self): arr_muts = ["Override Num Compounds"] self.description_tabs(arr_muts,self.tab_Expert) ncomp_list = list(range(1,101)) entry_ncomp = ttk.Combobox(self.tab_Expert, width=7, values=ncomp_list,textvariable=self.ncomp, font=self.entryFont) entry_ncomp.grid(column=1, row=0, sticky=(W, E),padx=self.padx) def On_closing(self): """ on closing function """ if messagebox.askokcancel("Quit", "Do you want to quit?"): self.stop_term() if hasattr(self,'terminal'): self.root.quit() self.terminal.destroy() else: self.root.quit() def Run(self): """ Run the code """ self.root.protocol('WM_DELETE_WINDOW', self.On_closing) self.beta_popup() self.root.mainloop() def beta_popup(self): beta_popup = tk.Toplevel(self.root) beta_popup.wm_title("Warning") msg = "This Graphical User Interface is still under active development.\nPlease contact us using Github Issues." entry = ttk.Label(beta_popup,text=msg) entry.grid(column=0,row=0,padx=5,pady=3) B1 = ttk.Button(beta_popup, text="Okay", command = beta_popup.destroy) B1.grid(column=0,row=1,padx=5,pady=3) beta_popup.grid_columnconfigure((0,1),weight=1) beta_popup.grid_rowconfigure((0,1),weight=1) beta_popup.protocol('WM_DELETE_WINDOW', beta_popup.destroy) beta_popup.attributes('-topmost', 'true')
class Emulatore(object): """ Interfaccia grafica per l'emulatore del pdp8 """ def __init__(self, master, codice, calcolatore, emulatore): """ Inizializza i frame per l'interfaccia dell'emulatore """ self.CD = calcolatore self.codice = codice self.delay = 100 self.master = Frame(master) self.root = emulatore # Memoria Ram self.ram = LabelFrame( self.master, text="Memoria RAM", relief=RIDGE, borderwidth=5, labelanchor="n", pady=5, ) self.ram.rowconfigure(0, weight=1) self.ram.columnconfigure(0, weight=1) self.ram.grid(row=0, column=0, rowspan=3, columnspan=5, sticky=W + E + N + S) # Controlli self.controlli = Frame(self.master, padx=10, pady=10) self.controlli.grid(row=0, column=5, rowspan=1) # Status CD self.registri = LabelFrame( self.master, text="REGISTRI", relief=RIDGE, borderwidth=5, labelanchor="n", padx=25, pady=10, ) self.registri.grid(row=0, column=6, rowspan=1, sticky=W + E + N + S) self.unita = LabelFrame( self.master, text="UC", relief=RIDGE, borderwidth=5, labelanchor="n", padx=10, pady=10, ) self.unita.grid(row=2, column=6, rowspan=1, sticky=N) # Var self.variabili = Frame(self.master) self.variabili.grid(row=2, column=5) self.nstep = LabelFrame( self.variabili, text="Num. Step", relief=RIDGE, borderwidth=5, labelanchor="n", ) self.nstep.grid(row=0, column=5, sticky=W + E) self.delays = LabelFrame( self.variabili, text="Delay", relief=RIDGE, borderwidth=5, labelanchor="n" ) self.delays.grid(row=1, column=5, sticky=W + E) self.tempo = LabelFrame( self.variabili, text="Tempo", relief=RIDGE, borderwidth=5, labelanchor="n" ) self.tempo.grid(row=1, column=6, sticky=W + E) # Unita' di controllo self.unitas = LabelFrame(self.unita, text="S", labelanchor="s", padx=10) self.unitas.grid(row=0, column=0, sticky=N) self.unitaf = LabelFrame(self.unita, text="F", labelanchor="s", padx=10) self.unitaf.grid(row=0, column=1, sticky=N) self.unitar = LabelFrame(self.unita, text="R", labelanchor="s", padx=10) self.unitar.grid(row=0, column=2, sticky=N) self.unitaint = LabelFrame(self.unita, text="Int.", labelanchor="s", padx=10) self.unitaint.grid(row=0, column=3, sticky=N) # Registri self.programc = LabelFrame( self.registri, text="PC", relief=FLAT, labelanchor="e", padx=5 ) self.programc.grid(row=0, column=0, sticky=W + E) self.mar = LabelFrame( self.registri, text="MAR", relief=FLAT, labelanchor="e", padx=5 ) self.mar.grid(row=1, column=0, sticky=W + E) self.mbr = LabelFrame( self.registri, text="MBR", relief=FLAT, labelanchor="e", padx=5 ) self.mbr.grid(row=2, column=0, sticky=W + E) self.lopr = LabelFrame( self.registri, text="OPR", relief=FLAT, labelanchor="e", padx=5 ) self.lopr.grid(row=3, column=0, sticky=W + E) self.vari = LabelFrame( self.registri, text="I", relief=FLAT, labelanchor="e", padx=5 ) self.vari.grid(row=4, column=0, sticky=W + E) self.vare = LabelFrame( self.registri, text="E", relief=FLAT, labelanchor="e", padx=5 ) self.vare.grid(row=5, column=0, sticky=W + E) self.lac = LabelFrame( self.registri, text="AC", relief=FLAT, labelanchor="e", padx=5 ) self.lac.grid(row=6, column=0, sticky=W + E) self.lacint = LabelFrame( self.registri, text="INT AC", relief=FLAT, labelanchor="e", padx=5 ) self.lacint.grid(row=7, column=0, sticky=W + E) self.lachex = LabelFrame( self.registri, text="HEX AC", relief=FLAT, labelanchor="e", padx=5 ) self.lachex.grid(row=8, column=0, sticky=W + E) # Microistruzioni self.micro = LabelFrame( self.master, text="Microistruzioni eseguite", relief=RIDGE, borderwidth=5, labelanchor="n", pady=5, ) self.micro.rowconfigure(0, weight=1) self.micro.columnconfigure(0, weight=1) self.micro.grid(row=3, column=4, rowspan=5, columnspan=5, sticky=W + E + N + S) # Inout self.inout = LabelFrame( self.master, text="Input & Output", relief=RIDGE, borderwidth=5, labelanchor="n", pady=5, ) self.inout.rowconfigure(0, weight=1) self.inout.columnconfigure(0, weight=1) self.inout.grid(row=3, column=0, columnspan=4, sticky=W + E + N + S) self.create_widgets() def create_widgets(self): """ Crea il layout del programma, finestra dell'emulatore """ # Memoria RAM self.Visualizza = Text(self.ram, width=80) self.Visualizzascrollbar = Scrollbar(self.ram) self.Visualizzascrollbar.config(command=self.Visualizza.yview) self.Visualizza.config(yscrollcommand=self.Visualizzascrollbar.set) self.Visualizzascrollbar.grid(row=0, column=1, sticky=N + S) self.Visualizza.grid(row=0, column=0, sticky=W) # INOUT self.Visualizzainout = Text( self.inout, width=62, height=7, fg="green", bg="black" ) self.Visualizzascrollbar_inout = Scrollbar(self.inout) self.Visualizzascrollbar_inout.config(command=self.Visualizzainout.yview) self.Visualizzainout.config(yscrollcommand=self.Visualizzascrollbar_inout.set) self.Visualizzascrollbar_inout.grid(row=0, column=1, sticky=N + S) self.Visualizzainout.grid(row=0, column=0, sticky=W) # Mircroistruzioni self.Visualizzamicro = Text(self.micro, width=55, height=7) self.Visualizzascrollbar_m = Scrollbar(self.micro) self.Visualizzascrollbar_m.config(command=self.Visualizzamicro.yview) self.Visualizzamicro.config(yscrollcommand=self.Visualizzascrollbar_m.set) self.Visualizzascrollbar_m.grid(row=0, column=1, sticky=N + S) self.Visualizzamicro.grid(row=0, column=0, sticky=W) # Pulsanti self.butload = Button( self.controlli, text="LOAD", anchor=CENTER, width=15, command=self.loading, bg="SkyBlue", ) self.butload.grid(row=0, column=0) self.butstep = Button( self.controlli, text="Step", anchor=CENTER, width=15, command=self.step, bg="linen", ) self.butstep.grid(row=1, column=0) self.butminstep = Button( self.controlli, text="miniStep", anchor=CENTER, width=15, command=self.mini_step, bg="linen", ) self.butminstep.grid(row=2, column=0) self.butstep = Button( self.controlli, text="microStep", anchor=CENTER, width=15, command=self.micro_step, bg="linen", ) self.butstep.grid(row=3, column=0) self.butsetstep = Button( self.controlli, text="Set n Step", anchor=CENTER, width=15, command=self.setnstep, bg="linen", ) self.butsetstep.grid(row=4, column=0) self.butsetdelay = Button( self.controlli, text="Set Delay", anchor=CENTER, width=15, command=self.setdelay, bg="linen", ) self.butsetdelay.grid(row=5, column=0) self.butstart = Button( self.controlli, text="START", anchor=CENTER, width=15, command=self.start, bg="DarkOliveGreen3", ) self.butstart.grid(row=6, column=0) self.butreset = Button( self.controlli, text="RESET", anchor=CENTER, width=15, command=self.resetCD, bg="Orange3", ) self.butreset.grid(row=7, column=0) self.butstop = Button( self.controlli, text="STOP", anchor=CENTER, width=15, command=self.stop, bg="IndianRed", ) self.butstop.grid(row=8, column=0) self.butbreak = Button( self.controlli, text="BREAK", anchor=CENTER, width=15, command=self.breakpoint, bg="Magenta2", ) self.butbreak.grid(row=9, column=0) self.butcontinue = Button( self.controlli, text="CONTINUA", anchor=CENTER, width=15, command=self.continua, bg="Magenta2", ) self.butcontinue.grid(row=10, column=0) self.butesegui = Button( self.controlli, text="ESEGUI", anchor=CENTER, width=15, command=self.esegui, bg="Yellow", ) self.butesegui.grid(row=11, column=0) # Labels self.labelprogramc = Label( self.programc, text="00000000000", relief=SUNKEN, bg="red" ) self.labelprogramc.grid() self.labelmar = Label(self.mar, text="00000000000", relief=SUNKEN, bg="yellow") self.labelmar.grid() self.labelmbr = Label(self.mbr, text="000000000000000", relief=SUNKEN) self.labelmbr.grid() self.labelvari = Label(self.vari, text="0", relief=SUNKEN) self.labelvari.grid() self.labelopr = Label(self.lopr, text="000", relief=SUNKEN) self.labelopr.grid() self.labelucs = Label(self.unitas, text="0") self.labelucs.grid() self.labelucf = Label(self.unitaf, text="0") self.labelucf.grid() self.labelucr = Label(self.unitar, text="0") self.labelucr.grid() self.labelucint = Label(self.unitaint, text="0") self.labelucint.grid() self.labelnstep = Label(self.nstep, text="1") self.labelnstep.grid() self.labeldelay = Label(self.delays, text=str(self.delay)) self.labeldelay.grid() self.labeltempo = Label(self.tempo, text=str(self.CD.tempo)) self.labeltempo.grid() self.labelac = Label(self.lac, text="000000000000000", relief=SUNKEN) self.labelac.grid() self.labelacint = Label(self.lacint, text="000000000000000", relief=SUNKEN) self.labelacint.grid() self.labelachex = Label(self.lachex, text="000000000000000", relief=SUNKEN) self.labelachex.grid() self.labelvare = Label(self.vare, text="0", relief=SUNKEN) self.labelvare.grid() def continua(self): """ Continua l'esecuzione dopo un break """ self.CD.S = True self.esegui() def micro_step(self): """ Esegue il metodo step del calcolatore didattico ed aggiorna """ if self.CD.S: self.CD.step(self.root, self.codice) if self.CD.tempo == 0 and not self.CD.F and not self.CD.R: self.CD.previstr = self.CD.nextistr self.aggiornaall() def step(self): """ Esegue il metodo step del calcolatore didattico ed aggiorna """ var = True if self.CD.S and self.CD.nstep > 0: while var and self.CD.S: self.CD.step(self.root, self.codice) if not self.CD.F and not self.CD.R and self.CD.tempo == 0: self.CD.nstep -= 1 self.aggiornaall() self.CD.previstr = self.CD.nextistr var = False if self.CD.nstep > 0: self.butstep.after(self.delay, self.step) else: self.CD.setnstep(1) else: self.CD.setnstep(1) self.aggiornaall() def esegui(self): """ Esegue il programma fino all'arresto della macchina tramite l'istruzione HLT """ while self.CD.S: self.CD.step(self.root, self.codice) if not self.CD.F and not self.CD.R and self.CD.tempo == 0: self.aggiornaall() self.CD.previstr = self.CD.nextistr break if self.CD.S: self.butesegui.after(self.delay, self.esegui) else: self.CD.setnstep(1) self.aggiornaall() def mini_step(self): """ Esegue un singolo ciclo della macchina """ if self.CD.S: for x in range(0, 4): self.CD.step(self.root, self.codice) self.CD.nstep = 1 self.aggiornaall() if self.CD.F is False and self.CD.R is False: self.CD.previstr = self.CD.nextistr def cerca_istr_prev(self): """ Evidenzia di VERDE l'ultima istruzione eseguita """ if self.CD.PC == "000000000000": return try: if self.CD.previstr == "" and int(self.CD.PC, 2) == self.CD.START: return else: pospc = str(3.0 + self.CD.previstr) self.Visualizza.tag_add( "PISTR", str(pospc[:-1] + "16"), str(pospc[:-1] + "end") ) self.Visualizza.tag_config("PISTR", background="green") self.Visualizza.see(pospc) except TypeError: pass # Errore che si ottiene durante il reset del CD # NOTA : METODO NON NECESSARIO NEL PROGRAMMA FINALE # def cerca_istr_corr(self): # """ # Evidenzia di verde l'istruzione che si dovrà eseguire # """ # if self.CD.PC == '000000000000': # return # try: # if int(self.CD.PC,2) == self.CD.START: # Inizio esecuzione del programma # Il PC e l'istruzione da eseguire sono allo stesso 'livello' # pos = str(3.0) # self.Visualizza.tag_add("ISTR", str(pos[0]+'.16'), str(pos[:-1]+'end')) # self.Visualizza.tag_config("ISTR", background = "green") # else: # pospc = str(3.0 + self.CD.nextistr) # self.Visualizza.tag_add("ISTR", str(pospc[:-1]+'16'), str(pospc[:-1]+'end')) # self.Visualizza.tag_config("ISTR", background = "green") # self.Visualizza.see(pospc) # except TypeError: # pass ## Errore che si ottiene durante il reset del CD def cerca_MAR(self): """ Evidenzia di giallo l'indirizzo puntato dal MAR """ try: pos = 3.0 stringa = self.Visualizza.get(str(pos), "end") while ( stringa[:12] != self.CD.MAR and int(pos) < len(self.CD.RAM) + 3 and len(self.CD.RAM) > 0 ): pos += 1 stringa = self.Visualizza.get(str(pos), "end") if int(pos) >= len(self.CD.RAM) + 3: return self.Visualizza.tag_add("MAR", pos, str(float(pos) + 0.12)) self.Visualizza.tag_config("MAR", background="yellow") except TypeError: pass # Errore che si ottiene durante il reset del CD def cerca_PC(self): """ Evidenzia di rosso l'indirizzo puntato da PC """ try: pos = 3.0 stringa = self.Visualizza.get(str(pos), "end") while ( stringa[:12] != self.CD.PC and int(pos) < len(self.CD.RAM) + 3 and len(self.CD.RAM) > 0 ): pos += 1 stringa = self.Visualizza.get(str(pos), "end") if int(pos) >= len(self.CD.RAM) + 3: return self.Visualizza.tag_add("PC", pos, str(float(pos) + 0.12)) self.Visualizza.tag_config("PC", background="red") except TypeError: pass # Errore che si ottiene durante il reset del CD def aggiornaout(self): """ Aggiorna micro e input/output """ self.aggiornamicro() self.aggiornainout() def aggiornamicro(self): """ Aggiorna le microistruzioni eseguite """ self.Visualizzamicro.delete(1.0, END) stringa = self.CD.microistruzioni self.Visualizzamicro.insert(INSERT, stringa) self.Visualizzamicro.see(END) def aggiornainout(self): """ Aggiorna gli input ed output di sistema """ self.Visualizzainout.delete(1.0, END) stringa = self.CD.inout self.Visualizzainout.insert(INSERT, stringa) self.Visualizzainout.see(END) def aggiornaram(self): """ Aggiorna lo stato della RAM """ self.Visualizza.delete(1.0, END) stringa = self.CD.statusRAM() self.Visualizza.insert(INSERT, stringa) self.cerca_MAR() self.cerca_PC() self.cerca_istr_prev() # self.cerca_istr_corr() #Non più necessaria nella versione finale def aggiornareg(self): """ Aggiorna lo stato dei Registri """ self.labelprogramc.config(text=self.CD.PC) self.labelmar.config(text=self.CD.MAR) self.labelmbr.config(text=self.CD.MBR) self.labelac.config(text=self.CD.AC) self.labelacint.config(text=str(self.CD.range(int(self.CD.AC, 2)))) self.labelachex.config(text=str((hex(int(self.CD.AC, 2))[2:].upper())).zfill(4)) self.labelvare.config(text=self.CD.E) self.labelvari.config(text=self.CD.I) self.labelopr.config(text=self.CD.OPR) def aggiornauc(self): """ Aggiorna lo stato dell'unita' di controllo """ if self.CD.S and not self.CD.breaks: self.labelucs.config(text=self.CD.S, bg="green") self.unitas.config(bg="green") elif not self.CD.S and self.CD.breaks: self.labelucs.config(text=self.CD.S, bg="Magenta2") self.unitas.config(bg="Magenta2") else: self.labelucs.config(text=self.CD.S, bg="red") self.unitas.config(bg="red") self.labelucf.config(text=self.CD.F) self.labelucr.config(text=self.CD.R) self.labelucint.config(text=self.CD.Interrupt) self.labeltempo.config(text=self.CD.tempo) def aggiornaall(self): """ Aggiorna tutto """ self.aggiornaram() self.aggiornareg() self.aggiornauc() self.aggiornamicro() self.aggiornaout() self.labelnstep.config(text=self.CD.nstep) def loading(self): """ Carica il contenuto del codice assembly decodificandolo in binario nella RAM """ contenuto = self.codice.Inserisci.get(1.0, END) if len(contenuto) > 1: self.resetCD() if self.CD.carica(contenuto, self) is not None: self.CD.S = 0 self.aggiornaall() def resetCD(self): """ Resetta il calcolatore didattico """ self.CD = pdp8() self.aggiornaall() def start(self): """ Mette la variabile Start (S) ad 1, cioe' True """ self.CD.S = True if self.CD.breaks == True: self.CD.breaks = False self.aggiornauc() def stop(self): """ Mette la variabile Start (S) ad 0, cioe' False """ self.CD.S = False self.aggiornauc() def setnstep(self): """ Setta, in base al valore passato, il numero di cicli da eseguire """ temp = askinteger( "Num Step", "Numero di step da eseguire", initialvalue=1, minvalue=1, parent=self.root, ) if temp is None: self.CD.setnstep(1) else: self.CD.setnstep(temp) self.labelnstep.config(text=self.CD.nstep) def setdelay(self): """ Setta, in base al valore passato, il ritardo di esecuzione. Il valore è espresso in millisecondi, di default = 1000 """ temp = askinteger( "Set Delay", "Ritardo in millisecondi", initialvalue=100, minvalue=1, parent=self.root, ) if temp is not None: self.delay = temp self.labeldelay.config(text=self.delay) def breakpoint(self): """ Setta o elimina i breakpoint dal programma caricato in memoria """ temp = askstring("Cella di memoria", "Indirizzo esadecimale", parent=self.root) if temp is not None: temp = self.CD.binario(int(temp, 16)).zfill(12) self.CD.breakpoint(temp) self.aggiornaram() def exit(self): """ Esce dal programma """ if askquestion("Exit", "Sicuro di voler uscire?", parent=self.master) == YES: self.codice.master.quit() self.codice.master.destroy() else: showinfo( "Suggerimento", """Forse e' meglio fare una pausa!""", icon=WARNING, parent=self.master, )
class OptimizerMainWindow: """ classdocs """ # TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"]) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode="w") as fd: fd.write(self.optimizer.optimizedSequence)
def youtube_dl_launcher_for_ffmpegaudioencoder(): # Imports---------------------------------------------------------------------------------------------------------- from tkinter import (filedialog, StringVar, Menu, E, W, N, S, LabelFrame, NORMAL, END, DISABLED, Checkbutton, Label, ttk, scrolledtext, messagebox, OptionMenu, Toplevel, WORD, Entry, Button, HORIZONTAL, SUNKEN, Text) import pyperclip, pathlib, threading, yt_dlp from re import sub from configparser import ConfigParser global main # --------------------------------------------------------------------------------------------------------- Imports # Main Gui & Windows ---------------------------------------------------------------------------------------------- def main_exit_function(): # Asks if the user is ready to exit confirm_exit = messagebox.askyesno( title='Prompt', message="Are you sure you want to exit the program?\n\n" " Note: This will end all current tasks!", parent=main) if confirm_exit: # If user selects Yes - destroy window main.destroy() # Main UI window -------------------------------------------------------------------------------------------------- try: # Checks rather or not the youtube-dl-gui window is already open if main is not None or Toplevel.winfo_exists(main): main.lift( ) # If youtube-dl-gui window exists then bring to top of all other windows except: # If youtube-dl-gui does not exist, create it... if not combined_with_ffmpeg_audio_encoder: from tkinter import Tk, PhotoImage main = Tk() # Make full tkinter loop if standalone main.iconphoto( True, PhotoImage(file="Runtime/Images/Youtube-DL-Gui.png")) if combined_with_ffmpeg_audio_encoder: main = Toplevel() # Make toplevel loop if NOT standalone main.title("Simple-Youtube-DL-Gui v1.21") main.configure(background="#434547") window_height = 500 window_width = 610 screen_width = main.winfo_screenwidth() screen_height = main.winfo_screenheight() x_coordinate = int((screen_width / 2) - (window_width / 2)) y_coordinate = int((screen_height / 2) - (window_height / 2)) main.geometry( f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}") main.protocol('WM_DELETE_WINDOW', main_exit_function) for n in range(4): # Loop to specify the needed column/row configures main.grid_columnconfigure(n, weight=1) for n in range(5): main.grid_rowconfigure(n, weight=1) # The entire top bar/menu is only present during standalone version ------------------------------------------- if not combined_with_ffmpeg_audio_encoder: my_menu_bar = Menu(main, tearoff=0) main.config(menu=my_menu_bar) file_menu = Menu(my_menu_bar, tearoff=0, activebackground='dim grey') my_menu_bar.add_cascade(label='File', menu=file_menu) file_menu.add_command( label='Exit', command=main_exit_function) # Exits the program options_menu = Menu(my_menu_bar, tearoff=0, activebackground='dim grey') my_menu_bar.add_cascade(label='Options', menu=options_menu) def set_ffmpeg_path(): global ffmpeg path = filedialog.askopenfilename( title='Select Location to "ffmpeg.exe"', initialdir='/', filetypes=[('ffmpeg', 'ffmpeg.exe')]) if path == '': pass elif path != '': ffmpeg = str(pathlib.Path(path)) config.set('ffmpeg_path', 'path', ffmpeg) with open(config_file, 'w') as configfile: config.write(configfile) options_menu.add_command(label='Set path to FFMPEG', command=set_ffmpeg_path) options_menu.add_separator() def reset_config(): msg = messagebox.askyesno( title='Warning', message= 'Are you sure you want to reset the config.ini file settings?' ) if not msg: pass if msg: try: config.set('ffmpeg_path', 'path', '') with open(config_file, 'w') as configfile: config.write(configfile) messagebox.showinfo( title='Prompt', message='Please restart the program') except: pass main.destroy() options_menu.add_command(label='Reset Configuration File', command=reset_config) from Packages.about import openaboutwindow def open_browser_for_ffmpeg(): import webbrowser webbrowser.open_new_tab( 'https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-essentials.7z' ) help_menu = Menu(my_menu_bar, tearoff=0, activebackground="dim grey") my_menu_bar.add_cascade(label="Help", menu=help_menu) help_menu.add_command(label="Download FFMPEG", command=open_browser_for_ffmpeg) help_menu.add_separator() help_menu.add_command(label="About", command=openaboutwindow) # ------------------------------------------- The entire top bar/menu is only present during standalone version # Bundled Apps ------------------------------------------------------------------------------------------------ config_file = 'Runtime/config.ini' # Defines location of config.ini config = ConfigParser() config.read(config_file) # This creates the config file if on the standalone version --------------------------------------------------- if not combined_with_ffmpeg_audio_encoder: if not config.has_section( 'ffmpeg_path'): # Create config parameters config.add_section('ffmpeg_path') if not config.has_option('ffmpeg_path', 'path'): config.set('ffmpeg_path', 'path', '') try: with open(config_file, 'w') as configfile: config.write(configfile) except: messagebox.showinfo( title='Error', message= 'Could Not Write to config.ini file, delete and try again') # --------------------------------------------------- This creates the config file if on the standalone version # Define location of FFMPEG in a variable --------------------------------------------------------------------- ffmpeg = pathlib.Path(config['ffmpeg_path']['path'].replace('"', '')) # --------------------------------------------------------------------- Define location of FFMPEG in a variable # Code needed to add location of ffmpeg.exe in the event it's missing for standalone version ------------------ if not combined_with_ffmpeg_audio_encoder: if not pathlib.Path(ffmpeg).is_file( ): # Checks config for bundled app paths path ------------------------ def check_ffmpeg( ): # FFMPEG ------------------------------------------------------------------------- global ffmpeg import shutil def write_path_to_ffmpeg( ): # Writes path to ffmpeg to the config.ini file try: config.set('ffmpeg_path', 'path', ffmpeg) with open(config_file, 'w') as configfile: config.write(configfile) except: pass if shutil.which('ffmpeg') is not None: ffmpeg = str(pathlib.Path( shutil.which('ffmpeg'))).lower() messagebox.showinfo( title='Prompt!', message='ffmpeg.exe found on system PATH, ' 'automatically setting path to location.\n\n' 'Note: This can be changed in the config.ini file' ' or in the Options menu') if pathlib.Path("Apps/ffmpeg/ffmpeg.exe").is_file(): rem_ffmpeg = messagebox.askyesno( title='Delete Included ffmpeg?', message= 'Would you like to delete the included FFMPEG?' ) if rem_ffmpeg: try: shutil.rmtree( str(pathlib.Path("Apps/ffmpeg"))) except: pass write_path_to_ffmpeg() elif pathlib.Path("Apps/ffmpeg/ffmpeg.exe").is_file(): messagebox.showinfo( title='Info', message='Program will use the included ' '"ffmpeg.exe" located in the "Apps" folder') ffmpeg = str(pathlib.Path("Apps/ffmpeg/ffmpeg.exe")) write_path_to_ffmpeg() else: error_prompt = messagebox.askyesno( title='Error!', message='Cannot find ffmpeg, ' 'please navigate to "ffmpeg.exe"') if not error_prompt: messagebox.showerror( title='Error!', message= 'Program requires ffmpeg.exe to work correctly' ) main.destroy() if error_prompt: set_ffmpeg_path() if not pathlib.Path(ffmpeg).is_file(): messagebox.showerror( title='Error!', message= 'Program requires ffmpeg.exe to work correctly' ) main.destroy() check_ffmpeg( ) # FFMPEG ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------------------ Bundled Apps # ------------------ Code needed to add location of ffmpeg.exe in the event it's missing for standalone version # Link Frame -------------------------------------------------------------------------------------------------- link_frame = LabelFrame(main, text=' Paste Link ') link_frame.grid(row=0, columnspan=4, sticky=E + W, padx=20, pady=(10, 10)) link_frame.configure(fg="white", bg="#434547", bd=3) link_frame.rowconfigure(1, weight=1) link_frame.columnconfigure(0, weight=1) link_frame.columnconfigure(1, weight=1) # -------------------------------------------------------------------------------------------------- Link Frame # Options Frame ----------------------------------------------------------------------------------------------- options_frame = LabelFrame(main, text=' Options ') options_frame.grid(row=2, columnspan=4, sticky=E + W, padx=20, pady=(10, 10)) options_frame.configure(fg="white", bg="#434547", bd=3) options_frame.rowconfigure(1, weight=1) options_frame.columnconfigure(0, weight=1) options_frame.columnconfigure(1, weight=1) # ----------------------------------------------------------------------------------------------- Options Frame # Input Frame ------------------------------------------------------------------------------------------------- global link_input_label input_frame = LabelFrame(main, text=' Input ') input_frame.grid(row=1, columnspan=4, sticky=E + W, padx=20, pady=(4, 10)) input_frame.configure(fg="white", bg="#434547", bd=3) input_frame.rowconfigure(1, weight=1) input_frame.columnconfigure(0, weight=1) input_frame.columnconfigure(1, weight=1) link_input_label = Label( input_frame, text='Please Paste Link Above and Select "Add Link"', background="#434547", foreground="white", height=1, font=("Helvetica", 10)) link_input_label.grid(row=0, column=0, columnspan=4, padx=8, pady=(4, 7), sticky=W + E) # ------------------------------------------------------------------------------------------------- Input Frame # File Output ------------------------------------------------------------------------------------------------- def file_save(): global VideoOutput save_entry.config(state=NORMAL) # save_entry.delete( 0, END ) # This function clears entry box in order to add new link to entry box save_entry.config(state=DISABLED) # VideoOutput = filedialog.askdirectory( parent=main ) # Pop up window to choose a save directory location if VideoOutput: save_for_entry = '"' + VideoOutput + '/"' # Completes save directory and adds quotes save_entry.config(state=NORMAL) # save_entry.insert( 0, save_for_entry) # Adds download_link to entry box save_entry.config(state=DISABLED) # start_job_btn.config(state=NORMAL) # Enables Button # ------------------------------------------------------------------------------------------------- File Output # Best Video Function ----------------------------------------------------------------------------------------- def set_video_only(): if video_only.get( ) == 'on': # If video checkbutton is checked enable video options menu and set audio off highest_quality_audio_only.set('') video_menu_options_menu.config(state=NORMAL) audio_menu_options_menu.config(state=DISABLED) audio_menu_options.set('Extract Only') if video_only.get( ) != 'on': # If not checked, set video_only to on video_only.set( 'on' ) # This prevents you from being able to de-select the check button # ----------------------------------------------------------------------------------------- Audio Only Function def highest_quality_audio_only_toggle(): if highest_quality_audio_only.get( ) == 'on': # If audio checkbutton is checked video_only.set( '') # enables video options menu and set audio to off video_menu_options_menu.config(state=DISABLED) audio_menu_options_menu.config(state=NORMAL) if highest_quality_audio_only.get( ) != 'on': # If not checked, set audio_only to on highest_quality_audio_only.set( 'on' ) # This prevents you from being able to de-select the check button # Video Only Checkbutton -------------------------------------------------------------------------------------- video_only = StringVar() video_only_checkbox = Checkbutton( options_frame, text='Best Video + Audio\nMuxed File', variable=video_only, onvalue='on', offvalue='', command=set_video_only, takefocus=False) video_only_checkbox.grid(row=0, column=1, columnspan=1, rowspan=1, padx=10, pady=6, sticky=N + S + E + W) video_only_checkbox.configure(background="#434547", foreground="white", activebackground="#434547", activeforeground="white", selectcolor="#434547", font=("Helvetica", 12)) video_only.set('on') # Enables Best Video by default # -------------------------------------------------------------------------------------- Video Only Checkbutton # Highest Quality Audio Only ---------------------------------------------------------------------------------- highest_quality_audio_only = StringVar() highest_quality_audio_only_checkbox = Checkbutton( options_frame, text='Audio Only', variable=highest_quality_audio_only, onvalue='on', offvalue='', command=highest_quality_audio_only_toggle, takefocus=False) highest_quality_audio_only_checkbox.grid(row=0, column=2, columnspan=1, rowspan=1, padx=10, pady=3, sticky=N + S + E + W) highest_quality_audio_only_checkbox.configure( background="#434547", foreground="white", activebackground="#434547", activeforeground="white", selectcolor="#434547", font=("Helvetica", 12)) highest_quality_audio_only.set('') # Disables audio only by default # ---------------------------------------------------------------------------------- Highest Quality Audio Only # Download Rate ----------------------------------------------------------------------------------------------- def download_rate_menu_hover(e): download_rate_menu["bg"] = "grey" download_rate_menu["activebackground"] = "grey" def download_rate_menu_hover_leave(e): download_rate_menu["bg"] = "#23272A" download_rate = StringVar(main) download_rate_choices = { 'Unlimited': 131072000000000, '10 - KiB (Slowest)': 1280, '50 - KiB': 6400, '100 - KiB': 12800, '250 - KiB': 32000, '500 - KiB': 64000, '750 - KiB': 96000, '1 - MiB': 131072, '5 - MiB': 655360, '10 - MiB': 1310720, '30 - MiB': 3932160, '50 - MiB': 6553600, '100 - MiB': 13107200, '250 - MiB': 32768000, '500 - MiB': 65536000, '750 - MiB': 98304000, '1000 - MiB (Fastest)': 13107200000 } download_rate_menu_label = Label(options_frame, text="Download Rate :", background="#434547", foreground="white") download_rate_menu_label.grid(row=0, column=0, columnspan=1, padx=10, pady=(3, 10), sticky=W + E) download_rate_menu = OptionMenu(options_frame, download_rate, *download_rate_choices.keys()) download_rate_menu.config(background="#23272A", foreground="white", highlightthickness=1, width=15) download_rate_menu.grid(row=1, column=0, columnspan=1, padx=10, pady=(3, 20)) download_rate.set('Unlimited') download_rate_menu["menu"].configure(activebackground="dim grey") download_rate_menu.bind("<Enter>", download_rate_menu_hover) download_rate_menu.bind("<Leave>", download_rate_menu_hover_leave) # ----------------------------------------------------------------------------------------------- Download Rate # Video Options ----------------------------------------------------------------------------------------------- def video_menu_options_menu_hover(e): video_menu_options_menu["bg"] = "grey" video_menu_options_menu["activebackground"] = "grey" def video_menu_options_menu_hover_leave(e): video_menu_options_menu["bg"] = "#23272A" video_menu_options = StringVar(main) video_menu_options_choices = { '(bv+ba/b) Best video + audio format ' 'and combine both, or download best combined format': 'bv+ba/b', '(Same as above with video up to 480p)': 'bv*[height<=480]+ba/b[height<=480] / wv*+ba/w', '(Same as above with video up to 720p)': 'bv*[height<=720]+ba/b[height<=720] / wv*+ba/w', '(Same as above with video up to 1080p)': 'bv*[height<=1080]+ba/b[height<=1080] / wv*+ba/w', '(Same as above with video up to 1440p)': 'bv*[height<=1440]+ba/b[height<=1440] / wv*+ba/w', '(Same as above with video up to 2160p)': 'bv*[height<=2160]+ba/b[height<=2160] / wv*+ba/w', '(Default) (bv*+ba/b) Best video and if missing audio, ' 'merge it with best available audio': 'bv*+ba/b', '(bv) Best video only': 'bv', 'Download the best h264 video, ' 'or best video if no such codec': '(bv * +ba / b)[vcodec ^= avc1] / (bv * +ba / b)' } video_menu_options_menu = OptionMenu( options_frame, video_menu_options, *video_menu_options_choices.keys()) video_menu_options_menu.config(background="#23272A", foreground="white", highlightthickness=1, width=15, anchor=W) video_menu_options_menu.grid(row=1, column=1, columnspan=1, padx=10, pady=(3, 20)) video_menu_options.set( '(Default) (bv*+ba/b) Best video and if missing audio, ' 'merge it with best available audio') video_menu_options_menu["menu"].configure(activebackground="dim grey") video_menu_options_menu.bind("<Enter>", video_menu_options_menu_hover) video_menu_options_menu.bind("<Leave>", video_menu_options_menu_hover_leave) # ----------------------------------------------------------------------------------------------- Video Options # Audio Options ----------------------------------------------------------------------------------------------- def audio_menu_options_menu_hover(e): audio_menu_options_menu["bg"] = "grey" audio_menu_options_menu["activebackground"] = "grey" def audio_menu_options_menu_hover_leave(e): audio_menu_options_menu["bg"] = "#23272A" audio_menu_options = StringVar(main) audio_menu_options_choices = { 'Extract Only': '', 'Encode to mp3': 'mp3', 'Encode to flac': 'flac', 'Encode to m4a': 'm4a', 'Encode to opus': 'opus', 'Encode to vorbis': 'vorbis', 'Encode to wav': 'wav' } audio_menu_options_menu = OptionMenu( options_frame, audio_menu_options, *audio_menu_options_choices.keys()) audio_menu_options_menu.config(background="#23272A", foreground="white", highlightthickness=1, width=15, anchor=W, state=DISABLED) audio_menu_options_menu.grid(row=1, column=2, columnspan=1, padx=10, pady=(3, 20)) audio_menu_options.set('Extract Only') audio_menu_options_menu["menu"].configure(activebackground="dim grey") audio_menu_options_menu.bind("<Enter>", audio_menu_options_menu_hover) audio_menu_options_menu.bind("<Leave>", audio_menu_options_menu_hover_leave) # ----------------------------------------------------------------------------------------------- Audio Options # Add Link to variable ---------------------------------------------------------------------------------------- def apply_link(): global download_link, link_input_label, extracted_title_name link_entry.config(state=NORMAL) # link_entry.delete( 0, END ) # This function clears entry box in order to add new link to entry box link_entry.config(state=DISABLED) # download_link = text_area.get(1.0, END).rstrip( "\n") # Pasted download link and strips the unneeded newline text_area.delete( 1.0, END ) # Deletes entry box where you pasted your link as it stores it into var link_entry.config(state=NORMAL) # link_entry.insert(0, download_link) # Adds download_link to entry box link_entry.config(state=DISABLED) # save_btn.config(state=NORMAL) # try: # The code below checks link input for the title and adds it to a variable for use with the gui with yt_dlp.YoutubeDL({'noplaylist': True}) as ydl: dl_link_input = ydl.extract_info(download_link, download=False) string_one = sub('[^a-zA-Z0-9 \n]', '', dl_link_input['title']) string_two = " ".join(string_one.split()) extracted_title_name = pathlib.Path( string_two[:128]).with_suffix('') except: extracted_title_name = download_link link_input_label.configure(text=extracted_title_name) # ---------------------------------------------------------------------------------------------------- Add Link # Start Job --------------------------------------------------------------------------------------------------- def start_job( ): # This is the progress window and everything that has to do with actually processing the file global download_link def close_encode(): confirm_exit = messagebox.askyesno( title='Prompt', message="Are you sure you want to stop progress?", parent=window) if confirm_exit: # If user selects 'Yes' to the above message prompt, destroy the window in question window.destroy() def close_window( ): # This thread is needed in order to close the window while the GUI is processing a file thread = threading.Thread(target=close_encode) thread.start() window = Toplevel(main) # Programs download window window.title( extracted_title_name ) # Takes extracted_title_name and adds it as the windows title window.configure(background='#434547') encode_label = Label(window, text='- ' * 22 + 'Progress ' + '- ' * 22, font=('Times New Roman', 14), background='#434547', foreground='white') encode_label.grid(column=0, columnspan=2, row=0) window.grid_columnconfigure(0, weight=1) window.grid_rowconfigure(0, weight=1) window.grid_rowconfigure(1, weight=1) window.protocol('WM_DELETE_WINDOW', close_window) window.geometry('600x140') encode_window_progress = Text(window, height=2, relief=SUNKEN, bd=3) encode_window_progress.grid(row=1, column=0, columnspan=2, pady=(10, 6), padx=10, sticky=E + W) encode_window_progress.insert(END, '') app_progress_bar = ttk.Progressbar(window, orient=HORIZONTAL, mode='determinate') app_progress_bar.grid(row=2, columnspan=2, pady=(10, 10), padx=15, sticky=E + W) def my_hook( d ): # This updates the progress bar with the correct percentage if d['status'] == 'downloading': p = d['_percent_str'] p = p.replace('%', '') app_progress_bar['value'] = float(p) class MyLogger: # ytb-dl logger, allows the program to get all the needed info from the program global download_info_string def debug(self, msg): # For compatability with youtube-dl, both debug and info are passed into debug # You can distinguish them by the prefix '[debug] ' if msg.startswith('[debug] '): pass else: self.info(msg) def info(self, msg): encode_window_progress.delete('1.0', END) encode_window_progress.insert(END, msg) def warning(self, msg): pass def error(self, msg): pass if video_only.get( ) == 'on': # If "Best Video..." is selected then use these options for ytb-dl ydl_opts = { 'ratelimit': download_rate_choices[download_rate.get()], 'progress_hooks': [my_hook], 'noplaylist': True, 'overwrites': True, 'merge_output_format': 'mkv', 'final_ext': 'mkv', 'outtmpl': str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s', 'ffmpeg_location': str(pathlib.Path(ffmpeg)), 'logger': MyLogger(), "progress_with_newline": True, 'format': video_menu_options_choices[video_menu_options.get()], 'prefer_ffmpeg': True } if video_only.get() != 'on' and audio_menu_options.get( ) == 'Extract Only': # If "Best Video..." is NOT selected and "Audio Menu" is set to Extract Only ydl_opts = { 'ratelimit': download_rate_choices[download_rate.get()], 'progress_hooks': [my_hook], 'noplaylist': True, 'overwrites': True, 'outtmpl': str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s', 'ffmpeg_location': str(pathlib.Path(ffmpeg)), 'logger': MyLogger(), "progress_with_newline": True, 'format': 'bestaudio/best', 'extractaudio': True, 'prefer_ffmpeg': True } if video_only.get() != 'on' and audio_menu_options.get( ) != 'Extract Only': # If "Best Video..." is NOT selected and "Audio Menu" is set to encode to another codec ydl_opts = { 'ratelimit': download_rate_choices[download_rate.get()], 'progress_hooks': [my_hook], 'noplaylist': True, 'overwrites': True, 'outtmpl': str(pathlib.Path(VideoOutput)) + '/%(title)s.%(ext)s', 'ffmpeg_location': str(pathlib.Path(ffmpeg)), 'logger': MyLogger(), "progress_with_newline": True, 'format': 'bestaudio/best', 'extractaudio': True, 'prefer_ffmpeg': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': audio_menu_options_choices[audio_menu_options.get()], 'preferredquality': '0' }] } with yt_dlp.YoutubeDL( ydl_opts ) as ydl: # Block of code needed to process the link/file ydl.download([download_link]) window.destroy( ) # Once the job is complete this destroys the download/processing window # --------------------------------------------------------------------------------------------------- Start Job # Buttons and Entry Box's ------------------------------------------------------------------------------------- text_area = scrolledtext.ScrolledText(link_frame, wrap=WORD, width=69, height=1, font=("Times New Roman", 14), foreground="grey") text_area.insert(END, "Right Click or 'Ctrl + V'") text_area.grid(row=0, column=0, columnspan=3, pady=(1, 5), padx=10, sticky=W + E) # ------------------------------------------------------------------ Right click menu to paste in text_area box def paste_clipboard( ): # Allows user to paste what ever is in their clipboard with right click and paste text_area.delete(1.0, END) text_area.config(foreground="black") text_area.insert(END, pyperclip.paste()) def remove_text( e): # Deletes current text in text box upon 'Left Clicking' text_area.config(foreground="black") text_area.delete(1.0, END) link_input_label.configure( text='Please Paste Link Above and Select "Add Link"') link_entry.config(state=NORMAL) # link_entry.delete( 0, END ) # This function clears entry box in order to add new link to entry box link_entry.config(state=DISABLED) # m = Menu(main, tearoff=0) # Pop up menu for 'Paste' m.add_command(label="Paste", command=paste_clipboard) def do_popup( event ): # This code allows the program to know where the cursor is upon right clicking try: m.tk_popup(event.x_root, event.y_root) finally: m.grab_release() text_area.bind("<Button-3>", do_popup) # Uses right click to make a function text_area.bind("<Button-1>", remove_text) # Uses left click to make a function # Right click menu to paste in text_area box ------------------------------------------------------------------ link_entry = Entry(link_frame, borderwidth=4, background="#CACACA", state=DISABLED, width=70) link_entry.grid(row=1, column=1, columnspan=2, padx=10, pady=(0, 0), sticky=W + E) def apply_btn_hover(e): apply_btn["bg"] = "grey" def apply_btn_hover_leave(e): apply_btn["bg"] = "#8b0000" apply_btn = Button(link_frame, text="Add Link", command=apply_link, foreground="white", background="#8b0000", width=30) apply_btn.grid(row=1, column=0, columnspan=1, padx=10, pady=5, sticky=W) apply_btn.bind("<Enter>", apply_btn_hover) apply_btn.bind("<Leave>", apply_btn_hover_leave) def save_btn_hover(e): save_btn["bg"] = "grey" def save_btn_hover_leave(e): save_btn["bg"] = "#8b0000" save_btn = Button(main, text="Save Directory", command=file_save, foreground="white", background="#8b0000", state=DISABLED) save_btn.grid(row=4, column=0, columnspan=1, padx=10, pady=(15, 0), sticky=W + E) save_btn.bind("<Enter>", save_btn_hover) save_btn.bind("<Leave>", save_btn_hover_leave) save_entry = Entry(main, borderwidth=4, background="#CACACA", state=DISABLED) save_entry.grid(row=4, column=1, columnspan=3, padx=10, pady=(15, 0), sticky=W + E) def start_job_btn_hover(e): start_job_btn["bg"] = "grey" def start_job_btn_hover_leave(e): start_job_btn["bg"] = "#8b0000" start_job_btn = Button( main, text="Start Job", command=lambda: threading.Thread(target=start_job).start(), foreground="white", background="#8b0000", state=DISABLED) start_job_btn.grid(row=5, column=3, columnspan=1, padx=10, pady=(15, 15), sticky=N + S + W + E) start_job_btn.bind("<Enter>", start_job_btn_hover) start_job_btn.bind("<Leave>", start_job_btn_hover_leave) # ------------------------------------------------------------------------------------- Buttons and Entry Box's # End Loop ---------------------------------------------------------------------------------------------------- main.mainloop()
def _lowerFrame(self): frame = LabelFrame(self.root, text="Conversion") frame.grid(row=1, column=0, sticky="snew", padx=(5, 5), pady=(5, 5), ipady=10, ipadx=10) #frame.columnconfigure(0,weight=1) frame.columnconfigure(1, weight=1) frame.rowconfigure(2, weight=1) text = "You can change the type of media files, by giving their path at the previous step,\nthen choose the new format of them, we have design it to be very easy for novice users it's just one click to go" lbl = Label(frame, text=text, justify="center") lbl.grid(row=0, column=0, sticky="we", padx=(10, 10), pady=(15, 20), columnspan=2) Label(frame, text="choose profile ").grid(row=1, column=0, padx=(10, 10), sticky="w") def addOptionMenu(row, col): self.format = StringVar(frame) options = [ "mp3", "mp4", "wav", "m4a", "flac", "wma", "acc", "3gp", "ogg", "mp2", "amr", "webm", "gif" ] self.format.set(options[0]) optionMenu = Combobox(frame, textvariable=self.format, state="readonly", values=options) optionMenu.grid(row=row, column=col, sticky="we", ipady=1, padx=(10, 10)) addOptionMenu(1, 1) self.convertBtn = Button( frame, text="Convert", relief="groove", command=lambda: self._startNewThread(self._conversion, ())) self.convertBtn.grid(row=2, column=1, sticky="se", columnspan=2, padx=(10, 10), pady=(10, 5), ipady=2, ipadx=3) self.convertInfo = Label(frame, text="") self.convertInfo.grid(row=2, column=0, sticky="sw", padx=(10, 10), pady=(10, 5), ipady=2, ipadx=3)
def __init__(self, thread_cls): super().__init__() self.thread_cls = thread_cls self.img = None self.title("Emotion API") self.grid() self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(1, weight=2) self.grid_rowconfigure(4, weight=1) # Create LabelFrames lf_key = LabelFrame(self, text="Emotion API Key") lf_key.grid(row=0, column=0, columnspan=1, sticky=W + E, padx=5, pady=3) lf_key.grid_columnconfigure(0, weight=1) lf_mode = LabelFrame(self, text="Mode") lf_mode.grid(row=1, column=0, columnspan=1, sticky=W + E, padx=5, pady=3) for i in range(3): lf_mode.grid_columnconfigure(i, weight=1) lf_source = LabelFrame(self, text="Image Source", height=50) lf_source.grid(row=2, column=0, columnspan=1, sticky=W + E, padx=5, pady=3) lf_source.rowconfigure(0, weight=1) lf_source.grid_propagate(False) lf_source.columnconfigure(0, weight=1) lf_source.columnconfigure(1, weight=5) lf_source.columnconfigure(2, weight=1) lf_request = LabelFrame(self, text="Request Result") lf_request.grid(row=3, column=0, columnspan=1, sticky=W + E, padx=5, pady=3) lf_request.grid_columnconfigure(0, weight=1) lf_console = LabelFrame(self, text="Console") lf_console.grid(row=4, column=0, columnspan=1, sticky=N + S + W + E, padx=5, pady=3) lf_console.grid_columnconfigure(0, weight=1) lf_console.grid_rowconfigure(0, weight=1) lf_img = LabelFrame(self, text="Output Image") lf_img.grid(row=0, column=1, rowspan=5, sticky=N + S + W + E) lf_img.grid_columnconfigure(0, weight=1) lf_img.grid_rowconfigure(0, weight=1) # Create Input Fields self.ety_key = Entry(lf_key) self.ety_key.insert(END, "bfe9b2f471e04b29a8fabfe3dd9f647d") self.ety_key.grid(sticky=W + E, padx=3) self.var_mode = StringVar() Radiobutton(lf_mode, text="Local Image", variable=self.var_mode, value='local', command=self.change_mode).grid(row=1, column=0) Radiobutton(lf_mode, text="URL Image", variable=self.var_mode, value='url', command=self.change_mode).grid(row=1, column=1) Radiobutton(lf_mode, text="Camera", variable=self.var_mode, value='cam', command=self.change_mode).grid(row=1, column=2) # Local Image Source self.lb_filename = Label(lf_source, text="..") self.btn_fileopen = Button(lf_source, text="Open..", command=self.get_local_img) # URL Image Source self.lb_url = Label(lf_source, text="URL") self.ety_url = Entry(lf_source) self.ety_url.insert(END, "https://i.imgflip.com/qiev6.jpg") self.btn_url = Button(lf_source, text="Get Image", command=self.get_url_img) # Camera Image Source self.btn_get_cam = Button(lf_source, text="Get the Camera Image", command=self.get_cam_img) # set default mode: local raw image self.var_mode.set('local') self.change_mode() # request btn self.btn_request = Button(lf_request, text="Request Result", command=self.run_request, state='disable') self.btn_request.grid(sticky=W + E) # Create Output Console self.console = ScrolledText(lf_console, state='disable', width=60, bg='gray20', fg='white') self.console.grid(sticky=N + S + W + E) # Create Output Image self.plot = ResultImg(lf_img) self.plot.grid(sticky=N + S + W + E)