class InfoFrame(Frame): def __init__(self, parent, question): Frame.__init__(self, parent) self.answer = StringVar() self.question = Label(self, text=question, style='Title.TLabel') self.question.grid(column=0, row=0, padx=10, pady=10, sticky='w') self.configure(background='yellow') self.question.configure(background='yellow') self.bar = Separator(self, orient=HORIZONTAL) self.bar.grid(column=0, row=2, columnspan=2, padx=5, pady=5, sticky='nsew') self.ok = Button(self, text='OK', command=self.OkBut) self.ok.grid(column=0, row=3, padx=5, pady=5) self.grid() # Center the Window parent.update_idletasks() xp = (parent.winfo_screenwidth() / 2) - (self.winfo_width() / 2) - 8 yp = (parent.winfo_screenheight() / 2) - (self.winfo_height() / 2) - 20 parent.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(), self.winfo_height(), xp, yp)) self.update() parent.mainloop() def OkBut(self): self.quit()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): #title self.parent.title("HW3") #pack_info self.pack(fill=BOTH, expand=1) #Button_SelectFile Button(self, text="Select File", command=openFile).grid(row=0, column=0, pady=5) self.fileName = StringVar() Label(self, textvariable=self.fileName).grid(row=0, column=1, columnspan=2, pady=5, sticky=W) #Default_file self.fileName = StringVar(value="./dataset/ukbench00000.jpg") #Image_SelectedFile self.thumb = Label(self) self.thumb.grid(row=0, column=1, pady=5, sticky=W) image = Image.open(self.fileName.get()) image = ImageTk.PhotoImage( image.resize((int(image.size[0] * 0.8), int(image.size[1] * 0.8)), Image.ANTIALIAS)) self.thumb.configure(image=image) self.thumb.image = image #mode_SelectMode Label(self, text="Select Mode: ").grid(row=1, column=0, pady=5) mode = StringVar(self) #default mode.set("Q3-SIFT Visual Words") om = OptionMenu(self, mode, "Q1-ColorHistogram", "Q2-ColorLayout", "Q3-SIFT Visual Words", "Q4-Visual Words using stop words") om.grid(row=1, column=1, pady=5, sticky=W) #Button_Search Button(self, text="SEARCH", command=lambda: startSearching(self.fileName.get(), mode.get()) ).grid(row=3, column=0, pady=5) self.imgs = [] #RankList for i in xrange(10): self.imgs.append(Label(self)) self.imgs[i].grid(row=i / 5 + 4, column=i % 5, padx=5, pady=10)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("HW3") self.pack(fill=BOTH, expand=1) # File abtn = Button(self, text="-- Select File --", command=openFile) abtn.grid(row=0, column=0, pady=5) self.fileName = StringVar(value="./dataset/clothing/ukbench00000.jpg") albl = Label(self, textvariable=self.fileName) albl.grid(row=0, column=2, columnspan=3, pady=5, sticky=W) self.thumb = Label(self) self.thumb.grid(row=0, column=1, pady=5, sticky=W) image = Image.open(self.fileName.get()) image = ImageTk.PhotoImage( image.resize((image.size[0] / 2, image.size[1] / 2), Image.ANTIALIAS)) self.thumb.configure(image=image) self.thumb.image = image # Mode mode = StringVar(self) mode.set('-- Select Mode --') menu = OptionMenu(self, mode, 'Q1-Color_Histogram', 'Q2-Color_Layout', 'Q3-SIFT_Visual_Words', 'Q4-Visual_Words_Using_Stop_Words', 'Q5-Average_HSV', 'Q6-HSV_Histogram') menu.grid(row=1, column=0, pady=5, sticky=W) # Start Searching dbtn = Button( self, text="START SEARCHING", command=lambda: startSearching(mode.get(), self.fileName.get())) dbtn.grid(row=1, column=1, pady=5, sticky=W) # Return Ranking List self.imgs = [] for i in xrange(10): self.imgs.append(Label(self)) self.imgs[i].grid(row=i / 5 + 4, column=i % 5, padx=10, pady=20)
class FirstWindow(Frame): def __init__(self, parent, controller, listener): Frame.__init__(self, parent) self.parent = parent self.controller = controller self.listener = listener self.controller.add_listener(self.listener) self.initUI() def initUI(self): self.centerWindow() self.parent.title("Cursor") self.style = Style() self.style.theme_use("clam") self.style.configure("TFrame") self.pack(fill=BOTH, expand=1) self.label = Label(self) self.label.configure(text="Hold your hand above the device for two seconds...") self.label.place(x=50, y=50) quitButton = Button(self, text="Quit", command=self.quit) quitButton.place(x=50, y=100) def update_label(self): self.label.configure(text="You can now use the cursor.") def remove(self): self.controller.remove_listener(self.listener) def centerWindow(self): w, h = 450, 180 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
class StatusFrame(Frame): def __init__(self, parent, passfail, failtext): Frame.__init__(self, parent) self.status = StringVar() self.status_text = StringVar() self.statuslbl = Label(self, textvariable=self.status, style='Title.TLabel'); self.statuslbl.grid(column=0, row=1, columnspan=2, padx=100, pady=10) self.bar = Separator(self, orient=HORIZONTAL); self.bar.grid(column=0, row=2, columnspan=2, padx=5, pady=5, sticky='nsew') self.ok = Button(self, text='OK', command=self.OkBut, width=10); self.ok.grid(column=0, columnspan=2, row=4, padx=5, pady=5) if passfail == 'PASS': self.TestPassed() elif passfail == 'FAIL': self.TestFailed(failtext) else: self.status.set('What?????') self.grid() # Center the Window parent.update_idletasks() xp = (parent.winfo_screenwidth() / 2) - (self.winfo_width() / 2) - 8 yp = (parent.winfo_screenheight() / 2) - (self.winfo_height() / 2) - 20 parent.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(), self.winfo_height(), xp, yp)) parent.mainloop() def OkBut(self): self.quit() def StatusText(self, text ): self.status_text.set(text) def TestInProgress(self): self.status.set('Test In Progress') self.statuslbl.configure(foreground='black') def TestPassed(self): self.status.set('Test PASSED') self.configure(background='green') self.statuslbl.configure(background='green',foreground='yellow') def TestFailed(self, text): self.status.set('Test FAIL') self.configure(background='red') self.statuslbl.configure(background='red',foreground='yellow') self.text = Text( self, relief=SUNKEN, width=110, height=16); self.text.grid(column=0, row=3, columnspan=2, sticky='nsew', padx=10, pady=10) self.text.insert(INSERT,text)
class Reader(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Graphs") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, weight=1) self.columnconfigure(6, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) menu = Menu(self.parent) self.parent.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Load data",command = self.load_data) # lable to show current file and chanel self.file_lbl = Label(self, text="") self.file_lbl.grid(row = 0 , column = 3, pady=4, padx=5) # list box fro data files self.file_list = ScrolledList(self,lambda x: self.load_hunt_data(x)) self.file_list.grid(row=1, column=0, columnspan=3, rowspan=4, padx=5, sticky=E+W+S+N) # chanel graph viewer self.graph_viewer = TkinterGraph(self) self.graph_viewer.grid(row=1, column=3, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N) btn1 = Button(self, text="Left",command = lambda: self.plot_left()) btn1.grid(row=1, column=6) btn2 = Button(self, text="Right", command = lambda:self.plot_right()) btn2.grid(row=2, column=6, pady=4) # frames for the classifier for the two chanels self.frame_left = Frame(self, borderwidth=1) self.frame_right = Frame(self, borderwidth=1) self.frame_left.grid(row=5,column=3,columnspan=2, rowspan=1) btn4 = Button(self, text="SAVE", command = lambda:self.save_graph()) btn4.grid(row=5, column=6) # note manual addition of labels so that the lable will be to the right of tha radio button self.classify_left = StringVar() Label(self.frame_left,text="Left :").pack(side=LEFT) Label(self.frame_left,text="Type A").pack(side=LEFT) rb1 = Radiobutton(self.frame_left,variable=self.classify_left,value="TypeA") rb1.pack(side=LEFT) Label(self.frame_left,text="Type B").pack(side=LEFT) rb1 = Radiobutton(self.frame_left,variable=self.classify_left,value="TypeB") rb1.pack(side=LEFT) Label(self.frame_left,text="Type C").pack(side=LEFT) rb1 = Radiobutton(self.frame_left,variable=self.classify_left,value="TypeC") rb1.pack(side=LEFT) Label(self.frame_left,text="Type D").pack(side=LEFT) rb1 = Radiobutton(self.frame_left,variable=self.classify_left,value="TypeD") rb1.pack(side=LEFT) self.classify_right = StringVar() Label(self.frame_right,text="Right :").pack(side=LEFT) Label(self.frame_right,text="Type A").pack(side=LEFT) rb1 = Radiobutton(self.frame_right,variable=self.classify_right,value="TypeA") rb1.pack(side=LEFT) Label(self.frame_right,text="Type B").pack(side=LEFT) rb1 = Radiobutton(self.frame_right,variable=self.classify_right,value="TypeB") rb1.pack(side=LEFT) Label(self.frame_right,text="Type C").pack(side=LEFT) rb1 = Radiobutton(self.frame_right,variable=self.classify_right,value="TypeC") rb1.pack(side=LEFT) Label(self.frame_right,text="Type D").pack(side=LEFT) rb1 = Radiobutton(self.frame_right,variable=self.classify_right,value="TypeD") rb1.pack(side=LEFT) def load_data(self): # calls the file dialog box name = askopenfilename() (d_path,d_name)=split(name) # just want to extract the path of the file self.mypath = d_path # get 'filtered' files from that path files = self.get_files() # display in the list box self.file_list.load_data(files) def load_hunt_data(self,selection): (self.indx , self.filename) = selection d_file = join(self.mypath,self.filename) l_array=[] r_array=[] with open(d_file) as f: for line in f: data = line.split(',') if data[5]!='': r_array.append(data[5]) # RL_PVR l_array.append(data[6]) # LL_PVR self.rawy_l = numpy.array(l_array[1:]) # form 1 romove headder self.rawy_r = numpy.array(r_array[1:]) self.rawx = [i for i in range(len(self.rawy_l))] # reset the classification buttons self.classify_left.set("TypeA") self.classify_right.set("TypeA") self.plot_left() def plot_left(self): # choose th correct fram of radio buttons self.frame_right.grid_forget() self.frame_left.grid(row=5,column=3,columnspan=2, rowspan=1) # change display name self.file_lbl.configure(text=self.filename+" : Left") self.graph_viewer.change_data(self.rawx,self.rawy_l) def plot_right(self): self.frame_left.grid_forget() self.frame_right.grid(row=5,column=3,columnspan=2, rowspan=1) self.file_lbl.configure(text=self.filename+" : Right") self.graph_viewer.change_data(self.rawx,self.rawy_r) def save_graph(self): self.file_list.remove_item(self.indx) d_file = join(self.mypath,self.filename) # add a done prefix to the file name n_file = join(self.mypath,"done-"+self.filename) rename(d_file,n_file) # get the front of the filename fparts = self.filename.split('.') # save data wit the same name but with the chanel prefix and a dat postfix l_file = join(self.mypath,self.classify_left.get()+'-Left-'+fparts[0]+'.dat') # open file to write f = open(l_file, 'w') for v in self.rawy_l: f.write(v+'\n') f.close() r_file = join(self.mypath,self.classify_right.get()+'-Right-'+fparts[0]+'.dat') # open file to write f = open(r_file, 'w') for v in self.rawy_r: f.write(v+'\n') f.close() def get_files(self): files = [] for filename in listdir(self.mypath): # just get the files # note that it has to have the compleate path and name if isfile(join(self.mypath,filename)): # split the file name in to parts files.append(filename) #parts = filename.split('.') #print parts[-1] return files
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.buttons = {} self.nodes = {} self.edges = {} self.active_node = None self.active_edge = None self.start = None self.x = None self.y = None self.cycles = None self.show_cycles_only_mode = False self.steps = None self.step_index = None self.parent.title("Demonstrační aplikace - nalezení elementárních cyklů v orientovaném grafu") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(5, weight=1) self.rowconfigure(6, pad=7) self.label = Label(self, text="graf1.graphml") self.label.grid(sticky=W, pady=4, padx=5) self.canvas = Canvas(self) self.canvas.bind('<Double-Button-1>', self.event_add_node) self.canvas.bind('<Button-1>', self.event_add_edge_start) self.canvas.bind('<B1-Motion>', self.event_add_edge_move) self.canvas.bind('<ButtonRelease-1>', self.event_add_edge_end) self.canvas.bind('<Button-3>', self.event_move_node_start) self.canvas.bind('<B3-Motion>', self.event_move_node) self.canvas.pack() self.canvas.grid(row=1, column=0, columnspan=2, rowspan=6, padx=5, sticky=E + W + S + N) self.buttons['start'] = b = Button(self, text="Start", width=15) b.bind('<Button-1>', self.event_start) b.grid(row=1, column=3) self.buttons['next'] = b = Button(self, text=">>", width=15, state=DISABLED) b.bind('<Button-1>', self.event_next_step) b.grid(row=2, column=3, pady=4) self.buttons['prev'] = b = Button(self, text="<<", width=15, state=DISABLED) b.bind('<Button-1>', self.event_prev_step) b.grid(row=3, column=3, pady=4) b = Checkbutton(self, text="Pouze cykly", command=self.event_change_mode) b.grid(row=4, column=3, pady=4) self.buttons['reset'] = b = Button(self, text="Reset", width=15) b.bind('<Button-1>', self.event_reset) b.grid(row=6, column=3) menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Načíst", command=self.onLoad) fileMenu.add_command(label="Uložit", command=self.onSave) fileMenu.add_separator() fileMenu.add_command(label="Konec", command=self.onExit) menubar.add_cascade(label="Soubor", menu=fileMenu) fileMenu = Menu(menubar) fileMenu.add_command(label="O aplikaci", command=self.onAbout) menubar.add_cascade(label="Nápověda", menu=fileMenu) def onExit(self): self.quit() def onLoad(self): fileTypes = [('Soubory typu GraphML', '*.graphml')] dialog = tkFileDialog.Open(self, filetypes=fileTypes) filename = dialog.show() if filename != '': self.readFile(filename) def onSave(self): fileTypes = [('GraphML files', '*.graphml')] dialog = tkFileDialog.SaveAs(self, filetypes=fileTypes) filename = dialog.show() if filename != '': if not filename.endswith(".graphml"): filename += ".graphml" self.writeFile(filename) def onAbout(self): box.showinfo("O aplikaci", "Demonstrace algoritmu nalezení elementárních cyklů v orientovaném grafu podle D. B. Johnsona. \n\n" "Autoři:\n" "Paulík Miroslav\n" "Pavlů Igor\n" "FIT VUT v Brně 2013") def readFile(self, filename): self.reset() try: parser = GraphMLParser() g = parser.parse(filename) except Exception: box.showerror("Chyba při zpracování vstupního souboru", "Chybný formát souboru.") return nodeMap = {} try: for gnode in g.nodes(): nodeMap[gnode.id] = self.__add_node(int(gnode['x']), int(gnode['y'])) except KeyError: box.showerror("Chyba při zpracování vstupního souboru", "Uzlum chybi udaje o pozici (atributy x a y).") self.reset() return try: for gedge in g.edges(): start = nodeMap[gedge.node1.id] end = nodeMap[gedge.node2.id] isCurve = gedge.node1.id == gedge.node2.id self.__add_edge(start, end, isCurve) self.label.configure(text=os.path.basename(filename)) except KeyError: box.showerror("Chyba při zpracování vstupního souboru", "Soubor obsahuje hrany spojujici neexistujici hrany") self.reset() return self.repaint() def writeFile(self, filename): g = Graph() for i in self.nodes: node = self.nodes[i] node.name = str(i) gnode = g.add_node(i) gnode['label'] = i gnode['x'] = node.x gnode['y'] = node.y for i in self.edges: edge = self.edges[i] edge.name = i parser = GraphMLParser() parser.write(g, filename) def repaint(self): for e in self.edges: edge = self.edges[e] self.canvas.itemconfigure(e, fill=edge.color) for v in self.nodes: node = self.nodes[v] self.canvas.itemconfigure(v, fill=node.color) def reset_colors(self): for n in self.nodes: self.nodes[n].color = "white" for e in self.edges: self.edges[e].color = "grey" def reset(self): self.nodes = {} self.edges = {} self.canvas.delete("all") self.buttons['prev'].config(state=DISABLED) self.buttons['next'].config(state=DISABLED) def run(self): x = ElementaryCircuitsDetector(self.nodes, self.edges) x.detect_cycles() self.cycles = x.cycles self.step_index = 0 self.steps = x.get_all_steps() self.algorithm_step_move(0) if len(self.steps) > 0: self.buttons['prev'].config(state=1) self.buttons['next'].config(state=1) def event_reset(self, event): self.reset() def event_prev_step(self, event): if str(self.buttons['prev'].cget("state")) != str(DISABLED): self.algorithm_step_move(-1) def event_next_step(self, event): if str(self.buttons['next'].cget("state")) != str(DISABLED): self.algorithm_step_move(1) def event_start(self, event): self.run() def event_change_mode(self): self.show_cycles_only_mode = not self.show_cycles_only_mode self.run() def event_add_edge_start(self, event): self.x = event.x self.y = event.y def event_add_edge_move(self, event): if self.active_edge is None: self.active_edge = self.canvas.create_line(self.x, self.y, event.x, event.y, arrow="last", width=2) else: x1, y1, x2, y2 = self.canvas.coords(self.active_edge) self.canvas.coords(self.active_edge, x1, y1, event.x, event.y) def event_add_edge_end(self, event): if self.active_edge is None: return x1, y1, x2, y2 = self.canvas.coords(self.active_edge) start = self.__get_node_from_position(x1, y1) end = self.__get_node_from_position(x2, y2) if start is None or end is None: self.canvas.delete(self.active_edge) elif start == end: self.canvas.delete(self.active_edge) edge = Edge(start, start, True) points = edge.get_coords() self.active_edge = self.canvas.create_line(points, width=2, smooth=True, arrow="last") self.canvas.tag_lower(self.active_edge, min(self.nodes.keys())) self.edges[self.active_edge] = edge else: x, y = self.__calculate_edge_end_from_nodes(start, end) self.canvas.coords(self.active_edge, start.x, start.y, x, y) self.canvas.tag_lower(self.active_edge, min(self.nodes.keys())) edge = Edge(start, end) self.edges[self.active_edge] = edge self.active_edge = None self.x = None self.y = None def event_move_node_start(self, event): id = self.__get_id_from_position(event.x, event.y) if id is None: return self.__activate_node(id) self.x = event.x self.y = event.y def event_move_node(self, event): id = self.active_node if id is None: return deltax = event.x - self.x deltay = event.y - self.y self.canvas.move(id, deltax, deltay) self.x = event.x self.y = event.y coord = self.canvas.coords(id) self.nodes[self.active_node].x = (coord[2] - coord[0]) / 2 + coord[0] self.nodes[self.active_node].y = (coord[3] - coord[1]) / 2 + coord[1] self.__repair_edge_starting_in_node(self.nodes[self.active_node]) self.__repair_edge_ending_in_node(self.nodes[self.active_node]) def event_add_node(self, event): id = self.__get_id_from_position(event.x, event.y, reverse=True) if id is None or id not in self.nodes: self.__add_node(event.x, event.y) def __repair_edge_ending_in_node(self, node): list_of_edge_ids = [] for edge_id in self.edges: edge = self.edges[edge_id] if edge.end == node: list_of_edge_ids.append(edge_id) for edge_id in list_of_edge_ids: edge = self.edges[edge_id] x, y = self.__calculate_edge_end_from_nodes(edge.start, edge.end) if edge.is_curve: coords = edge.get_coords() self.canvas.coords(edge_id, coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0], coords[2][1], coords[3][0], coords[3][1]) else: self.canvas.coords(edge_id, edge.start.x, edge.start.y, x, y) def __repair_edge_starting_in_node(self, node): list_of_edge_ids = [] for edge_id in self.edges: edge = self.edges[edge_id] if edge.start == node: list_of_edge_ids.append(edge_id) for edge_id in list_of_edge_ids: edge = self.edges[edge_id] x, y = self.__calculate_edge_end_from_nodes(edge.start, edge.end) if edge.is_curve: coords = edge.get_coords() self.canvas.coords(edge_id, coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0], coords[2][1], coords[3][0], coords[3][1]) else: self.canvas.coords(edge_id, edge.start.x, edge.start.y, x, y) def __calculate_edge_end_from_nodes(self, start_node, end_node): diffx = end_node.x - start_node.x diffy = end_node.y - start_node.y distance = math.sqrt(diffx ** 2 + diffy ** 2) if distance > 0: ratio = NODE_SIZE / 2 / distance x = end_node.x - diffx * ratio y = end_node.y - diffy * ratio return x, y return end_node.x, end_node.y def __activate_node(self, id): self.__deactivate_node() if id in self.nodes: self.active_node = id def __deactivate_node(self): self.active_node = None def __get_id_from_position(self, x, y, reverse=False): overlaping = self.canvas.find_overlapping(x, y, x, y) if len(overlaping) > 0: if reverse: return overlaping[-1] else: return overlaping[0] else: return None def __get_node_from_position(self, x, y): id = self.__get_id_from_position(x, y) if id is not None and id in self.nodes: return self.nodes[id] else: return None def __add_node(self, x, y): node = Node(x, y) id = self.canvas.create_oval(node.get_coord(), fill="blue") self.nodes[id] = node return node def __add_edge(self, start, end, is_curve=False): edge = Edge(start, end, is_curve) if is_curve: id = self.canvas.create_line(edge.get_coords(), width=2, smooth=True, arrow="last") else: id = self.canvas.create_line(start.x, start.y, end.x, end.y, arrow="last", width=2) self.edges[id] = edge self.canvas.tag_lower(id, min(self.nodes.keys())) self.__repair_edge_starting_in_node(start) return edge def algorithm_step_move(self, move): if self.show_cycles_only_mode: # cycles only if (self.step_index + move) < len(self.cycles) and self.step_index + move >= 0: self.step_index += move self.reset_colors() colors = ['green', 'blue', 'red', 'yellow', 'purple', 'brown'] color_index = self.step_index % len(colors) for edge in self.cycles[self.step_index]: edge.color = edge.start.color = edge.end.color = colors[color_index] self.repaint() else: if (self.step_index + move) < len(self.steps) and self.step_index + move >= 0: self.step_index += move self.reset_colors() for i in range(self.step_index + 1): colors = self.steps[i] for id in colors: if id in self.nodes.keys(): self.nodes[id].color = colors[id] elif id in self.edges.keys(): self.edges[id].color = colors[id] self.repaint()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): #title self.parent.title("HW4_Mosaic") #pack_info self.pack(fill=BOTH, expand=1) #Button_SelectFile Button(self, text="Select File", command=openFile).grid(row=0, column=0, pady=5) self.fileName = StringVar() Label(self, textvariable=self.fileName).grid(row=0, column=1, columnspan=2, pady=5, sticky=W) #Default_file self.fileName = StringVar(value="./dataset/ukbench00000.jpg") #Image_SelectedFile self.thumb = Label(self) self.thumb.grid(row=0, column=1, pady=5, sticky=W) image = Image.open(self.fileName.get()) image = ImageTk.PhotoImage(image.resize((600, 450), Image.ANTIALIAS)) self.thumb.configure(image=image) self.thumb.image = image self.thumb_mosaic = Label(self) self.thumb_mosaic.grid(row=0, column=3, pady=5, sticky=W) self.thumb_mosaic.configure(image=image) self.thumb_mosaic.image = image #mode_SelectMode Label(self, text="Select Mode: ").grid(row=1, column=0, pady=5) mode = StringVar(self) #default mode.set("AVG_RGB") om = OptionMenu(self, mode, "AVG_RGB", "AVG_HSV", "Color_Layout") om.grid(row=1, column=1, pady=5, sticky=W) #mode_SelectDistanceAlgo. Label(self, text="Select Distance Algorithm: ").grid(row=2, column=0, pady=5) distanceMode = StringVar(self) #default distanceMode.set("Euclidean_Distance") distanceOm = OptionMenu(self, distanceMode, "Euclidean_Distance", "Manhattan_Distance", "Cosine_Similarity") distanceOm.grid(row=2, column=1, pady=5, sticky=W) #mode_selectCutGrids Label(self, text="Cut Into n*n grids. n = ").grid(row=3, column=0, pady=5, sticky=W) self.grids = StringVar(value="50") vcmd = (self.register(self.onValidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.gridsTextField = Entry(self, textvariable=self.grids, width=3, validate='key', validatecommand=vcmd) self.gridsTextField.grid(row=3, column=1, pady=1, sticky=W) #Button_START Button(self, text="START", command=lambda: startSearching(self.fileName.get(), mode.get( ), distanceMode.get(), int(self.gridsTextField.get()))).grid( row=4, column=0, pady=5) def onValidate(self, d, i, P, s, S, v, V, W): return True if S in '1234567890' else False
class StatusFrame(Frame): def __init__(self, parent, passfail, failtext): Frame.__init__(self, parent) self.status = StringVar() self.status_text = StringVar() self.statuslbl = Label(self, textvariable=self.status, style='Title.TLabel') self.statuslbl.grid(column=0, row=1, columnspan=2, padx=100, pady=10) self.bar = Separator(self, orient=HORIZONTAL) self.bar.grid(column=0, row=2, columnspan=2, padx=5, pady=5, sticky='nsew') self.ok = Button(self, text='OK', command=self.OkBut, width=10) self.ok.grid(column=0, columnspan=2, row=4, padx=5, pady=5) if passfail == 'PASS': self.TestPassed() elif passfail == 'FAIL': self.TestFailed(failtext) else: self.status.set('What?????') self.grid() # Center the Window parent.update_idletasks() xp = (parent.winfo_screenwidth() / 2) - (self.winfo_width() / 2) - 8 yp = (parent.winfo_screenheight() / 2) - (self.winfo_height() / 2) - 20 parent.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(), self.winfo_height(), xp, yp)) parent.mainloop() def OkBut(self): self.quit() def StatusText(self, text): self.status_text.set(text) def TestInProgress(self): self.status.set('Test In Progress') self.statuslbl.configure(foreground='black') def TestPassed(self): self.status.set('Test PASSED') self.configure(background='green') self.statuslbl.configure(background='green', foreground='yellow') def TestFailed(self, text): self.status.set('Test FAIL') self.configure(background='red') self.statuslbl.configure(background='red', foreground='yellow') self.text = Text(self, relief=SUNKEN, width=110, height=16) self.text.grid(column=0, row=3, columnspan=2, sticky='nsew', padx=10, pady=10) self.text.insert(INSERT, text)
class File_editor: def __init__(self,topwin,argv,**kwargs): global text_font self.topwin = topwin self.filefolder = 'log/' if len(argv) > 1: self.filefolder = argv[1] self.thread_status = 'Ready:' set_winicon(self.topwin,'icon_grey') self.frame3 = Frame(self.topwin, width=700,height=40, relief=SUNKEN) self.frame3.pack_propagate(0) self.frame3.pack(side=BOTTOM,pady=10) self.frame1 = Frame(self.topwin, width=150,height=460, relief=SUNKEN) self.frame1.pack_propagate(0) self.frame1.pack(side=LEFT,padx=10,pady=10) self.frame2 = Frame(self.topwin, width=550,height=460, relief=SUNKEN) self.frame2.pack_propagate(0) self.frame2.pack(side=LEFT,padx=10,pady=10) self.frame4 = Frame(self.frame3, width=450,height=40, relief=SUNKEN) self.frame4.pack_propagate(0) self.frame4.pack(side=RIGHT) self.label1 = Label(self.frame1,text='Files:') self.label1.pack(side=TOP) self.Fscroll = Scrollbar(self.frame1) self.Fscroll.pack(side=RIGHT, fill=Y, expand=NO) self.listbox = Listbox(self.frame1) self.listbox.pack(expand=1, fill="both") self.Fscroll.configure(command=self.listbox.yview) self.listbox.configure(yscrollcommand=self.Fscroll.set) self.Tbox = Text(self.frame2, height=12, width=40,wrap=WORD) self.Tbox.tag_configure('blackcol', font=text_font, foreground='black') self.Tbox.tag_configure('redcol', font=text_font, foreground='red') self.Tbox.configure(inactiveselectbackground="#6B9EB7", selectbackground="#4283A4") self.Tbox.tag_raise("sel") self.Tscroll = Scrollbar(self.frame2) self.Tbox.focus_set() self.Tbox.config(yscrollcommand=self.Tscroll.set) self.Tscroll.config(command=self.Tbox.yview) self.Tscroll.pack(side=RIGHT, fill=Y) self.Tbox.pack(side=BOTTOM,fill=BOTH,expand=1) self.loadLabel = Label(self.frame3,text='Ready:') self.loadLabel.pack(side=LEFT,padx=30) bb1 = Button(self.frame4, text='Change folder', command=self.load_other_folder) bb1.pack(side=LEFT,padx=30) bb2 = Button(self.frame4, text='Save', command=self.save_file) bb2.pack(side=LEFT) bb3 = Button(self.frame4, text='Close', command=self.close_func) bb3.pack(side=LEFT,padx=30) self.reload_file_list() self.topwin.bind('<Escape>', self.close_func) self.topwin.bind("<Control-a>", lambda x: widget_sel_all(self.Tbox)) self.Tbox.bind('<Control-f>',lambda x: search_text_dialog(self.Tbox,self.Tscroll)) self.listbox.bind('<Button-1>', lambda x: self.topwin.after(20,self.file_loader)) self.topwin.protocol('WM_DELETE_WINDOW', self.close_func) self.topwin.after(200,self.after_task) self.colortag() def after_task(self): self.topwin.bind('<Configure>', self.on_resize) def reload_file_list(self): try: self.listbox.delete(0, END) ## file_list = os.listdir(self.filefolder) file_list = next(os.walk(self.filefolder))[2] can_insert = True ignored_files = ['.lnk','.exe','.jpg','.jpeg','.mp3','.ogg','.avi','.mkv','.flv','.iso','.apk','.mp4', '.wav','.doc','.docx','.zip','.sys'] for x in file_list: for extension in ignored_files: if x[-len(extension):] == extension: can_insert = False break if can_insert == True: self.listbox.insert("end", x) can_insert = True except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) def load_other_folder(self): self.topwin.lower() try: self.topwin.unbind('<Configure>') self.filefolder = (askdirectory()+'/') self.reload_file_list() self.topwin.after(300,self.after_task) except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) self.topwin.lift() self.colortag() def save_file(self): self.topwin.unbind('<Configure>') if self.thread_status == 'Ready:': self.thread_status = 'Working:' self.loadLabel.configure(text= self.thread_status) try: if os.path.exists(self.filefolder + self.title): savef('',self.filefolder + self.title) fh = open(self.filefolder + self.title, 'a') text = self.Tbox.get(1.0, END) fh.write(text) fh.close() self.thread_status = 'Ready:' self.loadLabel.configure(text= self.thread_status) except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) self.topwin.after(200,self.after_task) def file_loader(self): global OS num = self.listbox.get(self.listbox.curselection()) try: text = readf(self.filefolder+num) except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) if self.thread_status == 'Ready:': self.thread_status = 'Working:' self.topwin.unbind('<Configure>') self.loadLabel.configure(text= self.thread_status) self.title = num self.topwin.title(self.title) try: if OS == 'Linux': Thread(target=self.file_loader_thread,args=(text,)).start() else: self.file_loader_thread(text) except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) def file_loader_thread(self,text): try: cnt = [0,0.01] filelen = len(text) self.Tbox.delete(1.0,END) for x in text: self.Tbox.insert(END, x+'\n','blackcol') cnt[0]+= 1 if cnt[0] > filelen*cnt[1]: self.loadLabel.configure(text = self.thread_status+' '+str(cnt[0])+'/'+str(filelen)) self.Tbox.yview(END) cnt[1] += 0.01 except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.thread_status = 'Ready:' self.loadLabel.configure(text= self.thread_status) self.Tbox.yview(END) self.topwin.after(200,self.after_task) def on_resize(self,*arg): try: self.wX = self.topwin.winfo_width() self.wY = self.topwin.winfo_height() self.frame1_xsize = 120+0.05*self.wX self.frame1_ysize = self.wY-50 self.frame2_xsize = self.wX-(120+0.05*self.wX) self.frame2_ysize = self.wY-50 self.frame3_xsize = self.wX*1.00 self.frame3_ysize = 40 self.frame4_xsize = self.frame3_xsize/1.55 self.frame4_ysize = self.frame3_ysize self.frame1.config(width=self.frame1_xsize,height=self.frame1_ysize) self.frame2.config(width=self.frame2_xsize,height=self.frame2_ysize) self.frame3.config(width=self.frame3_xsize,height=self.frame3_ysize) self.frame4.config(width=self.frame4_xsize,height=self.frame4_ysize) except Exception as e: self.Tbox.insert(END, str(e), 'redcol') self.Tbox.yview(END) def colortag(self): pass ## Themes are disabled ## tag_colors(text=[self.Tbox],scroll=[self.Tscroll,self.Fscroll],listbox=[self.listbox],window=[self.topwin], ## frame=[self.frame1,self.frame2,self.frame3,self.frame4],label=[self.label1,self.loadLabel]) def widget_sel_all(self,*arg): self.Tbox.tag_add(SEL, "1.0", END) self.Tbox.mark_set(INSERT, "1.0") self.Tbox.see(INSERT) def close_func(self,*arg): self.topwin.destroy()
class gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerUI(w=600, h=250) def initUI(self): self.parent.title("FIND BLR COEFFICIENT VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1) # weight attibute is used to make them growable ###### GUI Control Variables ###### self.LIMIT_L = IntVar() self.LIMIT_H = IntVar() self.PULSE_R = IntVar() self.PULSE_L = IntVar() self.pulse_height = DoubleVar() self.hdf5_file = StringVar() self.PMT = IntVar() self.EVENT = IntVar() self.amplitude_range = DoubleVar() self.delta = DoubleVar() self.noise_sigma = DoubleVar() self.coeff = DoubleVar() #self.DRAW = BooleanVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E + W + S + N) self.hdf5_file.set("2052.h5.z") e1 = Entry(self, textvariable=self.hdf5_file, width=30) e1.grid(row=1, column=1, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="HDF5 file") e1_label.grid(row=0, column=1, sticky=W, columnspan=5, pady=5) self.PMT.set("0") sb1 = Spinbox(self, from_=0, to=12, width=3, textvariable=self.PMT) sb1.grid(row=3, column=2, sticky=W) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2, column=2, padx=0, sticky=W) self.EVENT.set("0") sb1 = Spinbox(self, from_=0, to=1000, width=5, textvariable=self.EVENT) sb1.grid(row=3, column=3, sticky=W) sb1_label = Label(self, text="EVENT") sb1_label.grid(row=2, column=3, padx=0, sticky=W) self.LIMIT_L.set("19000") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_L) sb1.grid(row=5, column=2, sticky=W) sb1_label = Label(self, text="ROI Start ") sb1_label.grid(row=4, column=2, padx=0, sticky=W) self.LIMIT_H.set("22500") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_H) sb1.grid(row=5, column=3, sticky=W) sb1_label = Label(self, text="ROI End ") sb1_label.grid(row=4, column=3, padx=0, sticky=W) self.PULSE_R.set("20142") sb1 = Spinbox(self, from_=0, to=100000, width=8, textvariable=self.PULSE_R) sb1.grid(row=5, column=4, sticky=E) sb1_label = Label(self, text=" Pulse Rise") sb1_label.grid(row=4, column=4, padx=0, sticky=E) self.PULSE_L.set("1200") sb1 = Spinbox(self, from_=0, to=5000, width=8, textvariable=self.PULSE_L) sb1.grid(row=5, column=5, sticky=E) sb1_label = Label(self, text=" Pulse Length") sb1_label.grid(row=4, column=5, padx=0, sticky=E) sb1_label = Label(self, text=" ") sb1_label.grid(row=2, column=7, padx=0, sticky=W) sb1_label = Label(self, text=" ") sb1_label.grid(row=6, column=7, padx=0, sticky=W) self.pulse_height.set("545.5") sb1 = Entry(self, width=8, textvariable=self.pulse_height) sb1.grid(row=7, column=3, sticky=E) sb1_label = Label(self, text=" Amplitude") sb1_label.grid(row=6, column=3, padx=0, sticky=E) self.amplitude_range.set("2") sb1 = Entry(self, width=8, textvariable=self.amplitude_range) sb1.grid(row=7, column=4, sticky=E) sb1_label = Label(self, text=" Loop Range") sb1_label.grid(row=6, column=4, padx=0, sticky=E) self.delta.set("0.1") sb1 = Entry(self, width=8, textvariable=self.delta) sb1.grid(row=7, column=5, sticky=E) sb1_label = Label(self, text=" Loop Delta") sb1_label.grid(row=6, column=5, padx=0, sticky=E) self.noise_sigma.set("4") sb1 = Entry(self, width=3, textvariable=self.noise_sigma) sb1.grid(row=5, column=6, sticky=E) sb1_label = Label(self, text=" Noise Threshold") sb1_label.grid(row=4, column=6, padx=0, sticky=E) sb_coeff_label = Label(self, text="Coefficient ") sb_coeff_label.grid(row=0, column=6, padx=0, sticky=E) self.sb_coeff = Label(self) self.sb_coeff.grid(row=1, column=6, padx=0, sticky=E) # MAIN BUTTONS obtn = Button(self, text="GO!!", command=self.find_C) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=14, column=0, sticky=W, pady=10) def help_f(self): top = Toplevel() top.title("HELP") msg = Message(top, width=500, text="COEFF Calibration Procedure: \n \ Input Start Point and Length of the pulse \n \ Input an initial guess of the pulse amplitude \n \ Use a ROI with at least 1000 samples of baseline \n \ and 1000 samples after pulse end \n \ Adjust loop range and step until a graph error \n \ with a minimum is observed \n \ Refine the search to increase precision") msg.pack() button = Button(top, text="Close", command=top.destroy) button.pack() def find_C(self): draw = False LIMIT_L = self.LIMIT_L.get() #19000 LIMIT_H = self.LIMIT_H.get() #22500 PULSE_R = self.PULSE_R.get() #20142 PULSE_L = self.PULSE_L.get() #1200 pulse_height = self.pulse_height.get() #545 hdf5_file = self.hdf5_file.get() #'2052.h5.z' PMT = self.PMT.get() event = self.EVENT.get() amplitude_range = self.amplitude_range.get() #2 delta = self.delta.get() #0.1 noise_sigma = self.noise_sigma.get() #4 coeff_aux = fc.find_coeff(LIMIT_L, LIMIT_H, PULSE_R, PULSE_L, pulse_height, hdf5_file, PMT, event, amplitude_range, delta, noise_sigma, draw) plt.show() self.sb_coeff.configure(text=str(coeff_aux)) def centerUI(self, w, h): sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
class Main(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.current_image = posts[0] self.posts = posts self.initUI() self.current_booru = None def initUI(self): self.parent.title("Booru") self.pack(fill=Y, expand=0, side=LEFT) myicon = ImageTk.PhotoImage(file="sbooru.ico") self.current_booru_var = StringVar() self.mb = Menubutton(self, textvariable=self.current_booru_var, relief=RAISED, image=myicon, compound=LEFT) self.mb.image = myicon self.mb.pack(side=TOP) self.mb.menu = Menu(self.mb, tearoff=0) self.mb["menu"] = self.mb.menu self.current_booru_var.set("Safebooru") def change_booru(booru): self.current_booru = booru if self.current_booru == 0: self.current_booru_var.set("Danbooru") if self.current_booru == 1: self.current_booru_var.set("Safebooru") self.mb.menu.add_command(label="Danbooru", command=lambda: change_booru(0)) self.mb.menu.add_command(label="Safebooru", command=lambda: change_booru(1)) self.mb.pack() image = Image.open( get_image_from_internet_binary( u"%s%s" % (main_url, self.posts[0][u"preview_file_url"]))) photo = ImageTk.PhotoImage(image) self.label = Label(self, image=photo) self.label.image = photo self.label.pack(fill=Y, expand=0, side=TOP) self.lb = Listbox(self) for i in self.posts: self.lb.insert(END, i["id"]) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.pack(pady=15, fill=Y, expand=0, side=LEFT) self.description = Labelframe(self, text="Description", height=350, width=350) self.description.pack(pady=15, expand=0) #artist self.artist_v = StringVar() self.artist = Label(self.description, textvariable=self.artist_v, justify=LEFT, wraplength=350, anchor=W) self.artist.pack() #md5 self.md5_v = StringVar() self.md5 = Label(self.description, textvariable=self.md5_v, justify=LEFT, wraplength=350, anchor=W) self.md5.pack() #source self.source_v = StringVar() self.source = Label(self.description, textvariable=self.source_v, justify=LEFT, wraplength=350, anchor=W) self.source.pack() #wxh self.wxh_v = StringVar() self.wxh = Label(self.description, textvariable=self.wxh_v, justify=LEFT, wraplength=350, anchor=W) self.wxh.pack() #tags (for now all) self.tags_v = StringVar() self.tags = Label(self.description, textvariable=self.tags_v, justify=LEFT, wraplength=350, anchor=W) self.tags.pack() #uploader self.uploader_v = StringVar() self.uploader = Label(self.description, textvariable=self.uploader_v, justify=LEFT, wraplength=350, anchor=W) self.uploader.pack() idx = (0, 0) try: self.artist_v.set(u"Artist:\t%s" % self.posts[idx[0]][u"tag_string_artist"]) except KeyError: self.artist_v.set(u"Artist:\t") try: self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"]) except KeyError: self.md5_v.set(u"MD5:\t") try: self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"]) except KeyError: self.source_v.set(u"Source:\t") try: self.wxh_v.set(u"Size:\t%sx%s" % (self.posts[idx[0]][u"image_width"], self.posts[idx[0]][u"image_height"])) except KeyError: self.wxh_v.set(u"Size:\t") try: self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"]) except KeyError: self.tags_v.set(u"Tags:\t") try: self.uploader_v.set(u"Uploader:\t%s" % self.posts[idx[0]][u"uploader_name"]) except KeyError: self.uploader_v.set(u"Uploader:\t") self.button_frame = Frame(self.description) self.button_frame.pack(fill=Y, expand=0, side=LEFT) def download_image_current(): def download(): urllib.urlretrieve( "%s%s" % (main_url, self.current_image[u"file_url"]), "%s_%s.%s" % (self.current_image[u"id"], self.current_image[u"md5"], self.current_image[u"file_ext"])) t1 = Thread(target=download, args=()) t1.start() self.download_button = Button(self.button_frame, text="Download", command=download_image_current) self.download_button.pack(side=LEFT) def bigger_preview(): image = Image.open( get_image_from_internet_binary( u"%s%s" % (main_url, self.current_image[u"file_url"]))) photo = ImageTk.PhotoImage(image) self.bigpreview = Toplevel(self) labelu = Label(self.bigpreview, image=photo) labelu.image = photo labelu.pack(fill=Y, expand=0, side=LEFT) self.preview_button = Button(self.button_frame, text="Preview", command=bigger_preview) self.preview_button.pack(side=RIGHT) def onRefresh(): def method(): query_args["page"] = self.current_page.get() self.posts = get_posts("posts.json", query_args) self.lb.delete(0, END) for i in self.posts: self.lb.insert(END, i["id"]) t1 = Thread(target=method, args=()) t1.start() self.refresh = Button(self.button_frame, text="Refresh posts", command=onRefresh) self.refresh.pack(side=LEFT) page_control = Frame(self) page_control.pack(pady=15, side=BOTTOM) self.current_page = IntVar() self.current_page.set(1) def forward_f(): self.current_page.set(self.current_page.get() + 1) onRefresh() forward = Button(page_control, text=">>", command=forward_f) forward.pack(side=RIGHT) def backward_f(): self.current_page.set((self.current_page.get() - 1) if ( self.current_page.get() - 1 > 0) else self.current_page.get()) onRefresh() backward = Button(page_control, text="<<", command=backward_f) backward.pack(side=LEFT) curpaglabl = Label(page_control, textvariable=self.current_page, background="orange") curpaglabl.pack(pady=15, side=BOTTOM) def onSelectFileBrowser(self, val): sender = val.widget idx = sender.curselection() def get_image_and_cover_it(self): with open(sender.get(idx), "r") as fre: image = Image.open(fre.read()) photo = ImageTk.PhotoImage(image) self.label.configure(image=photo) self.label.image = photo t1 = Thread(target=get_image_and_cover_it, args=(self, )) t1.start() def onSelect(self, val): sender = val.widget idx = sender.curselection() self.current_image = self.posts[idx[0]] try: self.artist_v.set(u"Artist:\t%s" % self.posts[idx[0]][u"tag_string_artist"]) except KeyError: self.artist_v.set(u"Artist:\t") try: self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"]) except KeyError: self.md5_v.set(u"MD5:\t") try: self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"]) except KeyError: self.source_v.set(u"Source:\t") try: self.wxh_v.set(u"Size:\t%sx%s" % (self.posts[idx[0]][u"image_width"], self.posts[idx[0]][u"image_height"])) except KeyError: self.wxh_v.set(u"Size:\t") try: self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"]) except KeyError: self.tags_v.set(u"Tags:\t") try: self.uploader_v.set(u"Uploader:\t%s" % self.posts[idx[0]][u"uploader_name"]) except KeyError: self.uploader_v.set(u"Uploader:\t") def get_image_and_cover_it(self): image = Image.open( get_image_from_internet_binary( u"%s%s" % (main_url, self.posts[idx[0]][u"preview_file_url"]))) photo = ImageTk.PhotoImage(image) self.label.configure(image=photo) self.label.image = photo t1 = Thread(target=get_image_and_cover_it, args=(self, )) t1.start()
class Nono_Main(Frame): ''' It is GUI for player to choose nonogram, or to import from text file or picture ''' def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): ''' Loades nonograms from Nonogram base.txt file, fills list of nonograms and creates all widgets within GUI ''' self.parent.title("Nonograms") base_nonograms = import_from_file("Nonogram base.txt") self.all_nonograms = [] menubar = tk.Menu(self.parent) self.parent.config(menu=menubar) self.fl = "" fileMenu = tk.Menu(menubar) fileMenu.add_command(label="Export", command=self.export) fileMenu.add_command(label="Open", command=self.onOpen) fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=fileMenu) self.pack(fill=tk.BOTH, expand=1) nonos = [] for n in range(len(base_nonograms['unique'])): nonos.append('Nonogram ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['unique'] for n in range(len(base_nonograms['nonunique'])): nonos.append('NUS Nonogram ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['nonunique'] for n in range(len(base_nonograms['hard'])): nonos.append('HARD Nonogram ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['hard'] self.lb = tk.Listbox(self) for i in nonos: self.lb.insert(tk.END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=20, y=40) info1 = Label(self, text='Select nonogram:') info1.place(x=30, y=10) info2 = Label(self, text='Or choose a file:') info2.place(x=180, y=10) self.browseButton = tk.Button(self, text='Browse...', command=self.onBrowse) self.browseButton.place(x=200, y=30) self.info3 = Label(self, text="") self.info3.place(x=150, y=60) self.info4 = Label(self, text="Rows:") self.ySize = tk.Entry(self, width=5) def onSelect(self, val): ''' When player selects nonogram from list, new window appears with this particular nonogram. ''' sender = val.widget num = sender.curselection()[0] current_nonogram = self.all_nonograms[num] master = tk.Tk() if 'HARD' not in sender.get(sender.curselection())\ and 'Picture' not in sender.get(sender.curselection()): current_nonogram.solve() current_nonogram.full_solve() app = ShowNono(master, current_nonogram.Rows, current_nonogram.Columns, current_nonogram.nonogram_Matrix, current_nonogram.pair) app.mainloop() else: app = ShowNonoHard(master, current_nonogram.Rows, current_nonogram.Columns) app.mainloop() def onBrowse(self): ''' Opens filedialog window, so player can choose text file or picture to add nonograms. In the second case player is asked to give dimensions of picture he wants to solve. WARNING! Image size ratio cannot be changed! So if original picture has resolution 900x900 and players gives X = 10, Y = 100 picture will be converted to X = 100 and Y = 100, to retain size ratio and to match Y. ''' if self.ySize: self.ySize.destroy() if self.info4: self.info4.destroy() ftypes = [('Text files', '*.txt'), ('Pictures', '*.jpg; *.png; *.bmp')] dlg = filedialog.Open(self, filetypes=ftypes) self.fl = dlg.show() sss = self.fl.split("/") self.info3.configure(text=sss[-1]) if self.fl[-3:] == "txt": self.convert = tk.Button(self, text='Convert', command=self.converty) self.convert.place(x=200, y=160) elif self.fl[-3:] in ['jpg', 'png', 'bmp']: self.ySize = tk.Entry(self, width=5) self.ySize.place(x=210, y=100) self.info4 = Label(self, text="Rows:") self.info4.place(x=150, y=100) self.convert = tk.Button(self, text='Convert', command=self.converty) self.convert.place(x=200, y=160) def converty(self): ''' Imports and adds to list nonograms from file, or converts picture to nonogram and adds it to the list. ''' if self.fl[-3:] == "txt": base_nonograms = import_from_file(self.fl) name = self.fl.split("/")[-1].split(".")[0] nonos = [] for n in range(len(base_nonograms['unique'])): nonos.append('My ' + name + ' ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['unique'] for n in range(len(base_nonograms['nonunique'])): nonos.append('My NUS ' + name + ' ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['nonunique'] for n in range(len(base_nonograms['hard'])): nonos.append('HARD ' + name + ' ' + str(len(self.all_nonograms) + n)) self.all_nonograms += base_nonograms['hard'] for i in nonos: self.lb.insert(tk.END, i) elif self.fl[-3:] in ['jpg', 'png', 'bmp']: name = self.fl.split("/")[-1].split(".")[0] rows, cols = import_picture(self.fl, int(self.ySize.get()), int(self.ySize.get())) ngram = nonogram(rows, cols) self.lb.insert( tk.END, "Picture " + name + ' ' + str(len(self.all_nonograms))) self.all_nonograms.append(ngram) self.ySize.destroy() self.info4.destroy() self.convert.destroy() self.info3.configure(text="") def onOpen(self): self.onBrowse() def onExit(self): self.parent.destroy() def export(self): ''' Saves all nonograms from the list to "Nonogram base.txt" so they will be loaded on next opening. ''' text = [ str(nonogram.Rows) + '\n' + str(nonogram.Columns) for nonogram in self.all_nonograms ] new_text = '\n\n'.join(text) f = open('Nonogram base.txt', 'w') f.write(new_text) f.close
class gui(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.centerUI(w=600,h=250) def initUI(self): self.parent.title("FIND BLR COEFFICIENT VALUE") self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) # self.rowconfigure(0, weight=1) # weight attibute is used to make them growable ###### GUI Control Variables ###### self.LIMIT_L = IntVar() self.LIMIT_H = IntVar() self.PULSE_R = IntVar() self.PULSE_L = IntVar() self.pulse_height = DoubleVar() self.hdf5_file = StringVar() self.PMT = IntVar() self.EVENT = IntVar() self.amplitude_range = DoubleVar() self.delta = DoubleVar() self.noise_sigma = DoubleVar() self.coeff = DoubleVar() #self.DRAW = BooleanVar() search = Image.open("next_logo.jpg") search_temp = search.resize((170, 200), Image.ANTIALIAS) search_aux = ImageTk.PhotoImage(search_temp) label1 = Label(self, image=search_aux) label1.image = search_aux label1.grid(row=0, column=0, columnspan=10, rowspan=10, sticky=E+W+S+N) self.hdf5_file.set("2052.h5.z") e1 = Entry(self, textvariable=self.hdf5_file, width=30) e1.grid(row=1,column=1, sticky=W, columnspan=5, pady=5) e1_label = Label(self, text="HDF5 file") e1_label.grid(row=0,column=1,sticky=W, columnspan=5, pady=5) self.PMT.set("0") sb1 = Spinbox(self, from_=0, to=12, width=3, textvariable=self.PMT) sb1.grid(row=3,column=2, sticky=W) sb1_label = Label(self, text="PMT") sb1_label.grid(row=2,column=2, padx=0, sticky=W) self.EVENT.set("0") sb1 = Spinbox(self, from_=0, to=1000, width=5, textvariable=self.EVENT) sb1.grid(row=3,column=3, sticky=W) sb1_label = Label(self, text="EVENT") sb1_label.grid(row=2,column=3, padx=0, sticky=W) self.LIMIT_L.set("19000") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_L) sb1.grid(row=5,column=2, sticky=W) sb1_label = Label(self, text="ROI Start ") sb1_label.grid(row=4,column=2, padx=0, sticky=W) self.LIMIT_H.set("22500") sb1 = Spinbox(self, from_=0, to=100000, width=5, textvariable=self.LIMIT_H) sb1.grid(row=5,column=3, sticky=W) sb1_label = Label(self, text="ROI End ") sb1_label.grid(row=4,column=3, padx=0, sticky=W) self.PULSE_R.set("20142") sb1 = Spinbox(self, from_=0, to=100000, width=8, textvariable=self.PULSE_R) sb1.grid(row=5,column=4, sticky=E) sb1_label = Label(self, text=" Pulse Rise") sb1_label.grid(row=4,column=4, padx=0, sticky=E) self.PULSE_L.set("1200") sb1 = Spinbox(self, from_=0, to=5000, width=8, textvariable=self.PULSE_L) sb1.grid(row=5,column=5, sticky=E) sb1_label = Label(self, text=" Pulse Length") sb1_label.grid(row=4,column=5, padx=0, sticky=E) sb1_label = Label(self, text=" ") sb1_label.grid(row=2,column=7, padx=0, sticky=W) sb1_label = Label(self, text=" ") sb1_label.grid(row=6,column=7, padx=0, sticky=W) self.pulse_height.set("545.5") sb1 = Entry(self, width=8, textvariable=self.pulse_height) sb1.grid(row=7,column=3, sticky=E) sb1_label = Label(self, text=" Amplitude") sb1_label.grid(row=6,column=3, padx=0, sticky=E) self.amplitude_range.set("2") sb1 = Entry(self, width=8, textvariable=self.amplitude_range) sb1.grid(row=7,column=4, sticky=E) sb1_label = Label(self, text=" Loop Range") sb1_label.grid(row=6,column=4, padx=0, sticky=E) self.delta.set("0.1") sb1 = Entry(self, width=8, textvariable=self.delta) sb1.grid(row=7,column=5, sticky=E) sb1_label = Label(self, text=" Loop Delta") sb1_label.grid(row=6,column=5, padx=0, sticky=E) self.noise_sigma.set("4") sb1 = Entry(self, width=3, textvariable=self.noise_sigma) sb1.grid(row=5,column=6, sticky=E) sb1_label = Label(self, text=" Noise Threshold") sb1_label.grid(row=4,column=6, padx=0, sticky=E) sb_coeff_label = Label(self, text= "Coefficient ") sb_coeff_label.grid(row=0,column=6, padx=0, sticky=E) self.sb_coeff = Label(self) self.sb_coeff.grid(row=1,column=6, padx=0, sticky=E) # MAIN BUTTONS obtn = Button(self, text="GO!!", command=self.find_C) obtn.grid(row=14, column=4, sticky=E, pady=10) cbtn = Button(self, text="Quit", command=self.quit) cbtn.grid(row=14, column=5, sticky=E, pady=10) hbtn = Button(self, text="Help", command=self.help_f) hbtn.grid(row=14, column=0, sticky=W, pady=10) def help_f(self): top = Toplevel() top.title("HELP") msg = Message(top, width= 500, text="COEFF Calibration Procedure: \n \ Input Start Point and Length of the pulse \n \ Input an initial guess of the pulse amplitude \n \ Use a ROI with at least 1000 samples of baseline \n \ and 1000 samples after pulse end \n \ Adjust loop range and step until a graph error \n \ with a minimum is observed \n \ Refine the search to increase precision") msg.pack() button = Button(top, text="Close", command=top.destroy) button.pack() def find_C(self): draw = False LIMIT_L = self.LIMIT_L.get() #19000 LIMIT_H = self.LIMIT_H.get() #22500 PULSE_R = self.PULSE_R.get() #20142 PULSE_L = self.PULSE_L.get() #1200 pulse_height = self.pulse_height.get() #545 hdf5_file = self.hdf5_file.get() #'2052.h5.z' PMT = self.PMT.get() event = self.EVENT.get() amplitude_range = self.amplitude_range.get() #2 delta = self.delta.get() #0.1 noise_sigma = self.noise_sigma.get() #4 coeff_aux = fc.find_coeff(LIMIT_L, LIMIT_H, PULSE_R, PULSE_L, pulse_height, hdf5_file, PMT, event, amplitude_range, delta, noise_sigma, draw) plt.show() self.sb_coeff.configure(text=str(coeff_aux)) def centerUI(self,w,h): sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw-w)/2 y = (sh-h)/2 self.parent.geometry('%dx%d+%d+%d' % (w,h,x,y))
class EngineGui(): def __init__(self, communicationProtocal): self.communicationProtocal = communicationProtocal def StartGui(self): self.tkRoot = Tk(baseName="") self.tkRoot.geometry("350x300+0+0") self.tkRoot.title("Engine SAPI GUI") self.GUIVisible = True frame = Frame(self.tkRoot) frame.style = Style() frame.style.theme_use("alt") frame.pack(fill=BOTH, expand=1) frame.columnconfigure(1, weight=1) frame.columnconfigure(7, pad=7) frame.rowconfigure(13, weight=1) frame.rowconfigure(13, pad=7) Label(frame, text="Start:").grid(row = 0, column=0) self.labelStart = Label(frame, text="0") self.labelStart.grid(row = 1, column=0) Label(frame, text="Length:").grid(row = 0, column=1) self.labelLength = Label(frame, text="0") self.labelLength.grid(row = 1, column=1) Label(frame, text="Total:").grid(row = 0, column=2) self.labelTotal = Label(frame, text="0") self.labelTotal.grid(row = 1, column=2) self.labelSentenceLeft = Label(frame, text="...") self.labelSentenceLeft.grid(row = 2, column=0, sticky=E) self.labelSentenceSpoken = Label(frame, text="...", foreground="red") self.labelSentenceSpoken.grid(row = 2, column=1) self.labelSentenceRight = Label(frame, text="...") self.labelSentenceRight.grid(row = 2, column=2, sticky=W, columnspan=2) scrollbar = Scrollbar(frame, orient=VERTICAL) self.labelQueueToSpeak = Label(frame, text="Queue to speak:").grid(row = 3, column=0, pady=4, padx=5, sticky=W) self.listboxQueueToSpeak = Listbox(frame, width=50, height=3, yscrollcommand=scrollbar.set) scrollbar.config(command=self.listboxQueueToSpeak.yview) self.listboxQueueToSpeak.grid( sticky=N+S+E+W, row = 4, column = 0, columnspan = 2 ,rowspan = 3, padx=3) scrollbar.grid(sticky=N+S+W, row = 4, column = 2, rowspan = 3) self.buttonPauze = Button(frame, text="Pauze", command=self.communicationProtocal.handlePauze) self.buttonPauze.grid(row = 4, column=3) self.buttonStop = Button(frame, text="Stop", command=self.communicationProtocal.restartProcess) self.buttonStop.grid(row = 5, column=3) self.buttonResume = Button(frame, text="Resume", command=self.communicationProtocal.handleResume) self.buttonResume.grid(row = 6, column=3) Label(frame, text="Text to say:").grid(row = 7, column=0, padx=3, sticky=W) self.stringVarTextToSay = StringVar() self.entryTextToSay = Entry(frame, textvariable=self.stringVarTextToSay, width=500) self.entryTextToSay.grid(row=8, column=0, columnspan=3, padx=3, sticky=W) self.stringVarTextToSay.set("Hello SAPI Speak Engine") self.entryTextToSay.bind('<Return>', self.CallBackReturnSay) self.buttonSay = Button(frame, text="Say", command=self.CallBackButtonSay) self.buttonSay.grid(row = 8, column=3) Label(frame, text="Recover action:").grid(row = 9, column=0, padx=3, sticky=W) self.recoverActionLabelText = "None" self.labelRecoverAction = Label(frame, text=self.recoverActionLabelText, foreground="blue") self.labelRecoverAction.grid(row = 10, column=0) Label(frame, text="Voice speed:").grid(row = 9, column=1, sticky=W) self.buttonSpeedDown = Button(frame, text="Speed down", command=self.communicationProtocal.handleSpeedDown) self.buttonSpeedDown.grid(row = 10, column=1, padx=3, sticky=E) self.speedValue = 0 self.intVarSpeed = IntVar() vcmd = (self.tkRoot.register(self.OnValidateEntrySpeakSpeed), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.entrySpeakSpeed = Entry(frame, textvariable=self.intVarSpeed, validate="key", validatecommand=vcmd, width=5) self.entrySpeakSpeed.grid(row=10,column=2) self.entrySpeakSpeed.bind('<Return>', self.CallBackSetSpeed) self.buttonSpeedUp = Button(frame, text="Speed up", command=self.communicationProtocal.handleSpeedUp) self.buttonSpeedUp.grid(row = 10, column=3) Label(frame, text="voice:").grid(row = 11, column=0, padx=3, sticky=W) self.buttonPrevVoice = Button(frame, text="Prev voice", command=self.communicationProtocal.handlePrevVoice) self.buttonPrevVoice.grid(row = 12, column=0, padx=3, sticky=W) self.buttonNextVoice = Button(frame, text="Next voice", command=self.communicationProtocal.handleNextVoice) self.buttonNextVoice.grid(row = 12, column=3) self.currentVoice = StringVar(self.tkRoot) self.currentVoice.set(self.communicationProtocal.CurrentVoiceName) engine = pyttsx.init() voices = engine.getProperty("voices") voiceNames = list() for x in xrange(0, len(voices)): voiceNames.append(voices[x].name) self.optionMenuVoices = OptionMenu(frame, self.currentVoice, *tuple(voiceNames), command=self.CallBackOptionMenuVoices) self.optionMenuVoices.config(width=500) self.optionMenuVoices.grid(sticky=W, row = 12, column = 1) #hide if close button is clicked self.tkRoot.protocol("WM_DELETE_WINDOW", self.HideGui) self.tkRoot.after(1000/32, self.Update) self.tkRoot.mainloop() def Update(self): wordLocation = self.communicationProtocal.OnWordStartLocation wordLength = self.communicationProtocal.OnWordLength wordTotal = self.communicationProtocal.OnWordTotal if wordLocation: self.labelStart.configure(text=wordLocation) else: self.labelStart.configure(text="0") self.labelLength.configure(text=wordLength) if wordLength != 0 and wordTotal == 0: self.labelTotal.configure(text="Introduce") else: self.labelTotal.configure(text=wordTotal) if len(self.communicationProtocal.SpeakQueue) != 0: if (wordLocation < 25): self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[0:wordLocation]) else: self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation-25:wordLocation]) self.labelSentenceSpoken.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation:wordLocation+wordLength]) if (wordTotal - wordLocation - wordLength < 25): self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordTotal]) else: self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordLocation+wordLength+25]) else: self.labelSentenceLeft.configure(text="...") self.labelSentenceSpoken.configure(text="...") self.labelSentenceRight.configure(text="...") if (self.communicationProtocal.SpeakQueue != None and self.listboxQueueToSpeak.size() != len(self.communicationProtocal.SpeakQueue)): self.listboxQueueToSpeak.delete(0,self.listboxQueueToSpeak.size()) for x in xrange(0,len(self.communicationProtocal.SpeakQueue)): self.listboxQueueToSpeak.insert(x, str(x)+": "+self.communicationProtocal.SpeakQueue[x]) if (self.currentVoice.get() != self.communicationProtocal.CurrentVoiceName): self.currentVoice.set(self.communicationProtocal.CurrentVoiceName) if self.speedValue != self.communicationProtocal.CurrentRate: self.intVarSpeed.set(self.communicationProtocal.CurrentRate) self.speedValue = self.communicationProtocal.CurrentRate if self.recoverActionLabelText != self.communicationProtocal.recoveryTask: self.recoverActionLabelText = self.communicationProtocal.recoveryTask self.labelRecoverAction.configure(text=self.recoverActionLabelText) if self.GUIVisible != self.communicationProtocal.GUIVisible: # self.GUIVisible ? self.HideGui : self.ShowGui self.HideGui() if self.GUIVisible else self.ShowGui() self.tkRoot.after(1000/32,self.Update) def OnValidateEntrySpeakSpeed(self, d, i, P, s, S, v, V, W): try : int(S) return True except ValueError: return False def CallBackSetSpeed(self): self.communicationProtocal.handleSetSpeed(self.intVarSpeed.get()) def CallBackReturnSay(self, event): self.CallBackButtonSay() def CallBackButtonSay(self): self.communicationProtocal.handleSay(self.stringVarTextToSay.get()) def CallBackOptionMenuVoices(self, selectedItem): self.communicationProtocal.handleSetVoice(selectedItem) def Close(self): self.tkRoot.quit() def HideGui(self): self.GUIVisible = False self.communicationProtocal.GUIVisible = False self.tkRoot.withdraw() def ShowGui(self): self.GUIVisible = True self.communicationProtocal.GUIVisible = True self.tkRoot.deiconify()
class SearchVisualizerApp(Frame): def __init__(self, parent, speed=100, fname='map.txt', algo=uniform_cost_search, run=False, jump=False): Frame.__init__(self, parent) self.parent = parent self.path = None self.grid_view = None self.speed = speed self.algo = algo self.run = run self.jump = jump self.parent.title("Search Visualizer") self.style = Style().configure("TFrame", background="#333") self.tile_size = tile_size = 16 self.grid_view = Grid(self, self.tile_size) self.grid_view.pack(fill=BOTH, expand=True) self.grid_view.canvas.bind('<Button-1>', self._on_mouse_click) self.g = None self.h = None self.last_hover = None self.step_num = 0 self.load_map(fname) self.pack(fill=BOTH, expand=True) self.stepCounter = Label(self, text="Count: 000") self.stepCounter.pack(side=LEFT, padx=5, pady=5) self.algoLabel = Label(self, text="g: h: f:") self.algoLabel.pack(side=LEFT, padx=5, pady=5) # TODO Check boxes to select heuristic # TODO Button to select algorithm and restart quitButton = Button(self, text="Quit", command=self.quit) quitButton.pack(side=RIGHT, padx=5, pady=5) stepButton = Button(self, text="Step", command=self._step_button) stepButton.pack(side=RIGHT, padx=5, pady=5) pauseButton = Button(self, text="Start/Stop", command=self._pause_toggle) pauseButton.pack(side=RIGHT) jumpButton = Button(self, text="End", command=self._jump_button) jumpButton.pack(side=RIGHT, padx=5, pady=5) self.bind("<space>", self._pause_toggle) self.bind("<q>", self._quit) self.centerWindow() def _quit(self, event): self.quit() def _jump_button(self): self.run = False self.jump = True def _on_mouse_click(self, event): x, y = self.grid_view.canvas.canvasx( event.x), self.grid_view.canvas.canvasy(event.y) c, r = np.floor(x / self.tile_size), np.floor(y / self.tile_size) if (c, r) is self.last_hover: return self.last_hover = (c, r) tile_size = self.grid_view.tile_size grid_vm = self.grid_view.grid_vm (C, R) = grid_vm.shape if c >= C or r >= R: return s = grid_vm[c, r] if self.g and self.h: h = self.h(s) g = float("inf") if s in self.g: g = self.g[s] f = g + h self.algoLabel.configure( text="g: {0:5.2f} | h: {1:5.2f} | f: {2:5.2f}".format(g, h, f)) def _pause_toggle(self, event=None): self.run = not self.run if self.run: self.loop() def _step_button(self): self.run = False self.step() # Change the search generator to use def set_search(self, search): pass def load_map(self, fname): (grid, start, goal) = input_file(fname) grid_vm = np.array([TileVM(v) for v in grid.flatten()]).reshape(grid.shape) grid_vm[start].is_start = True grid_vm[goal].is_goal = True self.search = self.algo(grid_vm, grid_vm[start], grid_vm[goal]) self.grid_view.set_vm(grid_vm) # Update the Grid def loop(self): if self.run: self.step() self.parent.after(self.speed, self.loop) def step(self): try: (f, g, h, parent, curr) = self.search.next() curr.visited = True if self.jump is True: try: while 1: (f, g, h, parent, curr) = self.search.next() curr.visited = True self.step_num = self.step_num + 1 except StopIteration: self.run = False for s in g: self.grid_view.drawTile(s) self.g = g self.h = h # TODO Change fringe to binary heap show nodes that are in the fringe if self.path: for s in self.path: s.in_path = False self.grid_view.drawTile(s) self.path = gen_path(parent, curr) self.step_num = self.step_num + 1 self.stepCounter.configure(text="Count: " + str(self.step_num)) for s in self.path: s.in_path = True self.grid_view.drawTile(s) except StopIteration: self.run = False print("End of search") def centerWindow(self): # TODO: Modify this to instead show second window to specific position grid = self.grid_view.grid_vm tile_size = self.grid_view.tile_size (x, y) = grid.shape w = x * tile_size + 50 h = y * tile_size + 150 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (min(sw, w), min(sh, h), x, y))
class Reader(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Graphs") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, weight=1) self.columnconfigure(6, pad=7) self.rowconfigure(3, weight=1) self.rowconfigure(5, pad=7) menu = Menu(self.parent) self.parent.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Load data", command=self.load_data) # lable to show current file and chanel self.file_lbl = Label(self, text="") self.file_lbl.grid(row=0, column=3, pady=4, padx=5) # list box fro data files self.file_list = ScrolledList(self, lambda x: self.load_hunt_data(x)) self.file_list.grid(row=1, column=0, columnspan=3, rowspan=4, padx=5, sticky=E + W + S + N) # chanel graph viewer self.graph_viewer = TkinterGraph(self) self.graph_viewer.grid(row=1, column=3, columnspan=2, rowspan=4, padx=5, sticky=E + W + S + N) btn1 = Button(self, text="Left", command=lambda: self.plot_left()) btn1.grid(row=1, column=6) btn2 = Button(self, text="Right", command=lambda: self.plot_right()) btn2.grid(row=2, column=6, pady=4) # frames for the classifier for the two chanels self.frame_left = Frame(self, borderwidth=1) self.frame_right = Frame(self, borderwidth=1) self.frame_left.grid(row=5, column=3, columnspan=2, rowspan=1) btn4 = Button(self, text="SAVE", command=lambda: self.save_graph()) btn4.grid(row=5, column=6) # note manual addition of labels so that the lable will be to the right of tha radio button self.classify_left = StringVar() Label(self.frame_left, text="Left :").pack(side=LEFT) Label(self.frame_left, text="Type A").pack(side=LEFT) rb1 = Radiobutton(self.frame_left, variable=self.classify_left, value="TypeA") rb1.pack(side=LEFT) Label(self.frame_left, text="Type B").pack(side=LEFT) rb1 = Radiobutton(self.frame_left, variable=self.classify_left, value="TypeB") rb1.pack(side=LEFT) Label(self.frame_left, text="Type C").pack(side=LEFT) rb1 = Radiobutton(self.frame_left, variable=self.classify_left, value="TypeC") rb1.pack(side=LEFT) Label(self.frame_left, text="Type D").pack(side=LEFT) rb1 = Radiobutton(self.frame_left, variable=self.classify_left, value="TypeD") rb1.pack(side=LEFT) self.classify_right = StringVar() Label(self.frame_right, text="Right :").pack(side=LEFT) Label(self.frame_right, text="Type A").pack(side=LEFT) rb1 = Radiobutton(self.frame_right, variable=self.classify_right, value="TypeA") rb1.pack(side=LEFT) Label(self.frame_right, text="Type B").pack(side=LEFT) rb1 = Radiobutton(self.frame_right, variable=self.classify_right, value="TypeB") rb1.pack(side=LEFT) Label(self.frame_right, text="Type C").pack(side=LEFT) rb1 = Radiobutton(self.frame_right, variable=self.classify_right, value="TypeC") rb1.pack(side=LEFT) Label(self.frame_right, text="Type D").pack(side=LEFT) rb1 = Radiobutton(self.frame_right, variable=self.classify_right, value="TypeD") rb1.pack(side=LEFT) def load_data(self): # calls the file dialog box name = askopenfilename() (d_path, d_name) = split(name) # just want to extract the path of the file self.mypath = d_path # get 'filtered' files from that path files = self.get_files() # display in the list box self.file_list.load_data(files) def load_hunt_data(self, selection): (self.indx, self.filename) = selection d_file = join(self.mypath, self.filename) l_array = [] r_array = [] with open(d_file) as f: for line in f: data = line.split(',') if data[5] != '': r_array.append(data[5]) # RL_PVR l_array.append(data[6]) # LL_PVR self.rawy_l = numpy.array(l_array[1:]) # form 1 romove headder self.rawy_r = numpy.array(r_array[1:]) self.rawx = [i for i in range(len(self.rawy_l))] # reset the classification buttons self.classify_left.set("TypeA") self.classify_right.set("TypeA") self.plot_left() def plot_left(self): # choose th correct fram of radio buttons self.frame_right.grid_forget() self.frame_left.grid(row=5, column=3, columnspan=2, rowspan=1) # change display name self.file_lbl.configure(text=self.filename + " : Left") self.graph_viewer.change_data(self.rawx, self.rawy_l) def plot_right(self): self.frame_left.grid_forget() self.frame_right.grid(row=5, column=3, columnspan=2, rowspan=1) self.file_lbl.configure(text=self.filename + " : Right") self.graph_viewer.change_data(self.rawx, self.rawy_r) def save_graph(self): self.file_list.remove_item(self.indx) d_file = join(self.mypath, self.filename) # add a done prefix to the file name n_file = join(self.mypath, "done-" + self.filename) rename(d_file, n_file) # get the front of the filename fparts = self.filename.split('.') # save data wit the same name but with the chanel prefix and a dat postfix l_file = join(self.mypath, self.classify_left.get() + '-Left-' + fparts[0] + '.dat') # open file to write f = open(l_file, 'w') for v in self.rawy_l: f.write(v + '\n') f.close() r_file = join( self.mypath, self.classify_right.get() + '-Right-' + fparts[0] + '.dat') # open file to write f = open(r_file, 'w') for v in self.rawy_r: f.write(v + '\n') f.close() def get_files(self): files = [] for filename in listdir(self.mypath): # just get the files # note that it has to have the compleate path and name if isfile(join(self.mypath, filename)): # split the file name in to parts files.append(filename) #parts = filename.split('.') #print parts[-1] return files