class MainWindow(Tk): def __init__(self): Tk.__init__(self) self.title(mainWindowTitle) self.resizable(width=0, height=0) self.__setStyles() self.__initializeComponents() self.__dataController = DataController(); self.mainloop() def __initializeComponents(self): self.imageCanvas = Canvas(master=self, width=imageCanvasWidth, height=windowElementsHeight, bg="white") self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0), pady=windowPadding, fill=BOTH) self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth, height=windowElementsHeight) self.buttonsFrame.propagate(0) self.loadFileButton = Button(master=self.buttonsFrame, text=loadFileButtonText, command=self.loadFileButtonClick) self.loadFileButton.pack(fill=X, pady=buttonsPadding); self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText) self.colorByLabel.pack(fill=X) self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED, values=colorByComboboxValues) self.colorByCombobox.set(colorByComboboxValues[0]) self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange) self.colorByCombobox.pack(fill=X, pady=buttonsPadding) self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText) self.rejectedValuesPercentLabel.pack(fill=X) self.rejectedValuesPercentEntry = Entry(self.buttonsFrame) self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent) self.rejectedValuesPercentEntry.config(state=DISABLED) self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding) self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText) self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText) self.colorsTableLengthLabel.pack(fill=X) self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel) self.colorsTableLengthEntry.insert(0, defaultColorsTableLength) self.colorsTableLengthEntry.config(state=DISABLED) self.colorsTableLengthEntry.pack(fill=X) self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText) self.scaleTypeLabel.pack(fill=X) self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED, values=scaleTypesComboboxValues) self.scaleTypeCombobox.set(scaleTypesComboboxValues[0]) self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange) self.scaleTypeCombobox.pack(fill=X) self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText) self.colorsTableMinLabel.pack(fill=X) self.colorsTableMinEntry = Entry(self.colorsSettingsPanel) self.colorsTableMinEntry.insert(0, defaultColorsTableMin) self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMinEntry.pack(fill=X) self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText) self.colorsTableMaxLabel.pack(fill=X) self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel) self.colorsTableMaxEntry.insert(0, defaultColorsTableMax) self.colorsTableMaxEntry.config(state=DISABLED) self.colorsTableMaxEntry.pack(fill=X) self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding) self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText, state=DISABLED, command=self.__redrawButtonClick) self.redrawButton.pack(fill=X, pady=buttonsPadding) self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH) def __setStyles(self): Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont) def loadFileButtonClick(self): fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')]) if (fileName): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.lastFileName = fileName; self.title(mainWindowTitle + " " + fileName) self.__draw(fileName) tkMessageBox.showinfo(measureDialogTitle, measureDialogText + str(self.__dataController.getMeasure(fileName))) self.redrawButton.config(state=NORMAL) self.colorByCombobox.config(state="readonly") self.colorsTableLengthEntry.config(state=NORMAL) self.scaleTypeCombobox.config(state="readonly") def __redrawButtonClick(self): if (not self.__getInputParams()): self.__showInvalidInputMessage() return self.__draw(self.lastFileName) def __scaleTypeComboboxChange(self, event): if (self.scaleTypeCombobox.get() == relativeScaleType): self.colorsTableMinEntry.config(state=DISABLED) self.colorsTableMaxEntry.config(state=DISABLED) else: self.colorsTableMinEntry.config(state=NORMAL) self.colorsTableMaxEntry.config(state=NORMAL) def __colorByComboboxChange(self, event): if (self.colorByCombobox.get() == colorByNoneOption): self.rejectedValuesPercentEntry.config(state=DISABLED) else: self.rejectedValuesPercentEntry.config(state=NORMAL) def __draw(self, fileName): self.imageCanvas.delete(ALL) dataForDrawing = self.__dataController.getDataForDrawing( fileName, self.colorByCombobox.get(), self.colorsTableLength, self.scaleTypeCombobox.get(), self.colorsTableMinValue, self.colorsTableMaxValue, self.rejectedValuesPercent) for package in dataForDrawing: x = package[0]; y = package[1]; color = package[2]; self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color) def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv): allSpeeds = self.__getAllSpeeds(dataPackages) minSpeed = min(allSpeeds) maxSpeed = max(allSpeeds) if (self.scaleTypeCombobox.get() == relativeScaleType): colorsTableMinValue = minSpeed colorsTableMaxValue = maxSpeed else: colorsTableMinValue = self.colorsTableMinValue colorsTableMaxValue = self.colorsTableMaxValue i = 0 for package in dataPackages: x = (package[dataXNumber] - minX) * ratio y = (package[dataYNumber] - minY) * ratio color = hsv.getColorByValue(colorsTableMinValue, colorsTableMaxValue, allSpeeds[i]) tk_rgb = "#%02x%02x%02x" % color self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb) i += 1 def __showInvalidInputMessage(self): tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText) def __getInputParams(self): try: self.colorsTableLength = int(self.colorsTableLengthEntry.get()) self.colorsTableMinValue = float(self.colorsTableMinEntry.get()) self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get()) self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get()) if (self.colorsTableLength < 1 or self.colorsTableMinValue >= self.colorsTableMaxValue or self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100): raise return True except: return False
def initUI(self): self.parent.title("Resistor Calculator") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.columnconfigure(4, pad=3) self.columnconfigure(5, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.rowconfigure(7, pad=3) self.rowconfigure(8, pad=3) self.rowconfigure(9, pad=3) self.rowconfigure(10, pad=3) self.rowconfigure(11, pad=3) self.rowconfigure(12, pad=3) entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W + E) global resistance resistance = "" def ringOne(number): entry.delete(0, END) entry.insert(0, str(number)) global resistance resistance = resistance + str(number) def ringTwo(number): ent = str(number) entry.insert(END, str(number)) global resistance resistance = resistance + str(number) def ringThree(number): ent = str(number) entry.insert(END, str(number)) global resistance resistance = resistance + str(number) def ringFour(number): global resistance entry.delete(0, END) for x in range(0, number): resistance = resistance + "0" ent = "Resistance is: " + resistance entry.insert(END, ent) resistance = "" def cls(): global resistance resistance = "" entry.delete(0, END) entry.insert(0, "Please Select ring colors") entry.insert(0, "Please Select ring colors") entry.config(justify=RIGHT) black = Button(self, text="Black", command=lambda: ringOne(0)) black.grid(row=2, column=0) brown = Button(self, text="Brown", command=lambda: ringOne(1)) brown.grid(row=3, column=0) red = Button(self, text="Red", command=lambda: ringOne(2)) red.grid(row=4, column=0) orange = Button(self, text="Orange", command=lambda: ringOne(3)) orange.grid(row=5, column=0) yellow = Button(self, text="Yellow", command=lambda: ringOne(4)) yellow.grid(row=6, column=0) green = Button(self, text="Green", command=lambda: ringOne(5)) green.grid(row=7, column=0) blue = Button(self, text="Blue", command=lambda: ringOne(6)) blue.grid(row=8, column=0) violet = Button(self, text="Violet", command=lambda: ringOne(7)) violet.grid(row=9, column=0) grey = Button(self, text="Grey", command=lambda: ringOne(8)) grey.grid(row=10, column=0) white = Button(self, text="White", command=lambda: ringOne(9)) white.grid(row=11, column=0) black2 = Button(self, text="Black", command=lambda: ringTwo(0)) black2.grid(row=2, column=1) brown2 = Button(self, text="Brown", command=lambda: ringTwo(1)) brown2.grid(row=3, column=1) red2 = Button(self, text="Red", command=lambda: ringTwo(2)) red2.grid(row=4, column=1) orange2 = Button(self, text="Orange", command=lambda: ringTwo(3)) orange2.grid(row=5, column=1) yellow2 = Button(self, text="Yellow", command=lambda: ringTwo(4)) yellow2.grid(row=6, column=1) green2 = Button(self, text="Green", command=lambda: ringTwo(5)) green2.grid(row=7, column=1) blue2 = Button(self, text="Blue", command=lambda: ringTwo(6)) blue2.grid(row=8, column=1) violet2 = Button(self, text="Violet", command=lambda: ringTwo(7)) violet2.grid(row=9, column=1) grey2 = Button(self, text="Grey", command=lambda: ringTwo(8)) grey2.grid(row=10, column=1) white2 = Button(self, text="White", command=lambda: ringTwo(9)) white2.grid(row=11, column=1) black3 = Button(self, text="Black", command=lambda: ringThree(0)) black3.grid(row=2, column=2) brown3 = Button(self, text="Brown", command=lambda: ringThree(1)) brown3.grid(row=3, column=2) red3 = Button(self, text="Red", command=lambda: ringThree(2)) red3.grid(row=4, column=2) orange3 = Button(self, text="Orange", command=lambda: ringThree(3)) orange3.grid(row=5, column=2) yellow3 = Button(self, text="Yellow", command=lambda: ringThree(4)) yellow3.grid(row=6, column=2) green3 = Button(self, text="Green", command=lambda: ringThree(5)) green3.grid(row=7, column=2) blue3 = Button(self, text="Blue", command=lambda: ringThree(6)) blue3.grid(row=8, column=2) violet3 = Button(self, text="Violet", command=lambda: ringThree(7)) violet3.grid(row=9, column=2) grey3 = Button(self, text="Grey", command=lambda: ringThree(8)) grey3.grid(row=10, column=2) white3 = Button(self, text="White", command=lambda: ringThree(9)) white3.grid(row=11, column=2) black4 = Button(self, text="Black", command=lambda: ringFour(0)) black4.grid(row=2, column=3) brown4 = Button(self, text="Brown", command=lambda: ringFour(1)) brown4.grid(row=3, column=3) red4 = Button(self, text="Red", command=lambda: ringFour(2)) red4.grid(row=4, column=3) orange4 = Button(self, text="Orange", command=lambda: ringFour(3)) orange4.grid(row=5, column=3) yellow4 = Button(self, text="Yellow", command=lambda: ringFour(4)) yellow4.grid(row=6, column=3) green4 = Button(self, text="Green", command=lambda: ringFour(5)) green4.grid(row=7, column=3) blue4 = Button(self, text="Blue", command=lambda: ringFour(6)) blue4.grid(row=8, column=3) violet4 = Button(self, text="Violet", command=lambda: ringFour(7)) violet4.grid(row=9, column=3) grey4 = Button(self, text="Grey", command=lambda: ringFour(8)) grey4.grid(row=10, column=3) white4 = Button(self, text="White", command=lambda: ringFour(9)) white4.grid(row=11, column=3) i = 0 labels = "Ring 1", "Ring 2", "Ring 3", "Multiplier" for label in labels: label1 = Label(self, text=label) label1.grid(row=1, column=i) i += 1 clear = Button(self, text="Clear", command=lambda: cls()) clear.grid(row=12, columnspan=4, sticky=W + E) self.pack()
class Principal(Frame): # Class for helping Tooltips class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text, lang): self.text = text if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() + 27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass label = Label(tw, text=self.text[lang], justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() # Initialization function def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # Spiral parameters (defined as StringVars for convenience) self.a = StringVar() self.a.set('0') self.b = StringVar() self.b.set('0.5') self.c = StringVar() self.c.set('1') self.lMax = StringVar() self.lMax.set(158) self.frec = StringVar() self.frec.set(500) self.StringLongitud = StringVar() self.StringRadio = StringVar() # Help mode flag self.ayuda = False # Figure object self.f = Figure(figsize=(5, 5)) self.initUI() # Tooltip creator function (allowed by help mode flag) def createToolTip(self, widget, text): toolTip = self.ToolTip(widget) def enter(event): if self.ayuda: toolTip.showtip(text, self.lang) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) # Euclidean distance calculator function def distancia(self, r1, phi1, r2, phi2): return sqrt(r1**2 + r2**2 - 2 * r1 * r2 * cos(phi1 - phi2)) # Polar to Cartesian coordinates def pol2cart(self, rho, phi): x = rho * cos(phi) y = rho * sin(phi) return (x, y) # def grafico(self): # Set figure size self.f = Figure(figsize=(5, 5)) # Check whether negative parameters are present and show an error if float(self.c.get()) < 0 or float(self.b.get()) < 0: print self.lang tkMessageBox.showerror("Error", self.error.get()) return # Set figure axis ax = self.f.add_subplot(111, polar=True) # Initialize r and theta lists at the center point self.theta_disc = [0] self.r_disc = [0] self.theta_disc_n = [0] # Initialize length value and list l = 0 l_vec = [] # Loop limited by antenna length while l < int(self.lMax.get()): # Length of each antenna segment in cm, computed as 1/15 of the wave length lseg = 300 / float(self.frec.get()) * 100 / 15 if self.tipoCurva.get() == 1: # Archimedean spiral # New theta values are calculated according to the following: # In an Archimedean spiral # /r - a\ c # theta = |-------| # \ b / # In order to get an approximately equally spaced segments, new theta values are computed according to the next formula. This formula has been worked # out gradually, not basing on any well-known expression. # /0.5 * lseg - a\ c # |----------------| - lseg # \ b / # ------------------------------ + lseg # 10 * theta + 1 # n # theta = theta + --------------------------------------- # n + 1 n r + 1 # n self.theta_disc.append(self.theta_disc[-1] + \ (( ((0.5*lseg - float(self.a.get()))/float(self.b.get()))**(float(self.c.get())) - lseg) / (10*self.theta_disc[-1] + 1) + lseg) \ / (self.r_disc[-1] + 1)) # print str(lseg) # print str(self.r_disc[-1]) else: # print "Eh: " + str(self.theta_disc[-1]) # print "Ra: " + str(self.r_disc[-1]) # print "Ls: " + str(lseg) # print "Ot: " + str(log(0.5*lseg/float(self.a.get()))/float(self.b.get())) self.theta_disc.append(self.theta_disc[-1] + \ (( max(log(0.5*lseg/float(self.a.get()))/float(self.b.get()),float(self.a.get())) - lseg) * exp(-1*self.theta_disc[-1]) + lseg) \ / (self.r_disc[-1] + 1)) #print str(lseg) #print str(self.r_disc[-1]) if self.tipoCurva.get() == 1: self.r_disc.append( float(self.b.get()) * self.theta_disc[-1]**(1 / float(self.c.get())) + float(self.a.get())) elif self.tipoCurva.get() == 2: self.r_disc.append( float(self.a.get()) * exp(float(self.b.get()) * self.theta_disc[-1])) self.theta_disc_n.append(pi + self.theta_disc[-1]) l_vec.append( self.distancia(self.r_disc[-1], self.theta_disc[-1], self.r_disc[-2], self.theta_disc[-2])) l += l_vec[-1] if self.fuente.get() and str( self.checkFuente.cget('state')) == 'normal': self.theta_disc.remove(0) self.r_disc.remove(0) self.theta_disc_n.remove(0) ax.plot([self.theta_disc[0], self.theta_disc_n[0]], [self.r_disc[0], self.r_disc[0]], color='r') ax.plot([0], [0], color='m', marker='o', markersize=5) self.StringLongitud.set("%#.1f cm" % l) self.StringRadio.set("%#.1f cm" % max(self.r_disc)) ax.plot(self.theta_disc, self.r_disc, color='b', marker='.', markersize=4) if self.espejar.get(): ax.plot(self.theta_disc_n, self.r_disc, color='g', marker='.', markersize=4) ax.set_rmax(max(self.r_disc)) ax.grid(True) #with open('distancias.csv', 'wb') as f: # writer = csv.writer(f) # writer.writerows(izip(self.theta_disc, l_vec)) def regraficar(self): self.grafico() self.canvas.get_tk_widget().pack_forget() self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) #canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1, padx=10, pady=10) def cambiaFormula(self): curvas = [ '''R0lGODlhbAAWAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABsABYAAAT+8MlJq7046817ToYnjmRpXsqpriw3JGgrz2pDHHDFFHTvezjL4kcsWoKUBIHCQDQQxmhy4EhZDATGkoKcEHIPwjIBkJoljsZVEFIwuGDJUJJwhM7ngN0i4D0YcxJdDwVqEg0CeC0DHQhlOokSCJGCcVYSAYyHiiaaGwOXEwCGDwqRBQgOC28PBqEPCAgMDDANgH8MCnEzAQSxCFufHQ6xuSF6FACeFgwBG1AHCwYGaSgC19jZAssViHQOrMIbelsIQwoHCuoLDsFCGwUgDn67LXVgDvUX3BeOEw0OHgCAcmgeBgME4QUssoBSgQMe+Am5lOqBQQkKHq0gIHEGMS9yHU1lO6CN34FwDamBOZBQhYCWGERqyyaxjp8HLyNuoOYMDYI6//awcNDzh0oJ1HiEy9CRwsIHDSBanCBg6YkCT4kA8EPAToGiTDkIgGEAQM8XsAKtuGUkgRsoYqxiaDrBbS4wbmNx2iuBLt+/HNQCfhABADs=''', '''R0lGODlhQwASAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABDABIAAATn8MlJq70463ZSJQyhjWSpGUe1BM/imXCcNQvVDNLQyHz/KAOGgiXYPQAsn7IEKDwKg4SDgCA4DMtsBiVpCAqALk5LrhRqPwIt5yy7H4GaAWBIKJ7391uBULyoIhMNDDUMQi9uAVQIVRQJCAyMMAgPBwsGBg5GFAoCnp+gAmMXXhJSDBOEE3kkBQmZbYhkUogOLwEHWHCBJgUOehMLAhMFKTlBkG0wBKN6DpQSzBMOqD4C0BmdoaHNE1LK1xKwSg5Jepkv46gOyk+yGr7AE03RVwUsCrwF1SWq8g92Ij0gAGIClUjmSEQAADs=''', '''''' ] formula = PhotoImage(data=curvas[self.tipoCurva.get() - 1]) self.formulaLabel.configure(image=formula) self.formulaLabel.image = formula if self.tipoCurva.get() == 1: self.parC.config(state=NORMAL) self.labelC.config(state=NORMAL) else: self.parC.config(state=DISABLED) self.labelC.config(state=DISABLED) def activarFuente(self): if self.espejar.get(): self.checkFuente.config(state=NORMAL) else: self.checkFuente.config(state=DISABLED) def escribirFichero(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.nec' options['filetypes'] = [('NEC2 files', '.nec'), ('all files', '.*')] options['initialdir'] = '~/Documentos/Antenas/Espirales' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save NEC' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) r_final = list(reversed(self.r_disc)) + self.r_disc theta_final = list(reversed(self.theta_disc_n)) + self.theta_disc x_ant, y_ant = self.pol2cart(r_final[0], theta_final[0]) tipoCurvaExt = ['Archimedean', 'Logarithmic'] fich.write('CM Created with PySAD\n') fich.write('CM L = %#.1f\n' % float(self.lMax.get())) fich.write('CM ' + tipoCurvaExt[int(self.tipoCurva.get()) - 1] + ' spiral') fich.write('CM a = ' + self.a.get()) fich.write('CM b = ' + self.b.get()) if int(self.tipoCurva.get()) == 0: fich.write('CM c = ' + self.c.get()) fich.write('CE\n') print len(r_final) for i in range(len(r_final) - 1): x, y = self.pol2cart(r_final[i + 1], theta_final[i + 1]) linea = 'GW\t%#d\t%#d\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\n' % ( i + 1, 1, x_ant / 100, y_ant / 100, 0, x / 100, y / 100, 0, 0.001) fich.write(linea) x_ant, y_ant = x, y fich.write('GE\t0\nGN\t-1\nEK\n') fich.write('EX\t%#d\t%#d\t%#d\t%#d\t%#d\t%#d\n' % (0, len(r_final) / 2, 1, 0, 1, 0)) fich.write('FR\t0\t0\t0\t0\t299.8\t0\nEN') fich.close() def escribirPDF(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.pdf' options['filetypes'] = [('PDF files', '.pdf'), ('all files', '.*')] options['initialdir'] = '~' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save PDF' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) #self.f.axis('off') matplotlib.rcParams.update({'font.size': 1}) self.f.gca().axes.get_xaxis().set_visible(False) self.f.gca().axes.get_yaxis().set_visible(False) papeles_w = [21, 29.7, 42, 59.4, 84.1] papeles_h = [29.7, 42, 59.4, 84.1, 118.9] for i_pap in range(0, len(papeles_w) - 1): if 2 * max(self.r_disc) < papeles_w[i_pap]: break print i_pap self.f.set_size_inches(papeles_w[i_pap] / 2.54, papeles_h[i_pap] / 2.54) noMargen = dict(pad=72 * (papeles_w[i_pap] - 2 * max(self.r_disc)) / 2 / 2.54, h_pad=0, w_pad=0) self.f.set_tight_layout(noMargen) self.f.suptitle('test title') self.f.savefig(fich, format='pdf', dpi='90') fich.close() def mostrarAyuda(self): self.ayuda = not self.ayuda if self.ayuda: self.helpButton.state(["pressed"]) self.config(cursor="question_arrow") else: self.helpButton.state(["!pressed"]) self.config(cursor="") def initText(self): self.curTip = StringVar() self.ArcSpi = StringVar() self.LogSpi = StringVar() self.aaa = StringVar() self.bbb = StringVar() self.ccc = StringVar() self.Lma = StringVar() self.fre = StringVar() self.Mir = StringVar() self.Sou = StringVar() self.Gen = StringVar() self.lenlen = StringVar() self.radrad = StringVar() self.error = StringVar() def updateText(self, lang): self.lang = lang if lang == 0: self.espButton.state(["pressed"]) self.engButton.state(["!pressed"]) else: self.engButton.state(["pressed"]) self.espButton.state(["!pressed"]) self.stringText = { 'curTip': ["Tipo de curva", "Curve type"], 'ArcSpi': ["Espiral de Arquímedes", "Archimedean spiral "], 'LogSpi': ["Espiral logarítmica", "Logarithmic spiral"], 'aaa': ["a (cm)", "a (cm)"], 'bbb': ["b (cm/rad)", "b (cm/rad)"], 'ccc': ["c", "c"], 'Lma': ["Lmax (cm)", "Lmax (cm)"], 'fre': ["frec (MHz)", "freq (MHz)"], 'LmaToo': [ "Longitud máxima de cada brazo de la antena", "Maximum length of each antenna's branch" ], 'FreToo': [ "Frecuencia de diseño (aumentar para disminuir la longitud de los segmentos)", "Design frequency (increase for decreasing segment length)" ], 'Mir': ["Espejar", "Mirror"], 'MirToo': [ "Crea otra rama de la espiral girada 180º", "Create another spiral branch, twisted 180º" ], 'Sou': ["Colocar fuente", "Put source"], 'SouToo': [ "Une las dos mitades y crea una fuente NEC2 en el centro", "Join both halves and create a NEC2 source at the middle" ], 'Gen': ["Generar", "Generate"], 'GenToo': [ "Genera la espiral con los parámetros indicados", "Generate spiral following given parameters" ], 'NEC': ["NEC", "NEC"], 'NECToo': [ "Guarda la espiral como archivo NEC2", "Save the spiral as a NEC2 file" ], 'PDF': ["PDF", "PDF"], 'PDFToo': [ "Imprime la espiral a tamaño real en un documento PDF (máximo A0)", "Print the real sized spiral into a PDF document (A0 maximum)" ], 'HHH': ["H", "H"], 'lenlen': ["Longitud:", "Length:"], 'radrad': ["Radio:", "Radius:"], 'error': [ "No se permiten valores negativos de b o c", "Negative values of b or c are not allowed" ] } self.curTip.set(self.stringText['curTip'][self.lang]) self.ArcSpi.set(self.stringText['ArcSpi'][self.lang]) self.LogSpi.set(self.stringText['LogSpi'][self.lang]) self.aaa.set(self.stringText['aaa'][self.lang]) self.bbb.set(self.stringText['bbb'][self.lang]) self.ccc.set(self.stringText['ccc'][self.lang]) self.Lma.set(self.stringText['Lma'][self.lang]) self.fre.set(self.stringText['fre'][self.lang]) self.Mir.set(self.stringText['Mir'][self.lang]) self.Sou.set(self.stringText['Sou'][self.lang]) self.Gen.set(self.stringText['Gen'][self.lang]) self.lenlen.set(self.stringText['lenlen'][self.lang]) self.radrad.set(self.stringText['radrad'][self.lang]) self.error.set(self.stringText['error'][self.lang]) def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0, columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva, value=1, command=self.cambiaFormula, width=17).grid(row=1, columnspan=2, sticky=W, padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva, value=2, command=self.cambiaFormula).grid(row=2, columnspan=2, sticky=W, padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame, textvariable=self.aaa).grid(row=5, column=0, pady=2) Label(editarFrame, textvariable=self.bbb).grid(row=6, column=0, pady=2) self.labelC = Label(editarFrame, textvariable=self.ccc) self.labelC.grid(row=7, column=0, pady=2) self.labelC.config(state=DISABLED) Label(editarFrame, textvariable=self.Lma).grid(row=8, column=0, pady=2) Label(editarFrame, textvariable=self.fre).grid(row=9, column=0, pady=2) parA = Entry(editarFrame, width=4, textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame, width=4, textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame, width=4, textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame, width=4, textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame, width=4, textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage( data= '''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''' ) saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3, textvariable=self.lenlen).grid(row=1, column=0, pady=4, padx=12) Label(frame3, textvariable=self.radrad).grid(row=2, column=0, pady=4, padx=12) Label(frame3, textvariable=self.StringLongitud).grid(row=1, column=1, pady=4) Label(frame3, textvariable=self.StringRadio).grid(row=2, column=1, pady=4) def onExit(self): self.quit()
def initUI(self): self.parent.title("Resistor Calculator") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.columnconfigure(0, pad=3) self.columnconfigure(1, pad=3) self.columnconfigure(2, pad=3) self.columnconfigure(3, pad=3) self.columnconfigure(4, pad=3) self.columnconfigure(5, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.rowconfigure(4, pad=3) self.rowconfigure(5, pad=3) self.rowconfigure(6, pad=3) self.rowconfigure(7, pad=3) self.rowconfigure(8, pad=3) self.rowconfigure(9, pad=3) self.rowconfigure(10, pad=3) self.rowconfigure(11, pad=3) self.rowconfigure(12, pad=3) entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W+E) global resistance resistance="" def ringOne(number): entry.delete(0, END) entry.insert(0, str(number)) global resistance resistance = resistance + str(number) def ringTwo(number): ent=str(number) entry.insert(END, str(number)) global resistance resistance = resistance + str(number) def ringThree(number): ent=str(number) entry.insert(END, str(number)) global resistance resistance = resistance + str(number) def ringFour(number): global resistance entry.delete(0, END) for x in range (0, number): resistance = resistance + "0" ent = "Resistance is: " + resistance entry.insert(END,ent) resistance = "" def cls(): global resistance resistance = "" entry.delete(0, END) entry.insert(0,"Please Select ring colors") entry.insert(0,"Please Select ring colors") entry.config(justify=RIGHT) black = Button(self, text="Black", command=lambda: ringOne(0)) black.grid(row=2, column=0) brown = Button(self, text="Brown", command=lambda: ringOne(1)) brown.grid(row=3, column=0) red = Button(self, text = "Red", command=lambda: ringOne(2)) red.grid(row=4, column=0) orange = Button(self, text="Orange", command=lambda: ringOne(3)) orange.grid(row=5, column=0) yellow = Button(self, text="Yellow", command=lambda: ringOne(4)) yellow.grid(row=6, column=0) green = Button(self, text="Green", command=lambda: ringOne(5)) green.grid(row=7, column=0) blue = Button(self, text="Blue", command=lambda: ringOne(6)) blue.grid(row=8, column=0) violet = Button(self, text="Violet", command=lambda: ringOne(7)) violet.grid(row=9, column=0) grey = Button(self, text = "Grey", command=lambda: ringOne(8)) grey.grid(row=10, column = 0) white = Button(self, text="White", command=lambda: ringOne(9)) white.grid(row=11,column = 0) black2 = Button(self, text="Black", command=lambda: ringTwo(0)) black2.grid(row=2, column=1) brown2 = Button(self, text="Brown", command=lambda: ringTwo(1)) brown2.grid(row=3, column=1) red2 = Button(self, text = "Red", command=lambda: ringTwo(2)) red2.grid(row=4, column=1) orange2 = Button(self, text="Orange", command=lambda: ringTwo(3)) orange2.grid(row=5, column=1) yellow2 = Button(self, text="Yellow", command=lambda: ringTwo(4)) yellow2.grid(row=6, column=1) green2 = Button(self, text="Green", command=lambda: ringTwo(5)) green2.grid(row=7, column=1) blue2 = Button(self, text="Blue", command=lambda: ringTwo(6)) blue2.grid(row=8, column=1) violet2 = Button(self, text="Violet", command=lambda: ringTwo(7)) violet2.grid(row=9, column=1) grey2 = Button(self, text = "Grey", command=lambda: ringTwo(8)) grey2.grid(row=10, column = 1) white2 = Button(self, text="White", command=lambda: ringTwo(9)) white2.grid(row=11,column = 1) black3 = Button(self, text="Black", command=lambda: ringThree(0)) black3.grid(row=2, column=2) brown3 = Button(self, text="Brown", command=lambda: ringThree(1)) brown3.grid(row=3, column=2) red3 = Button(self, text = "Red", command=lambda: ringThree(2)) red3.grid(row=4, column=2) orange3 = Button(self, text="Orange", command=lambda: ringThree(3)) orange3.grid(row=5, column=2) yellow3 = Button(self, text="Yellow", command=lambda: ringThree(4)) yellow3.grid(row=6, column=2) green3 = Button(self, text="Green", command=lambda: ringThree(5)) green3.grid(row=7, column=2) blue3 = Button(self, text="Blue", command=lambda: ringThree(6)) blue3.grid(row=8, column=2) violet3 = Button(self, text="Violet", command=lambda: ringThree(7)) violet3.grid(row=9, column=2) grey3 = Button(self, text = "Grey", command=lambda: ringThree(8)) grey3.grid(row=10, column = 2) white3 = Button(self, text="White", command=lambda: ringThree(9)) white3.grid(row=11,column = 2) black4 = Button(self, text="Black", command=lambda: ringFour(0)) black4.grid(row=2, column=3) brown4 = Button(self, text="Brown", command=lambda: ringFour(1)) brown4.grid(row=3, column=3) red4 = Button(self, text = "Red", command=lambda: ringFour(2)) red4.grid(row=4, column=3) orange4 = Button(self, text="Orange", command=lambda: ringFour(3)) orange4.grid(row=5, column=3) yellow4 = Button(self, text="Yellow", command=lambda: ringFour(4)) yellow4.grid(row=6, column=3) green4 = Button(self, text="Green", command=lambda: ringFour(5)) green4.grid(row=7, column=3) blue4 = Button(self, text="Blue", command=lambda: ringFour(6)) blue4.grid(row=8, column=3) violet4 = Button(self, text="Violet", command=lambda: ringFour(7)) violet4.grid(row=9, column=3) grey4 = Button(self, text = "Grey", command=lambda: ringFour(8)) grey4.grid(row=10, column = 3) white4 = Button(self, text="White", command=lambda: ringFour(9)) white4.grid(row=11,column = 3) i=0 labels = "Ring 1", "Ring 2", "Ring 3", "Multiplier" for label in labels: label1 = Label(self, text=label) label1.grid(row=1, column = i) i+=1 clear = Button(self, text = "Clear", command = lambda: cls()) clear.grid(row=12, columnspan=4, sticky=W+E) self.pack()
class Login(object): def __init__(self): self.root = Tk() self.root.title(u'登录') self.root.resizable(False, False) self.root.geometry('+450+250') # self.sysfont = font(self.root, size=15) self.lb_user = Label(self.root, text=u'用户名:', width=20, height=10, font=("黑体", 15, "bold")) self.lb_passwd1 = Label(self.root, text=u'') self.lb_passwd = Label(self.root, text=u'密码:', width=20, height=5, font=("黑体", 15, "bold")) self.lb_user.grid(row=0, column=0, sticky=W) self.lb_passwd1.grid(row=1, column=0, sticky=W) self.lb_passwd.grid(row=2, column=0, sticky=W) self.en_user = Entry(self.root, width=24) self.en_passwd = Entry(self.root, width=24) self.en_user.grid(row=0, column=1, columnspan=1) self.en_passwd.grid(row=2, column=1, columnspan=1) self.en_user.insert(0, u'请输入用户名') self.en_passwd.insert(0, u'请输入密码') self.en_user.config( validate='focusin', validatecommand=lambda: self.validate_func('self.en_user'), invalidcommand=lambda: self.invalid_func('self.en_user')) self.en_passwd.config( validate='focusin', validatecommand=lambda: self.validate_func('self.en_passwd'), invalidcommand=lambda: self.invalid_func('self.en_passwd')) self.var = IntVar() self.ckb = Checkbutton(self.root, text=u'记住用户名和密码', underline=0, variable=self.var, font=(15)) self.ckb.grid(row=3, column=0) self.bt_print = Button(self.root, text=u'登陆') self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10) self.bt_print.config(command=self.print_info) self.bt_register = Button(self.root, text=u'注册') self.bt_register.grid(row=3, column=2, sticky=E, pady=50, padx=50) # self.bt_register.config(command=self.register_info) # self.root.bind('<Return>', self.enter_print) self.root.mainloop() def validate_func(self, en): return False if eval(en).get().strip() != '' else True def invalid_func(self, en): value = eval(en).get().strip() if value == u'输入用户名' or value == u'输入密码': eval(en).delete(0, END) if en == 'self.en_passwd': eval(en).config(show='*') def print_info(self): en1_value = self.en_user.get().strip() en2_value = self.en_passwd.get().strip() txt = u'''用户名: %s \n密码 : %s ''' % (self.en_user.get(), self.en_passwd.get()) if en1_value == '' or en1_value == u'输入用户名': print(u'无用户名', u'请输入用户名') elif en2_value == '' or en2_value == u'输入密码': print(u'无密码', u'请输入密码') else: a = 0 # 打开数据库连接 db = pymysql.connect("62.234.41.135", "root", "root", "book") # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 查询语句 sql = "select * from user" try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: id = row[0] name = row[1] pwd = row[2] if name == en1_value and pwd == en2_value: a = 1 print("数据库连接及验证成功!!!") print('登陆成功!!!', txt) # # 打印结果 # print "id=%d,name=%s,pwd=%s" % \ # (id, name, pwd) except: print("Error: unable b_while fecth data") # 关闭数据库连接 db.close() if (a == 0): print('用户名或密码错误!!!', txt) def register_info(self): self.rootR = Tk() loginPage(self.rootR) self.root.withdraw() def enter_print(self, event): self.print_info()
class CHEWD(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.selection = "" self.pdb = "" def initUI(self): self.parent.title("CHemical Energy Wise Decomposition") frame4 = Frame(self.parent) frame4.grid(row=0, column=0, sticky="nsew") self.wat = IntVar() self.wat.set(1) self.waterswap = Checkbutton(frame4, text="Water Swap", command=self.optionws, variable=self.wat) self.waterswap.grid(row=0, column=0) self.lig = IntVar() self.lig.set(0) self.ligandswap = Checkbutton(frame4, text="Ligand Swap", command=self.optionls, variable=self.lig) self.ligandswap.grid(row=0, column=1) self.mm = IntVar() self.mm.set(0) self.mmpbsa = Checkbutton(frame4, text="MMPBSA", command=self.optionmm, variable=self.mm) self.mmpbsa.grid(row=0, column=2) frame1 = Frame(self.parent) frame1.grid(row=1, column=0, sticky="nsew") lbl1 = Label(frame1, text="Log file folder", width=12) lbl1.grid(row=0, column=0) self.entry1 = Entry(frame1) self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E) self.browserButton = Button(frame1, text="Browser", command=self.onOpen) self.browserButton.grid(row=0, column=5, sticky="e") lbl2 = Label(frame1, text="MMPBSA log file", width=12) lbl2.grid(row=1, column=0) self.entry2 = Entry(frame1, state=DISABLED) self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E) self.browserButtonMM = Button(frame1, text="Browser", command=self.onOpenMM, state=DISABLED) self.browserButtonMM.grid(row=1, column=5, sticky="e") lbl3 = Label(frame1, text="MMPBSA PDB file", width=12) lbl3.grid(row=2, column=0) self.entry3 = Entry(frame1, state=DISABLED) self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E) self.browserButtonPDB = Button(frame1, text="Browser", command=self.onOpenPDB, state=DISABLED) self.browserButtonPDB.grid(row=2, column=5, sticky="e") lbl4 = Label(frame1, text="Ligand Name", width=12) lbl4.grid(row=3, column=0) self.entry4 = Entry(frame1) self.entry4.grid(row=3, column=1) self.lblswap = Label(frame1, text="Swap Ligand", width=12, state=DISABLED) self.lblswap.grid(row=3, column=2) self.swapentry = Entry(frame1, state=DISABLED) self.swapentry.grid(row=3, column=3) self.l1v = IntVar() self.l1v.set(1) self.lig1ck = Checkbutton(frame1, text="Ligand 1", command=self.changelig1, state=DISABLED, variable=self.l1v) self.lig1ck.grid(row=4, column=0) self.l2v = IntVar() self.l2v.set(0) self.lig2ck = Checkbutton(frame1, text="Ligand 2", command=self.changelig2, state=DISABLED, variable=self.l2v) self.lig2ck.grid(row=4, column=2) lbl5 = Label(frame1, text="Display Radius", width=12) lbl5.grid(row=5, column=0) self.entry5 = Entry(frame1) self.entry5.grid(row=5, column=1) self.entry5.insert(0, "5.0") self.sv = IntVar() self.sv.set(0) self.surface = Checkbutton(frame1, text="View Surface", command=self.viewsurface, variable=self.sv) self.surface.grid(row=5, column=2) self.vl = IntVar() self.vl.set(1) self.label = Checkbutton(frame1, text="View Label", command=self.viewlabel, variable=self.vl) self.label.grid(row=5, column=3) lbl6 = Label(frame1, text="Min Value", width=12) lbl6.grid(row=6, column=0) self.entry6 = Entry(frame1) self.entry6.grid(row=6, column=1) self.entry6.insert(0, "-5") lbl7 = Label(frame1, text="Max Value", width=12) lbl7.grid(row=6, column=2) self.entry7 = Entry(frame1) self.entry7.grid(row=6, column=3) self.entry7.insert(0, "+5") lbl8 = Label(frame1, text="Starting log file", width=12) lbl8.grid(row=7, column=0) self.entry8 = Entry(frame1) self.entry8.grid(row=7, column=1) self.entry8.insert(0, "400") lbl9 = Label(frame1, text="Ending log file", width=12) lbl9.grid(row=7, column=2) self.entry9 = Entry(frame1) self.entry9.grid(row=7, column=3) self.entry9.insert(0, "1000") frame2 = Frame(self.parent) frame2.grid(row=2, column=0, sticky="nsew") self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb) self.vsb.grid(row=1, column=3, sticky="ns") self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb1.grid(row=1, column=0) self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb2.grid(row=1, column=1) self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb3.grid(row=1, column=2) self.b1 = Button(frame2, text="Residue Number", state=DISABLED, command=lambda: self.sortdata(0)) self.b1.grid(row=0, column=0, sticky=W + E) self.b2 = Button(frame2, text="Residue Name", state=DISABLED, command=lambda: self.sortdata(1)) self.b2.grid(row=0, column=1, sticky=W + E) self.b3 = Button(frame2, text="Energy Value", state=DISABLED, command=lambda: self.sortdata(2)) self.b3.grid(row=0, column=2, sticky=W + E) OS = platform.system() if (OS == "Linux"): self.lb1.bind("<<ListboxSelect>>", self.OnSelect) self.lb1.bind("<4>", self.OnMouseWheel) self.lb1.bind("<5>", self.OnMouseWheel) self.lb2.bind("<<ListboxSelect>>", self.OnSelect) self.lb2.bind("<4>", self.OnMouseWheel) self.lb2.bind("<5>", self.OnMouseWheel) self.lb3.bind("<<ListboxSelect>>", self.OnSelect) self.lb3.bind("<4>", self.OnMouseWheel) self.lb3.bind("<5>", self.OnMouseWheel) else: self.lb1.bind("<<ListboxSelect>>", self.OnSelect) self.lb1.bind("<MouseWheel>", self.OnMouseWheel) self.lb2.bind("<<ListboxSelect>>", self.OnSelect) self.lb2.bind("<MouseWheel>", self.OnMouseWheel) self.lb3.bind("<<ListboxSelect>>", self.OnSelect) self.lb3.bind("<MouseWheel>", self.OnMouseWheel) frame3 = Frame(self.parent) frame3.grid(row=3, column=0, sticky="nsew") self.previous = Button(frame3, text="Previous Frame", state=DISABLED, command=self.prevframe) self.previous.grid(row=0, column=0, sticky=W + E) self.scale = Scale(frame3, command=self.onScale, state=DISABLED, orient=HORIZONTAL, length=320, showvalue=0) self.scale.grid(row=0, column=1, sticky=W + E) self.next = Button(frame3, text="Next Frame", state=DISABLED, command=self.nextframe) self.next.grid(row=0, column=2, sticky=W + E) self.var = IntVar() v = 000 self.var.set(v) self.label = Label(frame3, text=0, textvariable=self.var) self.label.grid(row=0, column=3) self.ApplyButton = Button(frame3, text="Apply", command=self.Apply) self.ApplyButton.grid(row=1, column=3, sticky="e") ToolTip(lbl1, "Load the result directory of Sire Analysis") ToolTip(self.browserButton, "Load the result directory of Sire Analysis") ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file") ToolTip( lbl5, "The radially distributed zone around ligand you want to be displayed" ) ToolTip( lbl6, "Minimum scale value for the color distribution and it will be treated as blue" ) ToolTip( lbl7, "Maximum scale value for the color distribution and it will be treated as red" ) def wsvisualizer(self, index, lig, zone, min, max, label): cmd.hide("all") x = cmd.get_names("all") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") #tt=0 stored.bfact = [] for line in fp: stored.bfact.append(line) #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt)) #tt=tt+1 #print(tt) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") self.togglelabelws(label, index, lig, zone) def lsvisualizer(self, index, lig, zone, min, max, hlig, label): cmd.hide("all") x = cmd.get_names("all") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") stored.bfact = [] for line in fp: stored.bfact.append(line) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") cmd.hide("licorice", x[index] + " and r. " + hlig) self.togglelabells(label, index, lig, zone, hlig) def wsupdateview(self, lig, zone, min, max, prev, index, label): cmd.hide("all") x = cmd.get_names("all") cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + prev + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") #tt=0 stored.bfact = [] for line in fp: stored.bfact.append(line) #print(stored.bfact[tt]+"\t"+line+"\t"+str(tt)) #tt=tt+1 #print(tt) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") self.togglelabelws(label, index, lig, zone) def lsupdateview(self, lig, zone, min, max, prev, index, hlig, label): cmd.hide("all") x = cmd.get_names("all") cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + prev + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"") cmd.show("cartoon", "bo. " + x[index]) cmd.show("sticks", x[index] + " and r. " + lig) cmd.color("white", x[index] + " and pol.") fp = open(tempfile.gettempdir() + "/temp.txt", "r") stored.bfact = [] for line in fp: stored.bfact.append(line) fp.close() cmd.alter(x[index], "b=stored.bfact.pop(0)") cmd.spectrum("b", "blue_white_red", x[index], minimum=min, maximum=max) cmd.ramp_new("ramp_obj", x[index], range=[min, 0, max], color="[blue, white, red ]") cmd.util.cbaw(x[index] + " and r. " + lig) cmd.show( "licorice", "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) ") cmd.hide("licorice", x[index] + " and r. " + hlig) self.togglelabells(label, index, lig, zone, hlig) def wsloadallpdb(self, pdblist, path): for x in pdblist: cmd.load(path + "/" + x) #print(path +"/"+ x) cmd.hide("all") def mmloadpdb(self, path): cmd.load(path) def togglesurface(self, sur): x = cmd.get_names("all") if (sur): cmd.show("surf", x[int(self.scale.get())]) cmd.set("transparency", "0.7") else: cmd.hide("surf", x[int(self.scale.get())]) def wslistdisplay(self, prev, cur, index): x = cmd.get_names("all") cmd.hide("sticks", x[index] + " and i. " + prev) cmd.label(x[index] + " and i. " + prev + " and name CA", "\" \"") cmd.show("sticks", x[index] + " and i. " + cur) cmd.label(x[index] + " and i. " + cur + " and name CA", "\"%s %s\"%(resn,resi)") def togglelabelws(self, label, index, lig, zone): global prevz x = cmd.get_names("all") if (label): cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\"%s %s\"%(resn,resi)") prevz = self.entry5.get() else: cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + prevz + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"") def togglelabells(self, label, index, lig, zone, hlig): global prevz x = cmd.get_names("all") if (label): cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + zone + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\"%s %s\"%(resn,resi)") cmd.label(x[index] + " and r. " + hlig + " and name CA", "\" \"") prevz = self.entry5.get() else: cmd.label( "( " + x[index] + " and (r. " + lig + " a. " + prevz + ") ) and (not (" + x[index] + " and (r. SWT or r. BWT or r. SWP))) " + " and name CA", "\" \"") def viewlabel(self): if (load > 0): if (self.wat.get() == 1): self.togglelabelws(self.vl.get(), int(self.scale.get()), self.entry4.get(), self.entry5.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.togglelabells(self.vl.get(), int(self.scale.get()), vl, self.entry5.get(), hl) elif (self.mm.get() == 1): self.togglelabelws(self.vl.get(), 0, self.entry4.get(), self.entry5.get()) def viewsurface(self): ## if (load > 0): self.togglesurface(self.sv.get()) def optionws(self): if (self.wat.get() == 1): self.lig.set(0) self.mm.set(0) self.entry1.config(state="normal") self.browserButton.config(state="normal") self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) else: self.wat.set(0) self.lig.set(1) self.mm.set(0) self.swapentry.config(state="normal") self.lig1ck.config(state="normal") self.lig2ck.config(state="normal") self.lblswap.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def optionls(self): if (self.lig.get() == 1): self.wat.set(0) self.mm.set(0) self.swapentry.config(state="normal") self.lig1ck.config(state="normal") self.lig2ck.config(state="normal") self.lblswap.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) else: self.lig.set(0) self.mm.set(0) self.wat.set(1) self.entry1.config(state="normal") self.browserButton.config(state="normal") self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def optionmm(self): if (self.mm.get() == 1): self.lig.set(0) self.wat.set(0) self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry8.config(state=DISABLED) self.entry9.config(state=DISABLED) self.entry1.config(state=DISABLED) self.browserButton.config(state=DISABLED) self.entry2.config(state="normal") self.entry3.config(state="normal") self.browserButtonMM.config(state="normal") self.browserButtonPDB.config(state="normal") else: self.wat.set(1) self.lig.set(0) self.mm.set(0) self.entry8.config(state="normal") self.entry9.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def changelig1(self): ## if (self.l1v.get() == 1): self.l2v.set(0) else: self.l2v.set(1) if (load > 0): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), hl, self.vl.get()) def changelig2(self): ## if (self.l2v.get() == 1): self.l1v.set(0) else: self.l1v.set(1) if (load > 0): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), hl, self.vl.get()) def loadmmpbsaresults(self): fp = open(self.entry3.get(), "r") e = 0 atomcount = 0 resnew = 0 rescount = 0 resnum = list() residuename = list() resv = list() atomnum = list() atomnums = list() score = list() r = "" rn = "" for line in fp: if e == 2: atomnum.append(atomnums) break t = line.split() if line.find('TER') != -1: e = e + 1 if line.find('ATOM') != -1: if (resnew == 0): r = t[4] rn = t[3] resnew = 1 resnum.append(r) residuename.append(rn) score.append(0) elif (r != t[4]): r = t[4] rn = t[3] atomnum.append(atomnums) resnum.append(r) residuename.append(rn) score.append(0) atomnums = list() atomnums.append(atomcount) atomcount = atomcount + 1 fp.close() ll = len(score) print(ll) resv = list() fp = open(self.entry2.get(), "r") for line in fp: t = line.split(',') t2 = t[0].split() if (len(t) == 20 and len(t2) == 2 and t2[0] != "LIG"): for xx in range(ll): if (int(resnum[xx]) == int(t2[1])): #print(str(ll)+"\t"+str(len(t))) score[xx] = float(t[17]) matchObj = re.match(r'Sidechain Energy Decomposition:', line, re.M | re.I) if matchObj: break fp.close() x = len(score) data = list() for i in range(x): data.append([resnum[i], score[i], residuename[i], atomnum[i]]) data.sort(key=lambda s: (int(s[0]))) scores = list() for i in range(len(data)): for j in range(len(data[i][3])): scores.append("{0:.3f}".format(data[i][1])) fp = open(tempfile.gettempdir() + "/temp.txt", "w") xs = len(scores) for i in range(xs): fp.write(str(scores[i]) + "\n") fp.close() self.lb1.delete(0, END) self.lb2.delete(0, END) self.lb3.delete(0, END) for i in range(x): self.lb1.insert(END, data[i][0]) self.lb2.insert(END, data[i][2]) self.lb3.insert(END, round(data[i][1], 3)) self.b1.config(state="normal") self.b2.config(state="normal") self.b3.config(state="normal") def changestate(self): ## fp = open(self.entry1.get() + "/bound_mobile_000100_0.00500.pdb") lend = 0 if (self.wat.get() == 1): lend = 2 elif (self.lig.get() == 1): lend = 4 e = 0 atomcount = 0 resnew = 0 rescount = 0 resnum = list() residuename = list() resv = list() atomnum = list() atomnums = list() score = list() r = "" rn = "" for line in fp: if e == lend: atomnum.append(atomnums) break t = line.split() if line.find('TER') != -1: e = e + 1 if line.find('ATOM') != -1: if (resnew == 0): r = t[4] rn = t[3] resnew = 1 resnum.append(r) residuename.append(rn) score.append(0) elif (r != t[4]): r = t[4] rn = t[3] atomnum.append(atomnums) resnum.append(r) residuename.append(rn) score.append(0) atomnums = list() atomnums.append(atomcount) atomcount = atomcount + 1 fp.close() x = list() tempx = list() ll = len(score) base = os.listdir(self.entry1.get()) for a in base: if a.endswith(".log"): tempx.append(a) tempx.sort() tlen = len(tempx) ia = int(self.entry8.get()) while (ia <= int(self.entry9.get()) and ia < tlen): x.append(tempx[ia]) ia += 1 c = 0 i = 0 for fn in x: fp = open(self.entry1.get() + "/" + fn, "r") if (c == 0): for line in fp: t = line.split() if (len(t) == 8): if (t[0] == "Residue("): for xx in range(ll): if (int(resnum[xx]) == int(t[3])): score[xx] = float(t[5]) if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"): c = c + 1 i = 0 break else: for line in fp: t = line.split() if (len(t) == 8): if (t[0] == "Residue("): for xx in range(ll): if (int(t[3]) == int(resnum[xx])): score[xx] = score[xx] + float(t[5]) i = i + 1 if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"): c = c + 1 i = 0 break fp.close() x = len(score) data = list() for i in range(x): data.append([resnum[i], score[i], residuename[i], atomnum[i]]) data.sort(key=lambda s: (int(s[0]))) for i in range(x): data[i][1] = data[i][1] / c scores = list() for i in range(len(data)): for j in range(len(data[i][3])): scores.append("{0:.3f}".format(data[i][1])) self.lb1.delete(0, END) self.lb2.delete(0, END) self.lb3.delete(0, END) for i in range(x): self.lb1.insert(END, data[i][0]) self.lb2.insert(END, data[i][2]) self.lb3.insert(END, round(data[i][1], 3)) fp = open(tempfile.gettempdir() + "/temp.txt", "w") lx = len(scores) for i in range(lx): fp.write(str(scores[i]) + "\n") fp.close() self.b1.config(state="normal") self.b2.config(state="normal") self.b3.config(state="normal") def prevframe(self): global prevz, load if (load > 0): self.scale.set(self.scale.get() - 1) def nextframe(self): global prevz, load if (load > 0): self.scale.set(self.scale.get() + 1) def onScale(self, val): global prevz, load if (load > 0): v = self.lig1pdb[int(float(val))][14:19] self.var.set(v) if (self.scale.get() == 0): self.previous.config(state=DISABLED) if (self.scale.get() == len(self.lig1pdb) - 2): self.next.config(state="normal") if (self.scale.get() == 1): self.previous.config(state="normal") if (self.scale.get() == len(self.lig1pdb) - 1): self.next.config(state=DISABLED) if (self.wat.get() == 1): self.wsupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), hl, self.vl.get()) def OnSelect(self, val): global prev sender = val.widget idx = sender.curselection() if (idx != ()): dis = self.lb1.get(idx) if (self.wat.get() == 1 or self.lig.get() == 1): self.wslistdisplay(prev, dis, int(self.scale.get())) elif (self.mm.get() == 1): self.wslistdisplay(prev, dis, 0) prev = dis def sortdata(self, sc): global dr1, dr2, dr3 tableData1 = self.lb1.get(0, END) tableData2 = self.lb2.get(0, END) tableData3 = self.lb3.get(0, END) data = list() nv = len(tableData1) for x in range(nv): data.append([tableData1[x], tableData2[x], tableData3[x]]) if (sc == 0): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b1.cget('text') if dr1 == 1: self.b1.config(text='[+] ' + lab) else: self.b1.config(text='[-] ' + lab) data.sort(key=lambda s: (int(s[sc])), reverse=dr1 == 1) dr1 = dr1 * -1 if (sc == 1): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b2.cget('text') if dr2 == 1: self.b2.config(text='[+] ' + lab) else: self.b2.config(text='[-] ' + lab) data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1) dr2 = dr2 * -1 if (sc == 2): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b3.cget('text') if dr3 == 1: self.b3.config(text='[+] ' + lab) else: self.b3.config(text='[-] ' + lab) data.sort(key=lambda s: (float(s[sc])), reverse=dr3 == 1) dr3 = dr3 * -1 nv = len(data) self.lb1.delete(0, 'end') self.lb2.delete(0, 'end') self.lb3.delete(0, 'end') for x in range(nv): self.lb1.insert(END, data[x][0]) self.lb2.insert(END, data[x][1]) self.lb3.insert(END, data[x][2]) def onOpen(self): global load fold = tkFileDialog.askdirectory() self.entry1.delete(0, 'end') self.entry1.insert(0, fold) load = 0 def onOpenMM(self): global load fold = tkFileDialog.askopenfilename() self.entry2.delete(0, 'end') self.entry2.insert(0, fold) load = 0 def onOpenPDB(self): global load fold = tkFileDialog.askopenfilename() self.entry3.delete(0, 'end') self.entry3.insert(0, fold) load = 0 def OnVsb(self, *args): self.lb1.yview(*args) self.lb2.yview(*args) self.lb3.yview(*args) def OnMouseWheel(self, event): self.lb1.yview("scroll", event.delta, "units") self.lb2.yview("scroll", event.delta, "units") self.lb3.yview("scroll", event.delta, "units") return "break" def Apply(self): global load, prevz if (load == 0): if (self.wat.get() == 1 or self.lig.get() == 1): self.changestate() self.base = os.listdir(self.entry1.get()) pdb1 = list() for a in self.base: matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a, re.M | re.I) if matchObj: pdb1.append(a) self.lig1pdb = list() self.lig2pdb = list() x = pdb1[1][22:27] for a in pdb1: matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb', a, re.M | re.I) if matchObj: self.lig1pdb.append(a) else: self.lig2pdb.append(a) self.lig1pdb.sort() self.lig2pdb.sort() self.scale.configure(from_=0, to=len(self.lig1pdb) - 1) self.scale.config(state="normal") elif (self.mm.get() == 1): self.loadmmpbsaresults() self.mmloadpdb(self.entry3.get()) self.wsvisualizer(0, self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), self.vl.get()) if (self.wat.get() == 1): self.wsloadallpdb(self.lig1pdb, self.entry1.get()) self.next.config(state="normal") v = self.lig1pdb[0][14:19] self.var.set(v) self.wsvisualizer(int(self.scale.get()), self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.wsloadallpdb(self.lig1pdb, self.entry1.get()) self.next.config(state="normal") v = self.lig1pdb[0][14:19] self.var.set(v) self.lsvisualizer(int(self.scale.get()), vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), hl, self.vl.get()) load = 1 else: #old code "else:" if (self.wat.get() == 1): self.wsupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() self.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, int(self.scale.get()), hl, self.vl.get()) elif (self.mm.get() == 1): self.wsupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, 0, self.vl.get()) prevz = self.entry5.get()
class CHEWDDialog(ModelessDialog): name = "Energy Visualizer" buttons = ("Apply", "Close") help = ("Energy.html", CHEWD) title = "CHemical Energy Wise Decomposition" def fillInUI(self, parent): #parent.resizable(0, 0) frame4 = Frame(parent) frame4.grid(row=0, column=0, sticky="nsew") self.wat = IntVar() self.wat.set(1) self.waterswap = Checkbutton(frame4, text="Water Swap", command=self.optionws, variable=self.wat) self.waterswap.grid(row=0, column=0) self.lig = IntVar() self.lig.set(0) self.ligandswap = Checkbutton(frame4, text="Ligand Swap", command=self.optionls, variable=self.lig) self.ligandswap.grid(row=0, column=1) self.mm = IntVar() self.mm.set(0) self.mmpbsa = Checkbutton(frame4, text="MMPBSA", command=self.optionmm, variable=self.mm) self.mmpbsa.grid(row=0, column=2) frame1 = Frame(parent) frame1.grid(row=1, column=0, sticky="nsew") lbl1 = Label(frame1, text="Log file folder", width=12) lbl1.grid(row=0, column=0) self.entry1 = Entry(frame1) self.entry1.grid(row=0, column=1, columnspan=4, sticky=W + E) self.browserButton = Button(frame1, text="Browser", command=self.onOpen) self.browserButton.grid(row=0, column=5, sticky="e") lbl2 = Label(frame1, text="MMPBSA log file", width=12) lbl2.grid(row=1, column=0) self.entry2 = Entry(frame1, state=DISABLED) self.entry2.grid(row=1, column=1, columnspan=4, sticky=W + E) self.browserButtonMM = Button(frame1, text="Browser", command=self.onOpenMM, state=DISABLED) self.browserButtonMM.grid(row=1, column=5, sticky="e") lbl3 = Label(frame1, text="MMPBSA PDB file", width=12) lbl3.grid(row=2, column=0) self.entry3 = Entry(frame1, state=DISABLED) self.entry3.grid(row=2, column=1, columnspan=4, sticky=W + E) self.browserButtonPDB = Button(frame1, text="Browser", command=self.onOpenPDB, state=DISABLED) self.browserButtonPDB.grid(row=2, column=5, sticky="e") lbl4 = Label(frame1, text="Ligand Name", width=12) lbl4.grid(row=3, column=0) self.entry4 = Entry(frame1) self.entry4.grid(row=3, column=1) self.lblswap = Label(frame1, text="Swap Ligand", width=12, state=DISABLED) self.lblswap.grid(row=3, column=2) self.swapentry = Entry(frame1, state=DISABLED) self.swapentry.grid(row=3, column=3) self.l1v = IntVar() self.l1v.set(1) self.lig1ck = Checkbutton(frame1, text="Ligand 1", command=self.changelig1, state=DISABLED, variable=self.l1v) self.lig1ck.grid(row=4, column=0) self.l2v = IntVar() self.l2v.set(0) self.lig2ck = Checkbutton(frame1, text="Ligand 2", command=self.changelig2, state=DISABLED, variable=self.l2v) self.lig2ck.grid(row=4, column=2) lbl5 = Label(frame1, text="Display Radius", width=12) lbl5.grid(row=5, column=0) self.entry5 = Entry(frame1) self.entry5.grid(row=5, column=1) self.entry5.insert(0, "5.0") self.sv = IntVar() self.sv.set(0) self.surface = Checkbutton(frame1, text="View Surface", command=self.viewsurface, variable=self.sv) self.surface.grid(row=5, column=2) self.vl = IntVar() self.vl.set(1) self.label = Checkbutton(frame1, text="View Label", command=self.viewlabel, variable=self.vl) self.label.grid(row=5, column=3) lbl6 = Label(frame1, text="Min Value", width=12) lbl6.grid(row=6, column=0) self.entry6 = Entry(frame1) self.entry6.grid(row=6, column=1) self.entry6.insert(0, "-5") lbl7 = Label(frame1, text="Max Value", width=12) lbl7.grid(row=6, column=2) self.entry7 = Entry(frame1) self.entry7.grid(row=6, column=3) self.entry7.insert(0, "+5") lbl8 = Label(frame1, text="Starting log file", width=12) lbl8.grid(row=7, column=0) self.entry8 = Entry(frame1) self.entry8.grid(row=7, column=1) self.entry8.insert(0, "400") lbl9 = Label(frame1, text="Ending log file", width=12) lbl9.grid(row=7, column=2) self.entry9 = Entry(frame1) self.entry9.grid(row=7, column=3) self.entry9.insert(0, "1000") frame2 = Frame(parent) frame2.grid(row=2, column=0, sticky="nsew") self.vsb = Scrollbar(frame2, orient="vertical", command=self.OnVsb) self.vsb.grid(row=1, column=3, sticky="ns") self.lb1 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb1.grid(row=1, column=0) self.lb2 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb2.grid(row=1, column=1) self.lb3 = Listbox(frame2, yscrollcommand=self.vsb.set) self.lb3.grid(row=1, column=2) self.b1 = Button(frame2, text="Residue Number", state=DISABLED, command=lambda: self.sortdata(0)) self.b1.grid(row=0, column=0, sticky=W + E) self.b2 = Button(frame2, text="Residue Name", state=DISABLED, command=lambda: self.sortdata(1)) self.b2.grid(row=0, column=1, sticky=W + E) self.b3 = Button(frame2, text="Energy Value", state=DISABLED, command=lambda: self.sortdata(2)) self.b3.grid(row=0, column=2, sticky=W + E) self.lb1.bind("<<ListboxSelect>>", self.OnSelect) self.lb1.bind("<MouseWheel>", self.OnMouseWheel) self.lb2.bind("<<ListboxSelect>>", self.OnSelect) self.lb2.bind("<MouseWheel>", self.OnMouseWheel) self.lb3.bind("<<ListboxSelect>>", self.OnSelect) self.lb3.bind("<MouseWheel>", self.OnMouseWheel) frame3 = Frame(parent) frame3.grid(row=3, column=0, sticky="nsew") self.previous = Button(frame3, text="Previous Frame", state=DISABLED, command=self.prevframe) self.previous.grid(row=0, column=0, sticky=W + E) self.scale = Scale(frame3, command=self.onScale, state=DISABLED, orient=HORIZONTAL, length=320, showvalue=0) self.scale.grid(row=0, column=1, sticky=W + E) self.next = Button(frame3, text="Next Frame", state=DISABLED, command=self.nextframe) self.next.grid(row=0, column=2, sticky=W + E) self.var = IntVar() v = 000 self.var.set(v) self.label = Label(frame3, text=0, textvariable=self.var) self.label.grid(row=0, column=3) ToolTip(lbl1, "Load the result directory of Sire Analysis") ToolTip(self.browserButton, "Load the result directory of Sire Analysis") ToolTip(lbl4, "Enter the name of the Ligand in your coordinate file") ToolTip( lbl5, "The radially distributed zone around ligand you want to be displayed" ) ToolTip( lbl6, "Minimum scale value for the color distribution and it will be treated as blue" ) ToolTip( lbl7, "Maximum scale value for the color distribution and it will be treated as red" ) def viewlabel(self): if (load > 0): if (self.wat.get() == 1): CHEWD.togglelabelws(self.vl.get(), str(self.scale.get()), self.entry4.get(), self.entry5.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.togglelabells(self.vl.get(), str(self.scale.get()), vl, self.entry5.get(), hl) elif (self.mm.get() == 1): CHEWD.togglelabelws(self.vl.get(), "0", self.entry4.get(), self.entry5.get()) def viewsurface(self): if (load > 0): CHEWD.togglesurface(self.sv.get()) def optionws(self): if (self.wat.get() == 1): self.lig.set(0) self.mm.set(0) self.entry1.config(state="normal") self.browserButton.config(state="normal") self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) else: self.wat.set(0) self.lig.set(1) self.mm.set(0) self.swapentry.config(state="normal") self.lig1ck.config(state="normal") self.lig2ck.config(state="normal") self.lblswap.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def optionls(self): if (self.lig.get() == 1): self.wat.set(0) self.mm.set(0) self.swapentry.config(state="normal") self.lig1ck.config(state="normal") self.lig2ck.config(state="normal") self.lblswap.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) else: self.lig.set(0) self.mm.set(0) self.wat.set(1) self.entry1.config(state="normal") self.browserButton.config(state="normal") self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def optionmm(self): if (self.mm.get() == 1): self.lig.set(0) self.wat.set(0) self.swapentry.config(state=DISABLED) self.lig1ck.config(state=DISABLED) self.lig2ck.config(state=DISABLED) self.lblswap.config(state=DISABLED) self.entry8.config(state=DISABLED) self.entry9.config(state=DISABLED) self.entry1.config(state=DISABLED) self.browserButton.config(state=DISABLED) self.entry2.config(state="normal") self.entry3.config(state="normal") self.browserButtonMM.config(state="normal") self.browserButtonPDB.config(state="normal") else: self.wat.set(1) self.lig.set(0) self.mm.set(0) self.entry8.config(state="normal") self.entry9.config(state="normal") self.entry1.config(state="normal") self.browserButton.config(state="normal") self.entry2.config(state=DISABLED) self.entry3.config(state=DISABLED) self.browserButtonMM.config(state=DISABLED) self.browserButtonPDB.config(state=DISABLED) def changelig1(self): if (self.l1v.get() == 1): self.l2v.set(0) else: self.l2v.set(1) if (load > 0): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), hl, self.vl.get()) def changelig2(self): if (self.l2v.get() == 1): self.l1v.set(0) else: self.l1v.set(1) if (load > 0): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), hl, self.vl.get()) def loadmmpbsaresults(self): fp = open(self.entry2.get(), "r") resv = list() for line in fp: t = line.split(',') t2 = t[0].split() if (len(t) == 20 and len(t2) == 2 and t2[0] != self.entry4.get()): resv.append([int(t2[1]), float(t[17]), t2[0]]) matchObj = re.match(r'Sidechain Energy Decomposition:', line, re.M | re.I) if matchObj: break self.lb1.delete(0, END) self.lb2.delete(0, END) self.lb3.delete(0, END) x = len(resv) for i in range(x): self.lb1.insert(END, resv[i][0]) self.lb2.insert(END, resv[i][2]) self.lb3.insert(END, resv[i][1]) fp = open(tempfile.gettempdir() + "/temp.txt", "w") fc = open(tempfile.gettempdir() + "/clear.txt", "w") fp.write("attribute: sireEnergy\n") fp.write("recipient: residues\n") fc.write("attribute: sireEnergy\n") fc.write("recipient: residues\n") for i in range(x): fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n") fc.write("\t:" + str(resv[i][0]) + "\t0.0\n") fp.close() fc.close() self.b1.config(state="normal") self.b2.config(state="normal") self.b3.config(state="normal") def changestate(self): x = list() tempx = list() if (self.wat.get() == 1): base = os.listdir(self.entry1.get()) else: base = os.listdir(self.entry1.get() + "/") for a in base: if a.endswith(".log"): tempx.append(a) tempx.sort() tlen = len(tempx) ia = int(self.entry8.get()) - 1 while (ia <= int(self.entry9.get()) and ia < tlen): x.append(tempx[ia]) ia += 1 resv = list() c = 0 i = 0 for fn in x: if (self.wat.get() == 1): fp = open(self.entry1.get() + "/" + fn, "r") else: fp = open(self.entry1.get() + "/" + fn, "r") if (c == 0): for line in fp: t = line.split() if (len(t) == 8): if (t[0] == "Residue("): resv.append([int(t[3]), float(t[5]), t[1]]) if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"): c = c + 1 i = 0 break else: for line in fp: t = line.split() if (len(t) == 8): if (t[0] == "Residue("): resv[i][1] = resv[i][1] + float(t[5]) i = i + 1 if (line == "PROTEIN BOX WATER FREE ENERGY COMPONENTS\n"): c = c + 1 i = 0 break fp.close() x = len(resv) self.lb1.delete(0, END) self.lb2.delete(0, END) self.lb3.delete(0, END) for i in range(x): resv[i][1] = resv[i][1] / c for i in range(x): self.lb1.insert(END, resv[i][0]) self.lb2.insert(END, resv[i][2]) self.lb3.insert(END, round(resv[i][1], 3)) fp = open(tempfile.gettempdir() + "/temp.txt", "w") fc = open(tempfile.gettempdir() + "/clear.txt", "w") fp.write("attribute: sireEnergy\n") fp.write("recipient: residues\n") fc.write("attribute: sireEnergy\n") fc.write("recipient: residues\n") for i in range(x): fp.write("\t:" + str(resv[i][0]) + "\t" + str(resv[i][1]) + "\n") fc.write("\t:" + str(resv[i][0]) + "\t0.0\n") fp.close() fc.close() self.b1.config(state="normal") self.b2.config(state="normal") self.b3.config(state="normal") def prevframe(self): global prevz, load if (load > 0): self.scale.set(self.scale.get() - 1) def nextframe(self): global prevz, load if (load > 0): self.scale.set(self.scale.get() + 1) def onScale(self, val): global prevz, load if (load > 0): v = self.lig1pdb[int(float(val))][14:19] self.var.set(v) if (self.scale.get() == 0): self.previous.config(state=DISABLED) if (self.scale.get() == len(self.lig1pdb) - 2): self.next.config(state="normal") if (self.scale.get() == 1): self.previous.config(state="normal") if (self.scale.get() == len(self.lig1pdb) - 1): self.next.config(state=DISABLED) if (self.wat.get() == 1): CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), hl, self.vl.get()) def OnSelect(self, val): global prev sender = val.widget idx = sender.curselection() dis = self.lb1.get(idx) if (self.wat.get() == 1): CHEWD.wslistdisplay(self.entry4.get(), self.entry5.get(), prev, dis, str(self.scale.get()), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.lslistdisplay(vl, self.entry5.get(), prev, dis, str(self.scale.get()), hl, self.vl.get()) elif (self.mm.get() == 1): CHEWD.mmlistdisplay(self.entry4.get(), self.entry5.get(), prev, dis, "0", self.vl.get()) prev = dis def sortdata(self, sc): global dr1, dr2, dr3 tableData1 = self.lb1.get(0, END) tableData2 = self.lb2.get(0, END) tableData3 = self.lb3.get(0, END) data = list() nv = len(tableData1) for x in range(nv): data.append([tableData1[x], tableData2[x], tableData3[x]]) if (sc == 0): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b1.cget('text') if dr1 == 1: self.b1.config(text='[+] ' + lab) else: self.b1.config(text='[-] ' + lab) data.sort(key=lambda s: (s[sc]), reverse=dr1 == 1) dr1 = dr1 * -1 if (sc == 1): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b2.cget('text') if dr2 == 1: self.b2.config(text='[+] ' + lab) else: self.b2.config(text='[-] ' + lab) data.sort(key=lambda s: (s[sc]), reverse=dr2 == 1) dr2 = dr2 * -1 if (sc == 2): lab = self.b1.cget('text') if lab[0] == '[': self.b1.config(text=lab[4:]) lab = self.b2.cget('text') if lab[0] == '[': self.b2.config(text=lab[4:]) lab = self.b3.cget('text') if lab[0] == '[': self.b3.config(text=lab[4:]) lab = self.b3.cget('text') if dr3 == 1: self.b3.config(text='[+] ' + lab) else: self.b3.config(text='[-] ' + lab) data.sort(key=lambda s: (s[sc]), reverse=dr3 == 1) dr3 = dr3 * -1 nv = len(data) self.lb1.delete(0, 'end') self.lb2.delete(0, 'end') self.lb3.delete(0, 'end') for x in range(nv): self.lb1.insert(END, data[x][0]) self.lb2.insert(END, data[x][1]) self.lb3.insert(END, data[x][2]) def onOpen(self): global load fold = tkFileDialog.askdirectory() self.entry1.delete(0, 'end') self.entry1.insert(0, fold) load = 0 def onOpenMM(self): global load fold = tkFileDialog.askopenfilename() self.entry2.delete(0, 'end') self.entry2.insert(0, fold) load = 0 def onOpenPDB(self): global load fold = tkFileDialog.askopenfilename() self.entry3.delete(0, 'end') self.entry3.insert(0, fold) load = 0 def OnVsb(self, *args): self.lb1.yview(*args) self.lb2.yview(*args) self.lb3.yview(*args) def OnMouseWheel(self, event): self.lb1.yview("scroll", event.delta, "units") self.lb2.yview("scroll", event.delta, "units") self.lb3.yview("scroll", event.delta, "units") return "break" def Apply(self): global load, prevz if (load == 0): if (self.wat.get() == 1 or self.lig.get() == 1): self.changestate() self.base = os.listdir(self.entry1.get()) pdb1 = list() for a in self.base: matchObj = re.match(r'bound_mobile_\d{6}_0\.\d{5}\.pdb', a, re.M | re.I) if matchObj: pdb1.append(a) self.lig1pdb = list() self.lig2pdb = list() #print x x = pdb1[1][22:27] for a in pdb1: matchObj = re.match(r'bound_mobile_\d{6}_0\.' + x + '.pdb', a, re.M | re.I) if matchObj: self.lig1pdb.append(a) else: self.lig2pdb.append(a) self.lig1pdb.sort() self.lig2pdb.sort() self.scale.configure(from_=0, to=len(self.lig1pdb) - 1) self.scale.config(state="normal") elif (self.mm.get() == 1): self.loadmmpbsaresults() CHEWD.mmloadpdb(self.entry3.get()) CHEWD.mmvisualizer("0", tempfile.gettempdir(), self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), self.vl.get()) if (self.wat.get() == 1): CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get()) self.next.config(state="normal") v = self.lig1pdb[0][14:19] self.var.set(v) CHEWD.wsvisualizer(str(self.scale.get()), tempfile.gettempdir(), self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), self.vl.get()) elif (self.lig.get() == 1): if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.wsloadallpdb(self.lig1pdb, self.entry1.get()) self.next.config(state="normal") v = self.lig1pdb[0][14:19] self.var.set(v) CHEWD.lsvisualizer(str(self.scale.get()), tempfile.gettempdir(), vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), hl, self.vl.get()) load = 1 else: if (self.wat.get() == 1): self.changestate() CHEWD.clear(tempfile.gettempdir()) CHEWD.loadresults(tempfile.gettempdir()) CHEWD.wsupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), self.vl.get()) elif (self.lig.get() == 1): self.changestate() if (self.l1v.get() == 1): vl = self.entry4.get() hl = self.swapentry.get() if (self.l2v.get() == 1): vl = self.swapentry.get() hl = self.entry4.get() CHEWD.clear(tempfile.gettempdir()) CHEWD.loadresults(tempfile.gettempdir()) CHEWD.lsupdateview(vl, self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, str(self.scale.get()), hl, self.vl.get()) elif (self.mm.get() == 1): CHEWD.mmupdateview(self.entry4.get(), self.entry5.get(), self.entry6.get(), self.entry7.get(), prevz, "0", self.vl.get()) prevz = self.entry5.get()
class toolUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Sequence modification parser") self.columnconfigure(0, pad=5) self.columnconfigure(1, pad=5, weight = 1) self.columnconfigure(2, pad=5) self.rowconfigure(0, pad=5, weight = 1) self.rowconfigure(1, pad=5, weight = 1) self.rowconfigure(2, pad=5, weight = 1) self.rowconfigure(3, pad=5, weight = 1) self.rowconfigure(4, pad=5, weight = 1) self.rowconfigure(5, pad=5, weight = 1) self.lInput = Label(self, text = "Input file") self.lInput.grid(row = 0, column = 0, sticky = W) self.lPRS = Label(self, text = "phospoRS Column Name") self.lPRS.grid(row = 1, column = 0, sticky = W) self.lScore = Label(self, text = "Min phosphoRS Score") self.lScore.grid(row = 2, column = 0, sticky = W) self.lDA = Label(self, text = "Check deamidation sites") self.lDA.grid(row = 3, column = 0, sticky = W) self.lLabFile = Label(self, text = "Label description file") self.lLabFile.grid(row = 4, column = 0, sticky = W) self.ifPathText = StringVar() self.prsScoreText = StringVar(value = '0') self.prsNameText = StringVar() self.doDAVar = IntVar() self.labFileText = StringVar(value = path.abspath('moddict.txt')) self.ifPath = Entry(self, textvariable = self.ifPathText) self.ifPath.grid(row = 0, column = 1, sticky = W+E) self.prsName = Entry(self, textvariable = self.prsNameText) self.prsName.grid(row = 1, column = 1, sticky = W+E) self.prsScore = Entry(self, textvariable = self.prsScoreText, state = DISABLED) self.prsScore.grid(row = 2, column = 1, sticky = W+E) self.doDABox = Checkbutton(self, variable = self.doDAVar) self.doDABox.grid(row = 3, column = 1, sticky = W) self.labFile = Entry(self, textvariable = self.labFileText) self.labFile.grid(row = 4, column = 1, sticky = W+E) self.foButton = Button(self, text = "Select file", command = self.selectFileOpen) self.foButton.grid(row = 0, column = 2, sticky = E+W, padx = 3) self.prsButton = Button(self, text = "Select column", state = DISABLED, command = self.selectColumn) self.prsButton.grid(row = 1, column = 2, sticky = E+W, padx = 3) self.labFileButton = Button(self, text = "Select file", command = self.selectLabFileOpen) self.labFileButton.grid(row = 4, column = 2, sticky = E+W, padx = 3) self.startButton = Button(self, text = "Start", command = self.start, padx = 3, pady = 3) self.startButton.grid(row = 5, column = 1, sticky = E+W) self.pack(fill = BOTH, expand = True, padx = 5, pady = 5) def selectFileOpen(self): #Open file dialog dlg = tkFileDialog.Open(self, filetypes = [('Excel spreadsheet', '*.xlsx')]) openName = dlg.show() if openName != "": self.ifPathText.set(openName) self.findPRS(openName)#find phosphRS column def selectLabFileOpen(self): #Open labels file dialog dlg = tkFileDialog.Open(self, filetypes = [('All files', '*.*')]) openName = dlg.show() if openName != "": self.labFileText.set(openName) def findPRS(self, openName): #find phosphoRS column worksheet = load_workbook(openName, use_iterators = True).get_active_sheet() #open excel sheet self.headers = [unicode(worksheet.cell(get_column_letter(columnNr) + '1').value).lower() for columnNr in range(1, worksheet.get_highest_column() + 1)] self.prsButton.config(state = "normal") if 'phosphors site probabilities' in self.headers: self.prsNameText.set('phosphoRS Site Probabilities') elif 'phosphors: phospho_sty site probabilities' in self.headers: self.prsNameText.set('PhosphoRS: Phospho_STY Site Probabilities') elif 'phosphors: phospho site probabilities' in self.headers: self.prsNameText.set('PhosphoRS: Phospho Site Probabilities') else: self.prsNameText.set('PhosphoRS column not found') return self.prsScore.config(state = 'normal') if self.prsScoreText.get() == '0': self.prsScoreText.set('95') def selectColumn(self): column = ListBoxChoice(self.parent, "Select column", "Select the column that has phosphoRS or ptmRS data", self.headers).returnValue() if not column is None: self.prsNameText.set(column) self.prsScore.config(state = 'normal') if self.prsScoreText.get() == '0': self.prsScoreText.set('95') def start(self): if self.prsScoreText.get() == '': self.prsScoreText.set("0") process(self.ifPathText.get(), float(self.prsScoreText.get()), bool(self.doDAVar.get()), 'PD', self.labFileText.get(), self.prsNameText.get())
class Principal(Frame): # Class for helping Tooltips class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text, lang): self.text = text if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() +27 self.tipwindow = tw = Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) try: # For Mac OS tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass label = Label(tw, text=self.text[lang], justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() # Initialization function def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # Spiral parameters (defined as StringVars for convenience) self.a = StringVar() self.a.set('0') self.b = StringVar() self.b.set('0.5') self.c = StringVar() self.c.set('1') self.lMax = StringVar() self.lMax.set(158) self.frec = StringVar() self.frec.set(500) self.StringLongitud = StringVar() self.StringRadio = StringVar() # Help mode flag self.ayuda = False # Figure object self.f = Figure(figsize=(5,5)) self.initUI() # Tooltip creator function (allowed by help mode flag) def createToolTip(self, widget, text): toolTip = self.ToolTip(widget) def enter(event): if self.ayuda: toolTip.showtip(text, self.lang) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave) # Euclidean distance calculator function def distancia( self, r1, phi1, r2, phi2 ): return sqrt(r1**2 + r2**2 - 2*r1*r2*cos(phi1-phi2)) # Polar to Cartesian coordinates def pol2cart(self, rho, phi): x = rho*cos(phi) y = rho*sin(phi) return(x, y) # def grafico(self): # Set figure size self.f = Figure(figsize=(5,5)) # Check whether negative parameters are present and show an error if float(self.c.get()) < 0 or float(self.b.get()) < 0: print self.lang tkMessageBox.showerror("Error", self.error.get()) return # Set figure axis ax = self.f.add_subplot(111, polar=True) # Initialize r and theta lists at the center point self.theta_disc = [0] self.r_disc = [0] self.theta_disc_n = [0] # Initialize length value and list l = 0 l_vec = [] # Loop limited by antenna length while l < int(self.lMax.get()): # Length of each antenna segment in cm, computed as 1/15 of the wave length lseg = 300/float(self.frec.get())*100/15 if self.tipoCurva.get() == 1: # Archimedean spiral # New theta values are calculated according to the following: # In an Archimedean spiral # /r - a\ c # theta = |-------| # \ b / # In order to get an approximately equally spaced segments, new theta values are computed according to the next formula. This formula has been worked # out gradually, not basing on any well-known expression. # /0.5 * lseg - a\ c # |----------------| - lseg # \ b / # ------------------------------ + lseg # 10 * theta + 1 # n # theta = theta + --------------------------------------- # n + 1 n r + 1 # n self.theta_disc.append(self.theta_disc[-1] + \ (( ((0.5*lseg - float(self.a.get()))/float(self.b.get()))**(float(self.c.get())) - lseg) / (10*self.theta_disc[-1] + 1) + lseg) \ / (self.r_disc[-1] + 1)) # print str(lseg) # print str(self.r_disc[-1]) else: # print "Eh: " + str(self.theta_disc[-1]) # print "Ra: " + str(self.r_disc[-1]) # print "Ls: " + str(lseg) # print "Ot: " + str(log(0.5*lseg/float(self.a.get()))/float(self.b.get())) self.theta_disc.append(self.theta_disc[-1] + \ (( max(log(0.5*lseg/float(self.a.get()))/float(self.b.get()),float(self.a.get())) - lseg) * exp(-1*self.theta_disc[-1]) + lseg) \ / (self.r_disc[-1] + 1)) #print str(lseg) #print str(self.r_disc[-1]) if self.tipoCurva.get() == 1: self.r_disc.append(float(self.b.get())*self.theta_disc[-1]**(1/float(self.c.get())) + float(self.a.get())) elif self.tipoCurva.get() == 2: self.r_disc.append(float(self.a.get())*exp(float(self.b.get())*self.theta_disc[-1])) self.theta_disc_n.append(pi + self.theta_disc[-1]) l_vec.append(self.distancia(self.r_disc[-1],self.theta_disc[-1],self.r_disc[-2],self.theta_disc[-2])) l += l_vec[-1] if self.fuente.get() and str(self.checkFuente.cget('state')) == 'normal': self.theta_disc.remove(0) self.r_disc.remove(0) self.theta_disc_n.remove(0) ax.plot([self.theta_disc[0],self.theta_disc_n[0]], [self.r_disc[0], self.r_disc[0]], color='r') ax.plot([0],[0], color='m', marker='o', markersize=5) self.StringLongitud.set("%#.1f cm" % l) self.StringRadio.set("%#.1f cm" % max(self.r_disc)) ax.plot(self.theta_disc, self.r_disc, color='b', marker='.', markersize=4) if self.espejar.get(): ax.plot(self.theta_disc_n, self.r_disc, color='g', marker='.', markersize=4) ax.set_rmax(max(self.r_disc)) ax.grid(True) #with open('distancias.csv', 'wb') as f: # writer = csv.writer(f) # writer.writerows(izip(self.theta_disc, l_vec)) def regraficar(self): self.grafico() self.canvas.get_tk_widget().pack_forget() self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) #canvas.show() self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH, expand=1, padx=10, pady=10) def cambiaFormula(self): curvas = ['''R0lGODlhbAAWAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABsABYAAAT+8MlJq7046817ToYnjmRpXsqpriw3JGgrz2pDHHDFFHTvezjL4kcsWoKUBIHCQDQQxmhy4EhZDATGkoKcEHIPwjIBkJoljsZVEFIwuGDJUJJwhM7ngN0i4D0YcxJdDwVqEg0CeC0DHQhlOokSCJGCcVYSAYyHiiaaGwOXEwCGDwqRBQgOC28PBqEPCAgMDDANgH8MCnEzAQSxCFufHQ6xuSF6FACeFgwBG1AHCwYGaSgC19jZAssViHQOrMIbelsIQwoHCuoLDsFCGwUgDn67LXVgDvUX3BeOEw0OHgCAcmgeBgME4QUssoBSgQMe+Am5lOqBQQkKHq0gIHEGMS9yHU1lO6CN34FwDamBOZBQhYCWGERqyyaxjp8HLyNuoOYMDYI6//awcNDzh0oJ1HiEy9CRwsIHDSBanCBg6YkCT4kA8EPAToGiTDkIgGEAQM8XsAKtuGUkgRsoYqxiaDrBbS4wbmNx2iuBLt+/HNQCfhABADs=''', '''R0lGODlhQwASAOMPAAwMDLa2thYWFiIiIlBQUJ6enubm5gQEBGJiYszMzEBAQDAwMHR0dIqKigAAAP///yH5BAEKAA8ALAAAAABDABIAAATn8MlJq70463ZSJQyhjWSpGUe1BM/imXCcNQvVDNLQyHz/KAOGgiXYPQAsn7IEKDwKg4SDgCA4DMtsBiVpCAqALk5LrhRqPwIt5yy7H4GaAWBIKJ7391uBULyoIhMNDDUMQi9uAVQIVRQJCAyMMAgPBwsGBg5GFAoCnp+gAmMXXhJSDBOEE3kkBQmZbYhkUogOLwEHWHCBJgUOehMLAhMFKTlBkG0wBKN6DpQSzBMOqD4C0BmdoaHNE1LK1xKwSg5Jepkv46gOyk+yGr7AE03RVwUsCrwF1SWq8g92Ij0gAGIClUjmSEQAADs=''', ''''''] formula = PhotoImage(data=curvas[self.tipoCurva.get()-1]) self.formulaLabel.configure(image=formula) self.formulaLabel.image = formula if self.tipoCurva.get() == 1: self.parC.config(state=NORMAL) self.labelC.config(state=NORMAL) else: self.parC.config(state=DISABLED) self.labelC.config(state=DISABLED) def activarFuente(self): if self.espejar.get(): self.checkFuente.config(state=NORMAL) else: self.checkFuente.config(state=DISABLED) def escribirFichero(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.nec' options['filetypes'] = [('NEC2 files', '.nec'),('all files', '.*')] options['initialdir'] = '~/Documentos/Antenas/Espirales' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save NEC' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) r_final = list(reversed(self.r_disc)) + self.r_disc theta_final = list(reversed(self.theta_disc_n)) + self.theta_disc x_ant, y_ant = self.pol2cart(r_final[0], theta_final[0]) tipoCurvaExt = ['Archimedean', 'Logarithmic'] fich.write('CM Created with PySAD\n') fich.write('CM L = %#.1f\n' % float(self.lMax.get())) fich.write('CM ' + tipoCurvaExt[int(self.tipoCurva.get())-1] + ' spiral') fich.write('CM a = ' + self.a.get()) fich.write('CM b = ' + self.b.get()) if int(self.tipoCurva.get()) == 0 : fich.write('CM c = ' + self.c.get()) fich.write('CE\n') print len(r_final) for i in range(len(r_final)-1): x, y = self.pol2cart(r_final[i+1], theta_final[i+1]) linea = 'GW\t%#d\t%#d\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\t%#.5f\n' % (i+1,1,x_ant/100,y_ant/100,0,x/100,y/100,0,0.001) fich.write(linea) x_ant, y_ant = x, y fich.write('GE\t0\nGN\t-1\nEK\n') fich.write('EX\t%#d\t%#d\t%#d\t%#d\t%#d\t%#d\n' % (0,len(r_final)/2,1,0,1,0)) fich.write('FR\t0\t0\t0\t0\t299.8\t0\nEN') fich.close() def escribirPDF(self): tipoCurva = ['Arq', 'Log'] c = [self.c.get() + ' ', ''] self.file_opt = options = {} options['defaultextension'] = '.pdf' options['filetypes'] = [('PDF files', '.pdf'),('all files', '.*')] options['initialdir'] = '~' options['initialfile'] = 'Spiral ' + tipoCurva[int(self.tipoCurva.get())-1] + ' ' + \ self.a.get() + ' ' + self.b.get() + ' ' + c[int(self.tipoCurva.get())-1] + self.lMax.get() + ' ' + self.frec.get() + '.nec' options['parent'] = self.parent options['title'] = 'Save PDF' fich = tkFileDialog.asksaveasfile(mode='w', **self.file_opt) #self.f.axis('off') matplotlib.rcParams.update({'font.size': 1}) self.f.gca().axes.get_xaxis().set_visible(False) self.f.gca().axes.get_yaxis().set_visible(False) papeles_w = [21, 29.7, 42, 59.4, 84.1] papeles_h = [29.7, 42, 59.4, 84.1, 118.9] for i_pap in range(0, len(papeles_w)-1): if 2*max(self.r_disc) < papeles_w[i_pap]: break print i_pap self.f.set_size_inches(papeles_w[i_pap]/2.54, papeles_h[i_pap]/2.54) noMargen = dict(pad=72*(papeles_w[i_pap] - 2*max(self.r_disc))/2/2.54, h_pad=0, w_pad=0) self.f.set_tight_layout(noMargen) self.f.suptitle('test title') self.f.savefig(fich, format='pdf', dpi='90') fich.close() def mostrarAyuda(self): self.ayuda = not self.ayuda if self.ayuda: self.helpButton.state(["pressed"]) self.config(cursor="question_arrow") else: self.helpButton.state(["!pressed"]) self.config(cursor="") def initText(self): self.curTip = StringVar() self.ArcSpi = StringVar() self.LogSpi = StringVar() self.aaa = StringVar() self.bbb = StringVar() self.ccc = StringVar() self.Lma = StringVar() self.fre = StringVar() self.Mir = StringVar() self.Sou = StringVar() self.Gen = StringVar() self.lenlen = StringVar() self.radrad = StringVar() self.error = StringVar() def updateText(self, lang): self.lang = lang if lang == 0: self.espButton.state(["pressed"]) self.engButton.state(["!pressed"]) else: self.engButton.state(["pressed"]) self.espButton.state(["!pressed"]) self.stringText = {'curTip': ["Tipo de curva", "Curve type"],'ArcSpi': ["Espiral de Arquímedes", "Archimedean spiral "],'LogSpi': ["Espiral logarítmica", "Logarithmic spiral"],'aaa': ["a (cm)", "a (cm)"],'bbb': ["b (cm/rad)", "b (cm/rad)"],'ccc': ["c", "c"],'Lma': ["Lmax (cm)", "Lmax (cm)"],'fre': ["frec (MHz)", "freq (MHz)"],'LmaToo': ["Longitud máxima de cada brazo de la antena", "Maximum length of each antenna's branch"],'FreToo': ["Frecuencia de diseño (aumentar para disminuir la longitud de los segmentos)", "Design frequency (increase for decreasing segment length)"],'Mir': ["Espejar", "Mirror"],'MirToo': ["Crea otra rama de la espiral girada 180º", "Create another spiral branch, twisted 180º"],'Sou': ["Colocar fuente", "Put source"],'SouToo': ["Une las dos mitades y crea una fuente NEC2 en el centro", "Join both halves and create a NEC2 source at the middle"],'Gen': ["Generar", "Generate"],'GenToo': ["Genera la espiral con los parámetros indicados", "Generate spiral following given parameters"],'NEC': ["NEC", "NEC"],'NECToo': ["Guarda la espiral como archivo NEC2", "Save the spiral as a NEC2 file"],'PDF': ["PDF", "PDF"],'PDFToo': ["Imprime la espiral a tamaño real en un documento PDF (máximo A0)", "Print the real sized spiral into a PDF document (A0 maximum)"],'HHH': ["H", "H"], 'lenlen': ["Longitud:", "Length:"], 'radrad': ["Radio:", "Radius:"], 'error': ["No se permiten valores negativos de b o c", "Negative values of b or c are not allowed"]} self.curTip.set(self.stringText['curTip'][self.lang]) self.ArcSpi.set(self.stringText['ArcSpi'][self.lang]) self.LogSpi.set(self.stringText['LogSpi'][self.lang]) self.aaa.set(self.stringText['aaa'][self.lang]) self.bbb.set(self.stringText['bbb'][self.lang]) self.ccc.set(self.stringText['ccc'][self.lang]) self.Lma.set(self.stringText['Lma'][self.lang]) self.fre.set(self.stringText['fre'][self.lang]) self.Mir.set(self.stringText['Mir'][self.lang]) self.Sou.set(self.stringText['Sou'][self.lang]) self.Gen.set(self.stringText['Gen'][self.lang]) self.lenlen.set(self.stringText['lenlen'][self.lang]) self.radrad.set(self.stringText['radrad'][self.lang]) self.error.set(self.stringText['error'][self.lang]) def initUI(self): self.initText() self.parent.title("PySAD") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) barraLateral = Frame(self, borderwidth=1) barraLateral.pack(side=RIGHT, padx=5, pady=5) idiomaFrame = Frame(barraLateral, relief=FLAT) idiomaFrame.pack(side=TOP) self.espButton = Button(idiomaFrame, text="es", width=0, command=lambda: self.updateText(0)) self.espButton.grid(row=0, column=0) self.engButton = Button(idiomaFrame, text="en", width=0, command=lambda: self.updateText(1)) self.engButton.grid(row=0, column=1) self.updateText(0) editarFrame = Frame(barraLateral, relief=RAISED, borderwidth=1, width=1000) editarFrame.pack(fill=BOTH, expand=1, side=TOP, padx=5, pady=5) self.tipoCurva = IntVar() tituloSelector = Label(editarFrame, textvariable=self.curTip) tituloSelector.grid(row=0,columnspan=2, padx=2, pady=4) Radiobutton(editarFrame, textvariable=self.ArcSpi, variable=self.tipoCurva , value=1, command=self.cambiaFormula, width=17).grid(row=1,columnspan=2,sticky=W,padx=4) Radiobutton(editarFrame, textvariable=self.LogSpi, variable=self.tipoCurva , value=2, command=self.cambiaFormula).grid(row=2,columnspan=2,sticky=W,padx=4) self.formulaLabel = Label(editarFrame) self.formulaLabel.grid(row=4, columnspan=2, pady=4) Label(editarFrame,textvariable=self.aaa).grid(row=5, column=0,pady=2) Label(editarFrame,textvariable=self.bbb).grid(row=6, column=0,pady=2) self.labelC = Label(editarFrame,textvariable=self.ccc) self.labelC.grid(row=7, column=0,pady=2) self.labelC.config(state=DISABLED) Label(editarFrame,textvariable=self.Lma).grid(row=8, column=0,pady=2) Label(editarFrame,textvariable=self.fre).grid(row=9, column=0,pady=2) parA = Entry(editarFrame,width=4,textvariable=self.a) parA.grid(row=5, column=1, sticky=W) parB = Entry(editarFrame,width=4,textvariable=self.b) parB.grid(row=6, column=1, sticky=W) self.parC = Entry(editarFrame,width=4,textvariable=self.c) self.parC.grid(row=7, column=1, sticky=W) self.parC.config(state=DISABLED) lMax = Entry(editarFrame,width=4,textvariable=self.lMax) lMax.grid(row=8, column=1, sticky=W) self.createToolTip(lMax, self.stringText['LmaToo']) frec = Entry(editarFrame,width=4,textvariable=self.frec) frec.grid(row=9, column=1, sticky=W) self.createToolTip(frec, self.stringText['FreToo']) self.espejar = IntVar() checkEspejar = Checkbutton(editarFrame, textvariable=self.Mir, variable=self.espejar, command=self.activarFuente) checkEspejar.grid(row=10, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(checkEspejar, self.stringText['MirToo']) self.fuente = IntVar() self.checkFuente = Checkbutton(editarFrame, textvariable=self.Sou, state=DISABLED, variable=self.fuente) self.checkFuente.grid(row=11, columnspan=2, pady=2, sticky=W, padx=4) self.createToolTip(self.checkFuente, self.stringText['SouToo']) okButton = Button(editarFrame, textvariable=self.Gen, command=self.regraficar) okButton.grid(row=12, columnspan=2, pady=5) self.createToolTip(okButton, self.stringText['GenToo']) self.frame2 = Frame(self, borderwidth=1) self.frame2.pack(fill=BOTH, expand=1, side=LEFT, padx=5, pady=5) self.canvas = FigureCanvasTkAgg(self.f, master=self.frame2) self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH, expand=1, padx=10, pady=10) frameGuardar = Frame(barraLateral, relief=FLAT, borderwidth=1) frameGuardar.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) icGuardar = PhotoImage(data='''R0lGODlhEAAQAIABADMzM////yH5BAEKAAEALAAAAAAQABAAAAIlDI55wchvQJQOxontUktTbkHcSJZkGCao161N5U5SLNM1vZlOAQA7''') saveButtonNEC = Button(frameGuardar, text=self.stringText['NEC'][0], image=icGuardar, compound=LEFT, command=self.escribirFichero, width=3) saveButtonNEC.image = icGuardar saveButtonNEC.grid(row=0, column=0, pady=2, padx=2, sticky=W) self.createToolTip(saveButtonNEC, self.stringText['NECToo']) saveButtonPDF = Button(frameGuardar, text=self.stringText['PDF'][0], image=icGuardar, compound=LEFT, command=self.escribirPDF, width=3) saveButtonPDF.image = icGuardar saveButtonPDF.grid(row=0, column=2, pady=2, padx=2, sticky=E) self.createToolTip(saveButtonPDF, self.stringText['PDFToo']) self.helpButton = Button(frameGuardar, text="?", command=self.mostrarAyuda, width=2) self.helpButton.grid(row=0, column=3, pady=2, padx=2, sticky=E) frame3 = Frame(barraLateral, relief=RAISED, borderwidth=1) frame3.pack(fill=BOTH, expand=1, side=BOTTOM, padx=5, pady=5) Label(frame3,textvariable=self.lenlen).grid(row=1, column=0,pady=4,padx=12) Label(frame3,textvariable=self.radrad).grid(row=2, column=0,pady=4,padx=12) Label(frame3,textvariable=self.StringLongitud).grid(row=1, column=1,pady=4) Label(frame3,textvariable=self.StringRadio).grid(row=2, column=1,pady=4) def onExit(self): self.quit()
class Login(object): def __init__(self): self.root = Tk() self.root.title(u'登录') self.root.resizable(False, False) self.root.geometry('+450+250') self.sysfont = Font(self.root, size=15) self.lb_user = Label(self.root, text=u'用户名:', width=20, height=10, font=("黑体", 15, "bold")) self.lb_passwd1 = Label(self.root, text=u'') self.lb_passwd = Label(self.root, text=u'密码:', width=20, height=5, font=("黑体", 15, "bold")) self.lb_user.grid(row=0, column=0, sticky=W) self.lb_passwd1.grid(row=1, column=0, sticky=W) self.lb_passwd.grid(row=2, column=0, sticky=W) self.en_user = Entry(self.root, font=self.sysfont, width=24) self.en_passwd = Entry(self.root, font=self.sysfont, width=24) self.en_user.grid(row=0, column=1, columnspan=1) self.en_passwd.grid(row=2, column=1, columnspan=1) self.en_user.insert(0, u'请输入用户名') self.en_passwd.insert(0, u'请输入密码') self.en_user.config( validate='focusin', validatecommand=lambda: self.validate_func('self.en_user'), invalidcommand=lambda: self.invalid_func('self.en_user')) self.en_passwd.config( validate='focusin', validatecommand=lambda: self.validate_func('self.en_passwd'), invalidcommand=lambda: self.invalid_func('self.en_passwd')) self.var = IntVar() self.ckb = Checkbutton(self.root, text=u'记住用户名和密码', underline=0, variable=self.var, font=(15)) self.ckb.grid(row=3, column=0) self.bt_print = Button(self.root, text=u'登陆') self.bt_print.grid(row=3, column=1, sticky=E, pady=50, padx=10) self.bt_print.config(command=self.print_info) self.bt_http = Button(self.root, text=u'http登录') self.bt_http.grid(row=3, column=2, sticky=E, pady=50, padx=50) self.bt_http.config(command=self.http_info) self.bt_register = Button(self.root, text=u'注册') self.bt_register.grid(row=3, column=3, sticky=E, pady=50, padx=50) self.bt_register.config(command=self.register_info) self.root.mainloop() def validate_func(self, en): return False if eval(en).get().strip() != '' else True def invalid_func(self, en): value = eval(en).get().strip() if value == u'输入用户名' or value == u'输入密码': eval(en).delete(0, END) if en == 'self.en_passwd': eval(en).config(show='*') def print_info(self): en1_value = self.en_user.get().strip() en2_value = self.en_passwd.get().strip() txt = u'''用户名: %s \n密码 : %s ''' % (self.en_user.get(), self.en_passwd.get()) if en1_value == '' or en1_value == u'输入用户名': showwarning(u'无用户名', u'请输入用户名') elif en2_value == '' or en2_value == u'输入密码': showwarning(u'无密码', u'请输入密码') else: a = 0 ip_port = ('127.0.0.1', 9999) regInfo = [en1_value, en2_value] tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpCliSock.connect(ip_port) datastr = json.dumps(regInfo) tcpCliSock.send(datastr.encode('utf-8')) data_sign = tcpCliSock.recv(1024) tcpCliSock.close() if data_sign == '0': a = 1 print "数据库连接及验证成功!!!".decode("utf-8").encode("gb2312") showinfo('登陆成功!!!', txt) self.Chat() # # 打印结果 else: print "Error: unable to fecth data" if (a == 0): showinfo('用户名或密码错误!!!', txt) def Chat(self): self.rootC = Toplevel() ChatClient(self.rootC) self.root.withdraw() def http_info(self): webbrowser.open("http://localhost:3000/login", new=0, autoraise=True) def register_info(self): self.rootR = Toplevel() loginPage(self.rootR) #self.root.withdraw() def enter_print(self, event): self.print_info()