class NFrame(Frame): """docstring for ClassName""" #Crea el Frame principal y coloca imagenes #parametros #@[in] master es la ventana padre donde se colocara el frame #@[in] inicial es un boolean que es True si es el primer frame creado #@[in] img es un boolean que indica si debe de pregargar texturas para un frame #si no le proporcionamos ningun dato a incial tendra por defecto True def __init__(self, master, inicial=True, img=False): Frame.__init__(self, master) self.master = master self.__list_label = [] self.__list_listbox = [] self.__list_scrollbar = [] self.__list_button = [] self.__texture = [] if inicial == True: self.init_window(master) if img == True: self.__loadIMG() #add imagenes dependiendo del tipo de sistema sobre el que opera el programa #Modifica las caracteristicas de la ventana principal def init_window(self, master): self.master.title("MOTVIAL") if sys.platform.startswith('win32'): self.master.iconbitmap("image\\cod.ico") elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): #self.master.iconbitmap("image/cod.ico") pass self.master.geometry("1114x608") self.master.configure(bg="#353535") self.master.resizable(1, 1) self.configure(height=300, width=10, background="#353535") self.pack(side=RIGHT, ipadx=0, ipady=0) #Precarga las texturas para despuer ser recortadas def __loadIMG(self): try: if sys.platform.startswith('win32'): ruta = "image\\texture.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/texture.png" self.__texture.append(Image.open(ruta)) except Exception as e: pass #Permite configurar un frame creado def ConfigureF(self, ax=600, ay=52, x=0, y=0, bg="#353535"): self.configure(height=ay, width=ax, background=bg) self.place(x=x, y=y) #Crea un Label def addLabel(self, textvar="NONE", ax=4, ay=10, x=0, y=0, bg="#353535", fontcolor="#FFFFFF"): label = Label(self, height=ay, width=ax, background=bg, text=textvar, fg=fontcolor) label.place(x=x, y=y) self.__list_label.append(label) return label #Crea un TextBox def addListBox(self, ax=600, ay=52, x=0, y=0, bg="#B4045F"): scrolly = Scrollbar(self, activebackground="#171212", bg="#171212", orient=VERTICAL, troughcolor="#171212") listbox = Listbox(self, height=ay, width=ax, background=bg, borderwidth=0, highlightcolor="#4d86a1", selectbackground="#4d86a1", activestyle=NONE, highlightbackground="#4a4a4a", yscrollcommand=scrolly.set) listbox.config(font=("", 10), fg="#FFFFFF") listbox.place(x=0, y=0) scrolly.place(x=651, y=0, height=387) self.__list_listbox.append(listbox) self.__list_scrollbar.append(scrolly) for x in self.__list_listbox: x.configure(yscrollcommand=scrolly.set) scrolly.configure(command=self.__yview) #metodo privado add scrollbar a los textbox def __yview(self, *args): for x in self.__list_listbox: x.yview(*args) def clickEventListbox(self, index): self.__list_listbox[index].configure(selectmode=SINGLE) self.__list_listbox[index].bind('<Double-1>', self.__openImage) def Error(self, error="Se produjo un error"): Ventana2 = Toplevel(self.master) Ventana2.configure(height=100, width=260, bg="#4a4a4a") Ventana2.title("Error") Error = Label(Ventana2, text=error, bg="#4a4a4a", fg="#FFFFFF") Error.place(x=40, y=15) Error.config(font=("", 12)) Salir = Button(Ventana2, width=10, text="Salir", command=Ventana2.destroy) Salir.place(x=85, y=55) def __openImage(self, event): try: index = self.__list_listbox[0].get( self.__list_listbox[0].curselection()) #print(index[3:16]) if str(index[3:16]) != "Serial Number": if sys.platform.startswith('win32'): root = "image\\" + str(index[3:9]) + ".jpg" elif sys.platform.startswith( 'linux') or sys.platform.startswith('darwin'): root = "image/" + str(index[3:9]) + ".jpg" #print(root) im = imread(root) imshow("image", im) except Exception as e: self.Error("Error al cargar la imagen") #add texto en pantalla def addText(self, x, text, n): self.__list_listbox[x].insert(END, text) if (n + 2) % 2 == 0: self.__list_listbox[x].itemconfigure(n, bg="#696969") def retTextBox(self, x): return self.__list_listbox[x] #add button def addButtonI(self, dim=(0, 0, 206, 109), x=0, y=0, command=0): try: crop = self.__texture[0].crop(dim) render = ImageTk.PhotoImage(crop) nbutton = Button(self, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1") nbutton.image = render nbutton.place(x=x, y=y) self.__list_button.append(nbutton) if command == 1: nbutton.configure(command=self.showOne) elif command == 2: nbutton.configure(command=self.showAll) elif command == 3: pass elif command == 4: nbutton.configure(command=self.master.destroy) return nbutton except Exception as e: self.Error("Error al cargar Texturas") return -1 def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def yview(self, *args): self.listbox1.yview(*args) def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def Switch(self, root, Ventana2): root.deiconify() Ventana2.destroy() def load50(self, Poss, mode="a"): maxi = self.buscMax() I = Poss[0] F = Poss[1] if mode == "+": Poss[1] = Poss[1] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) Poss[0] = Poss[1] - 50 if Poss[0] < 0: Poss[0] = 0 elif mode == "-" and Poss[0] != 0: Poss[0] = Poss[0] - 50 if Poss[0] < 0: Poss[0] = 0 Poss[1] = Poss[0] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) if mode == "a" or Poss[0] != I or Poss[1] != F: asca = ManagementJson("Helloword.json") lista = asca.intervaloIF(Poss[0], Poss[1]) #cargando texto self.listbox1.delete(0, self.listbox1.size()) for x in range(0, len(lista["serial"])): if lista["status"][x] == "Riesgo Medio": self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) else: self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) def buscMax(self): f = open("config.txt", "r") f.seek(7) maxi = f.readline() f.close() return maxi def load1(self, listbox3, label1, label2, label3): asca = ManagementJson("Helloword.json") lista = asca.searchError(listbox3.get()) try: if lista == 0: label1.configure(text="No se encontro") label2.configure(text="No se encontro") label3.configure(text="No se encontro") return 0 except Exception as e: raise e label1.configure(text=lista[0]) label2.configure(text=lista[1]) label3.configure(text=lista[2])
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + '\n' in self.filenames: index = self.filenames.index(filename + '\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + '\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=( module, self.reporter, self, )) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END) self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: # Obtaining message type (pylint's '--include-ids' appends the # ID to this letter, so 1 character long is not guaranteed) msg_type = msg[0][0] if (self.msg_type_dict.get(msg_type)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) # Obtaining message type (pylint's '--include-ids' appends the # ID to this letter, so 1 character long is not guaranteed) msg_type = msg[0][0] #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg_type)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename+'\n' in self.filenames: index = self.filenames.index(filename+'\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename+'\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME+HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self,)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME+HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] filename = msg[2] fileline = int(msg[5]) scroll = fileline - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(filename, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(fileline - 1)
class DualBox(Frame): """The DualBox class is a pair of Listboxes that has a list of carts.""" _prev_index = None _select_callback = None _list_box1 = None _list_box2 = None def __init__(self, parent): """Construct a DualBox. :param parent """ Frame.__init__(self) self._select_callback = parent.select_cart # make scroll bar scroll_bar = Scrollbar(self, orient=Tkinter.VERTICAL, command=self._scroll_bar) label1 = Label(self, text=TEXT_LABEL1) label2 = Label(self, text=TEXT_LABEL2) # make two scroll boxes self._list_box1 = Listbox(self, yscrollcommand=scroll_bar.set, exportselection=0, width=40) self._list_box2 = Listbox(self, yscrollcommand=scroll_bar.set, exportselection=0, width=40) # fill the whole screen - pack! scroll_bar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) label1.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True) self._list_box1.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=5, pady=5) self._list_box2.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=5, pady=5) label2.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True) # mouse wheel binding self._list_box1.bind("<MouseWheel>", self._scroll_wheel) self._list_box2.bind("<MouseWheel>", self._scroll_wheel) # onclick binding? self._list_box1.bind("<<ListboxSelect>>", self.select) self._list_box2.bind("<<ListboxSelect>>", self.select) def fill(self, carts): """Fill the DualBox with a list of carts. :param carts: array of carts """ self._list_box1.delete(0, Tkinter.END) self._list_box2.delete(0, Tkinter.END) for cart in carts: self._list_box1.insert(Tkinter.END, cart.title) self._list_box2.insert(Tkinter.END, cart.issuer) def _get_selected_index(self): one = self._list_box1.curselection() two = self._list_box2.curselection() if len(one) is 0: one = None else: one = one[0] if len(two) is 0: two = None else: two = two[0] if one is not None and two is not None: if one == self._prev_index: self._prev_index = two elif two == self._prev_index: self._prev_index = one elif one is not None: self._prev_index = one elif two is not None: self._prev_index = two return self._prev_index def select(self, *args): """Select an item in the DualBox. :param args """ index = self._get_selected_index() if index is not None: self._list_box1.selection_clear(0, Tkinter.END) self._list_box2.selection_clear(0, Tkinter.END) self._list_box1.selection_set(index, index) self._list_box2.selection_set(index, index) self._select_callback(index) def _scroll_bar(self, *args): """Scroll the list boxes with the vertical scroll bar. :param args """ self._list_box1.yview(*args) self._list_box2.yview(*args) def _scroll_wheel(self, event): """Scroll the list boxes with the mouse wheel. :param event """ self._list_box1.yview("scroll", event.delta, "units") self._list_box2.yview("scroll", event.delta, "units") # this prevents default bindings from firing, which # would end up scrolling the widget twice return "break"
class Automation(Frame): """The Automation class is a GUI that provides radio automation.""" _state = None _button_text = None _button = None _meter = None _cart_queue = None _list_time = None _list_track = None _list_artist = None def __init__(self): """Construct an Automation window.""" Frame.__init__(self) # initialize title title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE) title.grid(row=0, column=0, columnspan=3) # initialize button and state self._state = STATE_STOPPED self._button_text = StringVar() self._button = Button(self.master, textvariable=self._button_text, command=self._update_state, width=16, height=2) self._button.config(bd=2) self._button.grid(row=0, column=3) # initialize the meter self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data) self._meter.grid(row=1, column=0, columnspan=4) # initialize playlist view playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN) Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=16, text=TEXT_PLAYLIST_TIME).grid(row=0, column=0) Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1) Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2) inner_playlist = Frame(playlist) scroll = Scrollbar(inner_playlist, orient=Tkinter.VERTICAL, command=self._scroll_playlist) self._list_time = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=16, height=20) self._list_track = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20) self._list_artist = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20) scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) self._list_time.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2) self._list_track.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2) self._list_artist.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2) inner_playlist.grid(row=1, column=0, columnspan=3) playlist.grid(row=4, column=0, columnspan=4) # initialize cart queue self._cart_queue = CartQueue(self._cart_start, self._cart_stop) self._cart_queue.add_tracks() self._update_ui() # begin the event loop self.master.protocol("WM_DELETE_WINDOW", self.master.destroy) self.master.title(TEXT_TITLE) self.master.mainloop() def _scroll_playlist(self, *args): """Scroll the playlist view. :param args """ self._list_time.yview(*args) self._list_track.yview(*args) self._list_artist.yview(*args) def _update_state(self): """Move Automation to the next state. The state machine is as follows: STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED """ if self._state is STATE_STOPPED: print "Starting Automation..." self._cart_queue.start() self._state = STATE_PLAYING elif self._state is STATE_PLAYING: print "Stopping Automation after this track..." self._cart_queue.stop_soft() self._state = STATE_STOPPING elif self._state is STATE_STOPPING: print "Stopping Automation immediately." self._cart_queue.transition() self._state = STATE_STOPPED self._update_ui() def _cart_start(self): """Start the meter when a cart starts.""" self._meter.start() self._update_ui() def _cart_stop(self): """Reset the meter when a cart stops. Also, if a soft stop occured, update the button state. """ self._meter.reset() if self._state is STATE_STOPPING: self._state = STATE_STOPPED self._update_ui() def _update_ui(self): """Update the button and playlist.""" self._button_text.set(TEXT_BUTTON[self._state]) self._button.config(bg=COLOR_BUTTON[self._state], highlightbackground=COLOR_BUTTON[self._state]) self._list_time.delete(0, Tkinter.END) self._list_track.delete(0, Tkinter.END) self._list_artist.delete(0, Tkinter.END) for cart in self._cart_queue.get_queue(): self._list_time.insert(Tkinter.END, cart.start_time.strftime("%I:%M:%S %p")) self._list_track.insert(Tkinter.END, cart.title) self._list_artist.insert(Tkinter.END, cart.issuer) def _get_meter_data(self): """Get meter data for the first track in the queue.""" queue = self._cart_queue.get_queue() if len(queue) > 0: return queue[0].get_meter_data() else: return None
class GetKeysDialog(Toplevel): def __init__(self,parent,title,action,currentKeySequences,_htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE,width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action=action self.currentKeySequences=currentKeySequences self.result='' self.keyString=StringVar(self) self.keyString.set('') self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self,borderwidth=2,relief=SUNKEN) frameMain.pack(side=TOP,expand=TRUE,fill=BOTH) frameButtons=Frame(self) frameButtons.pack(side=BOTTOM,fill=X) self.buttonOK = Button(frameButtons,text='OK', width=8,command=self.OK) self.buttonOK.grid(row=0,column=0,padx=5,pady=5) self.buttonCancel = Button(frameButtons,text='Cancel', width=8,command=self.Cancel) self.buttonCancel.grid(row=0,column=1,padx=5,pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain,command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '"+self.action+"' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT, textvariable=self.keyString,relief=GROOVE,borderwidth=2) labelKeysBasic.pack(ipadx=5,ipady=5,fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check=Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label,variable=variable,onvalue=modifier,offvalue='') check.grid(row=0,column=column,padx=2,sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W) self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected) self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS) scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS) self.buttonClear=Button(self.frameControlsBasic, text='Clear Keys',command=self.ClearKeySeq) self.buttonClear.grid(row=2,column=0,columnspan=4) labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT, text="Enter new binding(s) for '"+self.action+"' :\n"+ "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n"+ "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n"+ "separated by a space, eg., <Alt-v> <Meta-v>." ) labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8]=='Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self,event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList,'-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0,END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9', 'F10','F11','F12') self.alphanumKeys=tuple(string.ascii_lowercase+string.digits) self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys=('Tab','Space','Return') self.editKeys=('BackSpace','Delete','Insert') self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow', 'Right Arrow','Up Arrow','Down Arrow') #make a tuple of most of the useful common 'final' keys keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+ self.whitespaceKeys+self.editKeys+self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = {'Space':'space', '~':'asciitilde','!':'exclam','@':'at','#':'numbersign', '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk', '(':'parenleft',')':'parenright','_':'underscore','-':'minus', '+':'plus','=':'equal','{':'braceleft','}':'braceright', '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon', ':':'colon',',':'comma','.':'period','<':'less','>':'greater', '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next', 'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up', 'Down Arrow': 'Down', 'Tab':'Tab'} if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result=self.keyString.get() self.destroy() def Cancel(self, event=None): self.result='' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
class ConditionalsEditor: def __init__(self, my_window, conditionals, close_callback): #Tk.__init__(self) self.my_window = my_window self.my_window.title("Condition Editor") self.close_callback = close_callback self.conditionals = conditionals shared_pad_x = 3 shared_pad_y = 3 main_frame = Frame(self.my_window) main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) image_path = "images" image_files = [ f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png") ] self.icons = {} for image_file in image_files: self.icons[os.path.splitext( os.path.basename(image_file))[0]] = PhotoImage( file=os.path.join(image_path, image_file)) up_down_button_frame = Frame(main_frame) self.up_button = Button(up_down_button_frame, state="disabled", text="Move up", image=self.icons["gtk-go-up"], command=self.up_pressed) self.up_button.grid(column=0, row=0, sticky=(E)) self.down_button = Button(up_down_button_frame, state="disabled", text="Move down", image=self.icons["gtk-go-down"], command=self.down_pressed) self.down_button.grid(column=0, row=1, sticky=(E)) up_down_button_frame.grid(column=0, row=0, sticky=(E)) condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1) condition_list.grid(column=1, row=0, sticky=(N, S, E, W), padx=shared_pad_x, pady=shared_pad_y, columnspan=1) self.condition_list_scrollbar = Scrollbar(condition_list) self.state_listbox = Listbox(condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.state_listbox_scroll, activestyle="none") self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S)) self.state_listbox.bind("<<ListboxSelect>>", self.state_listbox_selected) self.condition_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.condition_listbox_scroll, activestyle="none") self.condition_listbox.grid(column=1, row=0, sticky=(N, S, E, W), padx=0) self.condition_listbox.bind("<<ListboxSelect>>", self.condition_listbox_selected) self.execution_target_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.execution_target_listbox_scroll, activestyle="none") self.execution_target_listbox.grid(column=2, row=0, padx=0, sticky=(N, S)) self.execution_target_listbox.bind( "<<ListboxSelect>>", self.execution_target_listbox_selected) self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S)) self.condition_list_scrollbar.config( command=self.condition_list_scrollbar_callback) condition_list.grid_rowconfigure(0, weight=1) for conditional in self.conditionals: self.state_listbox.insert(END, conditional[0]) self.condition_listbox.insert(END, conditional[1]) self.execution_target_listbox.insert(END, conditional[2]) #for i in range(5): # self.state_listbox.insert(END, "Foo %d"%i) # self.condition_listbox.insert(END, "Bar %d"%i) # self.execution_target_listbox.insert(END, "Baz %d"%i) if_label = Label(main_frame, text="If:", padx=10) if_label.grid(column=0, row=1, sticky=(N, E)) self.if_text_variable = StringVar() if_entry = Entry(main_frame, textvariable=self.if_text_variable) if_entry.grid( column=1, row=1, sticky=(E, W), padx=shared_pad_x, pady=shared_pad_y, ) then_label = Label(main_frame, text="Then:", padx=10) then_label.grid(column=0, row=2, sticky=(N, E)) self.then_entry = Text(main_frame) self.then_entry.grid( column=1, row=2, sticky=(N, S, E, W), padx=shared_pad_x, rowspan=2, ) option_frame = Frame(main_frame) execution_target_label = Label(option_frame, text="Execution target:") execution_target_label.grid(column=0, row=0, sticky=(N, W), pady=(10, shared_pad_y)) self.execution_target = StringVar() self.execution_target.set("Debugger") debugger_radiobutton = Radiobutton(option_frame, text="Debugger", variable=self.execution_target, value="Debugger") debugger_radiobutton.grid(column=0, row=1, sticky=(N, W)) python_radiobutton = Radiobutton(option_frame, text="Python", variable=self.execution_target, value="Python") python_radiobutton.grid(column=0, row=2, sticky=(N, W)) state_label = Label(option_frame, text="State") state_label.grid(column=0, row=3, sticky=(N, W), pady=(10, shared_pad_y)) self.active_checkbutton = StringVar() self.active_checkbutton.set("Enabled") active_checkbutton = Checkbutton(option_frame, text="Enabled", variable=self.active_checkbutton, onvalue="Enabled", offvalue="Disabled") active_checkbutton.grid(column=0, row=4, sticky=(N, W)) option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5) button_frame = Frame(main_frame) self.add_button = Button(button_frame, state="disabled", text="Add", image=self.icons["gtk-add"], compound=LEFT) self.add_button.grid(column=0, row=0, sticky=(E)) self.update_button = Button(button_frame, state="disabled", text="Update", image=self.icons["gtk-edit"], compound=LEFT) self.update_button.grid(column=1, row=0, sticky=(E)) self.delete_button = Button(button_frame, state="disabled", text="Delete", image=self.icons["gtk-remove"], compound=LEFT) self.delete_button.grid(column=2, row=0, sticky=(E)) button_frame.grid(column=0, row=4, columnspan=2, sticky=(E), padx=shared_pad_x, pady=shared_pad_y) close_frame = Frame(main_frame) close_button = Button(close_frame, text="Close", image=self.icons["gtk-close"], compound=LEFT, command=self.on_closing) close_button.grid(column=0, row=0, sticky=(S, E)) close_frame.grid(column=0, row=5, columnspan=2, sticky=(S, E), padx=shared_pad_x, pady=(15, shared_pad_y)) self.my_window.grid_columnconfigure(0, weight=1) self.my_window.grid_rowconfigure(0, weight=1) main_frame.grid_columnconfigure(1, weight=1) main_frame.grid_rowconfigure(0, weight=1) main_frame.grid_rowconfigure(2, weight=0) main_frame.grid_rowconfigure(3, weight=1) main_frame.grid_rowconfigure(4, weight=1) main_frame.grid_rowconfigure(5, weight=1) condition_list.grid_columnconfigure(1, weight=1) button_frame.grid_rowconfigure(0, weight=1) self.my_window.protocol("WM_DELETE_WINDOW", self.on_closing) def on_closing(self): if self.close_callback is not None: self.close_callback() self.my_window.destroy() def up_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index - 1, state_current) self.condition_listbox.insert(index - 1, condition_current) self.execution_target_listbox.insert(index - 1, execution_target_current) self.conditionals.insert(index - 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index - 1) self.condition_listbox.selection_set(index - 1) self.execution_target_listbox.selection_set(index - 1) self.state_listbox.see(index - 1) if index - 1 == 0: self.up_button.config(state="disabled") self.down_button.config(state="normal") def down_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index + 1, state_current) self.condition_listbox.insert(index + 1, condition_current) self.execution_target_listbox.insert(index + 1, execution_target_current) self.conditionals.insert(index + 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index + 1) self.condition_listbox.selection_set(index + 1) self.execution_target_listbox.selection_set(index + 1) self.state_listbox.see(index + 1) if index + 1 == self.state_listbox.size() - 1: self.down_button.config(state="disabled") self.up_button.config(state="normal") def condition_list_scrollbar_callback(self, *args): self.state_listbox.yview(*args) self.condition_listbox.yview(*args) self.execution_target_listbox.yview(*args) def state_listbox_scroll(self, *args): self.condition_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) self.condition_list_scrollbar.set(*args) def condition_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) def execution_target_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.condition_listbox.yview_moveto(args[0]) def any_listbox_selected(self): self.up_button.config(state="normal") self.down_button.config(state="normal") if self.state_listbox.curselection( )[0] == self.state_listbox.size() - 1: self.down_button.config(state="disabled") if self.state_listbox.curselection()[0] == 0: self.up_button.config(state="disabled") self.delete_button.config(state="normal") self.then_entry.delete("1.0", END) self.then_entry.insert( END, self.conditionals[self.state_listbox.curselection()[0]][3]) self.if_text_variable.set( self.conditionals[self.state_listbox.curselection()[0]][1]) self.execution_target.set( self.conditionals[self.state_listbox.curselection()[0]][2]) self.active_checkbutton.set( self.conditionals[self.state_listbox.curselection()[0]][0]) def state_listbox_selected(self, event): index = self.state_listbox.curselection()[0] try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def condition_listbox_selected(self, event): index = self.condition_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def execution_target_listbox_selected(self, event): index = self.execution_target_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) self.any_listbox_selected()
class GetKeysDialog(Toplevel): def __init__(self, parent, title, action, currentKeySequences, _htest=False): """ action - string, the name of the virtual event these keys will be mapped to currentKeys - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest """ Toplevel.__init__(self, parent) self.configure(borderwidth=5) self.resizable(height=FALSE, width=FALSE) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.Cancel) self.parent = parent self.action = action self.currentKeySequences = currentKeySequences self.result = '' self.keyString = StringVar(self) self.keyString.set('') self.SetModifiersForPlatform( ) # set self.modifiers, self.modifier_label self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.CreateWidgets() self.LoadFinalKeyList() self.withdraw() #hide while setting geometry self.update_idletasks() self.geometry("+%d+%d" % (parent.winfo_rootx() + (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2), parent.winfo_rooty() + ((parent.winfo_height() / 2 - self.winfo_reqheight() / 2) if not _htest else 150)) ) #centre dialog over parent (or below htest box) self.deiconify() #geometry set, unhide self.wait_window() def CreateWidgets(self): frameMain = Frame(self, borderwidth=2, relief=SUNKEN) frameMain.pack(side=TOP, expand=TRUE, fill=BOTH) frameButtons = Frame(self) frameButtons.pack(side=BOTTOM, fill=X) self.buttonOK = Button(frameButtons, text='OK', width=8, command=self.OK) self.buttonOK.grid(row=0, column=0, padx=5, pady=5) self.buttonCancel = Button(frameButtons, text='Cancel', width=8, command=self.Cancel) self.buttonCancel.grid(row=0, column=1, padx=5, pady=5) self.frameKeySeqBasic = Frame(frameMain) self.frameKeySeqAdvanced = Frame(frameMain) self.frameControlsBasic = Frame(frameMain) self.frameHelpAdvanced = Frame(frameMain) self.frameKeySeqAdvanced.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5) self.frameKeySeqBasic.lift() self.frameHelpAdvanced.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.grid(row=1, column=0, sticky=NSEW, padx=5) self.frameControlsBasic.lift() self.buttonLevel = Button(frameMain, command=self.ToggleLevel, text='Advanced Key Binding Entry >>') self.buttonLevel.grid(row=2, column=0, stick=EW, padx=5, pady=5) labelTitleBasic = Label(self.frameKeySeqBasic, text="New keys for '" + self.action + "' :") labelTitleBasic.pack(anchor=W) labelKeysBasic = Label(self.frameKeySeqBasic, justify=LEFT, textvariable=self.keyString, relief=GROOVE, borderwidth=2) labelKeysBasic.pack(ipadx=5, ipady=5, fill=X) self.modifier_checkbuttons = {} column = 0 for modifier, variable in zip(self.modifiers, self.modifier_vars): label = self.modifier_label.get(modifier, modifier) check = Checkbutton(self.frameControlsBasic, command=self.BuildKeyString, text=label, variable=variable, onvalue=modifier, offvalue='') check.grid(row=0, column=column, padx=2, sticky=W) self.modifier_checkbuttons[modifier] = check column += 1 labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT, text=\ "Select the desired modifier keys\n"+ "above, and the final key from the\n"+ "list on the right.\n\n" + "Use upper case Symbols when using\n" + "the Shift modifier. (Letters will be\n" + "converted automatically.)") labelFnAdvice.grid(row=1, column=0, columnspan=4, padx=2, sticky=W) self.listKeysFinal = Listbox(self.frameControlsBasic, width=15, height=10, selectmode=SINGLE) self.listKeysFinal.bind('<ButtonRelease-1>', self.FinalKeySelected) self.listKeysFinal.grid(row=0, column=4, rowspan=4, sticky=NS) scrollKeysFinal = Scrollbar(self.frameControlsBasic, orient=VERTICAL, command=self.listKeysFinal.yview) self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set) scrollKeysFinal.grid(row=0, column=5, rowspan=4, sticky=NS) self.buttonClear = Button(self.frameControlsBasic, text='Clear Keys', command=self.ClearKeySeq) self.buttonClear.grid(row=2, column=0, columnspan=4) labelTitleAdvanced = Label( self.frameKeySeqAdvanced, justify=LEFT, text="Enter new binding(s) for '" + self.action + "' :\n" + "(These bindings will not be checked for validity!)") labelTitleAdvanced.pack(anchor=W) self.entryKeysAdvanced = Entry(self.frameKeySeqAdvanced, textvariable=self.keyString) self.entryKeysAdvanced.pack(fill=X) labelHelpAdvanced = Label( self.frameHelpAdvanced, justify=LEFT, text="Key bindings are specified using Tkinter keysyms as\n" + "in these samples: <Control-f>, <Shift-F2>, <F12>,\n" "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n" "Upper case is used when the Shift modifier is present!\n\n" + "'Emacs style' multi-keystroke bindings are specified as\n" + "follows: <Control-x><Control-y>, where the first key\n" + "is the 'do-nothing' keybinding.\n\n" + "Multiple separate bindings for one action should be\n" + "separated by a space, eg., <Alt-v> <Meta-v>.") labelHelpAdvanced.grid(row=0, column=0, sticky=NSEW) def SetModifiersForPlatform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys, it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # short name def ToggleLevel(self): if self.buttonLevel.cget('text')[:8] == 'Advanced': self.ClearKeySeq() self.buttonLevel.config(text='<< Basic Key Binding Entry') self.frameKeySeqAdvanced.lift() self.frameHelpAdvanced.lift() self.entryKeysAdvanced.focus_set() self.advanced = True else: self.ClearKeySeq() self.buttonLevel.config(text='Advanced Key Binding Entry >>') self.frameKeySeqBasic.lift() self.frameControlsBasic.lift() self.advanced = False def FinalKeySelected(self, event): self.BuildKeyString() def BuildKeyString(self): keyList = modifiers = self.GetModifiers() finalKey = self.listKeysFinal.get(ANCHOR) if finalKey: finalKey = self.TranslateKey(finalKey, modifiers) keyList.append(finalKey) self.keyString.set('<' + string.join(keyList, '-') + '>') def GetModifiers(self): modList = [variable.get() for variable in self.modifier_vars] return [mod for mod in modList if mod] def ClearKeySeq(self): self.listKeysFinal.select_clear(0, END) self.listKeysFinal.yview(MOVETO, '0.0') for variable in self.modifier_vars: variable.set('') self.keyString.set('') def LoadFinalKeyList(self): #these tuples are also available for use in validity checks self.functionKeys = ('F1', 'F2', 'F2', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12') self.alphanumKeys = tuple(string.ascii_lowercase + string.digits) self.punctuationKeys = tuple('~!@#%^&*()_-+={}[]|;:,.<>/?') self.whitespaceKeys = ('Tab', 'Space', 'Return') self.editKeys = ('BackSpace', 'Delete', 'Insert') self.moveKeys = ('Home', 'End', 'Page Up', 'Page Down', 'Left Arrow', 'Right Arrow', 'Up Arrow', 'Down Arrow') #make a tuple of most of the useful common 'final' keys keys = (self.alphanumKeys + self.punctuationKeys + self.functionKeys + self.whitespaceKeys + self.editKeys + self.moveKeys) self.listKeysFinal.insert(END, *keys) def TranslateKey(self, key, modifiers): "Translate from keycap symbol to the Tkinter keysym" translateDict = { 'Space': 'space', '~': 'asciitilde', '!': 'exclam', '@': 'at', '#': 'numbersign', '%': 'percent', '^': 'asciicircum', '&': 'ampersand', '*': 'asterisk', '(': 'parenleft', ')': 'parenright', '_': 'underscore', '-': 'minus', '+': 'plus', '=': 'equal', '{': 'braceleft', '}': 'braceright', '[': 'bracketleft', ']': 'bracketright', '|': 'bar', ';': 'semicolon', ':': 'colon', ',': 'comma', '.': 'period', '<': 'less', '>': 'greater', '/': 'slash', '?': 'question', 'Page Up': 'Prior', 'Page Down': 'Next', 'Left Arrow': 'Left', 'Right Arrow': 'Right', 'Up Arrow': 'Up', 'Down Arrow': 'Down', 'Tab': 'Tab' } if key in translateDict.keys(): key = translateDict[key] if 'Shift' in modifiers and key in string.ascii_lowercase: key = key.upper() key = 'Key-' + key return key def OK(self, event=None): if self.advanced or self.KeysOK(): # doesn't check advanced string yet self.result = self.keyString.get() self.destroy() def Cancel(self, event=None): self.result = '' self.destroy() def KeysOK(self): '''Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. ''' keys = self.keyString.get() keys.strip() finalKey = self.listKeysFinal.get(ANCHOR) modifiers = self.GetModifiers() # create a key sequence list for overlap check: keySequence = keys.split() keysOK = False title = 'Key Sequence Error' if not keys: tkMessageBox.showerror(title=title, parent=self, message='No keys specified.') elif not keys.endswith('>'): tkMessageBox.showerror(title=title, parent=self, message='Missing the final Key') elif (not modifiers and finalKey not in self.functionKeys + self.moveKeys): tkMessageBox.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (finalKey not in self.functionKeys + self.moveKeys + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' tkMessageBox.showerror(title=title, parent=self, message=msg) elif keySequence in self.currentKeySequences: msg = 'This key combination is already in use.' tkMessageBox.showerror(title=title, parent=self, message=msg) else: keysOK = True return keysOK
class TextureFrame(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.__list_label = [] self.__list_listbox = [] self.__list_scrollbar = [] self.__list_button = [] self.__texture = [] self.__loadIMG() #Precarga las texturas para despuer ser recortadas def __loadIMG(self): try: if sys.platform.startswith('win32'): ruta = "image\\texture.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/texture.png" self.__texture.append(Image.open(ruta)) except Exception as e: pass #Permite configurar un frame creado def ConfigureF(self, ax=600, ay=52, x=0, y=0, bg="#353535"): self.configure(height=ay, width=ax, background=bg) self.place(x=x, y=y) def addButtonI(self, dim=(0, 0, 206, 109), x=0, y=0, command=0): try: crop = self.__texture[0].crop(dim) render = ImageTk.PhotoImage(crop) nbutton = Button(self, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1") nbutton.image = render nbutton.place(x=x, y=y) self.__list_button.append(nbutton) if command == 1: nbutton.configure(command=self.showOne) elif command == 2: nbutton.configure(command=self.showAll) elif command == 3: pass elif command == 4: nbutton.configure(command=self.master.destroy) return nbutton except Exception as e: self.Error("Error al cargar Texturas") return -1 def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def yview(self, *args): self.listbox1.yview(*args) def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def Switch(self, root, Ventana2): root.deiconify() Ventana2.destroy() def load50(self, Poss, mode="a"): maxi = self.buscMax() I = Poss[0] F = Poss[1] if mode == "+": Poss[1] = Poss[1] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) Poss[0] = Poss[1] - 50 if Poss[0] < 0: Poss[0] = 0 elif mode == "-" and Poss[0] != 0: Poss[0] = Poss[0] - 50 if Poss[0] < 0: Poss[0] = 0 Poss[1] = Poss[0] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) if mode == "a" or Poss[0] != I or Poss[1] != F: asca = ManagementJson("Helloword.json") lista = asca.intervaloIF(Poss[0], Poss[1]) #cargando texto self.listbox1.delete(0, self.listbox1.size()) for x in range(0, len(lista["serial"])): if lista["status"][x] == "Riesgo Medio": self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) else: self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) def buscMax(self): f = open("config.txt", "r") f.seek(7) maxi = f.readline() f.close() return maxi def load1(self, listbox3, label1, label2, label3): asca = ManagementJson("Helloword.json") lista = asca.searchError(listbox3.get()) try: if lista == 0: label1.configure(text="No se encontro") label2.configure(text="No se encontro") label3.configure(text="No se encontro") return 0 except Exception as e: raise e label1.configure(text=lista[0]) label2.configure(text=lista[1]) label3.configure(text=lista[2])