def __bookmarks(self, master): panel = Frame(master) panel.grid_rowconfigure(0, weight=1) bookmarks = Frame(panel) bookmarks.grid_columnconfigure(0, weight=1) bookmarks.grid_rowconfigure(0, weight=1) li = Listbox(bookmarks, width=40) li.grid(column=0, row=0, sticky=(N, E, S, W)) self.bookmarks_list = li sb = Scrollbar(bookmarks, orient=VERTICAL, command=li.yview) sb.grid(column=1, row=0, sticky=(N, S)) li.config(yscrollcommand=sb.set) def _lbox_selected(*args): selected_idx = int(li.curselection()[0]) self.render_start.set(self.bookmarks_values[selected_idx]) self.canvas.xview_moveto(0) if not self.render_auto.get(): self.update() li.bind('<Double-Button-1>', _lbox_selected) bookmarks.grid(column=0, row=0, sticky=(N, E, S, W)) buttons = Frame(panel) Button(buttons, image=self.img_start, command=self.start_event).pack(side="left") Button(buttons, image=self.img_prev, command=self.prev_event).pack(side="left") Button(buttons, image=self.img_end, command=self.end_event).pack(side="right") Button(buttons, image=self.img_next, command=self.next_event).pack(side="right") buttons.grid(column=0, row=1, sticky=(E, W)) return panel
class ScrolledList(object): # TODO add columns to the Scrolled list: # http://stackoverflow.com/questions/5286093/display-listbox-with-columns-using-tkinter def __init__(self, parent_frame): self._vsbar = Scrollbar(parent_frame) self._hsbar = Scrollbar(parent_frame, orient='horizontal') self._list = Listbox(parent_frame, relief=SUNKEN, font=('courier', 12)) self._vsbar.config(command=self._list.yview, relief=SUNKEN) self._hsbar.config(command=self._list.xview, relief=SUNKEN) self._list.config(yscrollcommand=self._vsbar.set, relief=SUNKEN) self._list.config(xscrollcommand=self._hsbar.set) self._vsbar.pack(side=RIGHT, fill=Y) self._hsbar.pack(side=BOTTOM, fill=X) self._list.pack(side=LEFT, expand=YES, fill=BOTH) #self._list.bind('<Double-1>', self.handlelist) self._list_pos = 0 def clear(self): self._list.delete(0, END) self._list_pos = 0 def append_list_entry(self, entry_str, fg=None): pos = self._list_pos self._list_pos += 1 self._list.insert(END, entry_str) if fg: self._list.itemconfig(pos, fg=fg) return pos def highlight_entry(self, entry_index, bg): self._list.itemconfig(index=entry_index, bg=bg)
class ScrolledList(Frame): def __init__(self, master, d_list, a_function): Frame.__init__(self, master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': self.listbox.insert(idx, item) idx += 1 # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index, label))
class ScrolledList(Frame): ''' a customizable scrolled listbox compoent ''' def makeWidgets(self, width): scrbar_width = 30 scrbar = Scrollbar(self, width=scrbar_width) self.list = Listbox(self, relief=SUNKEN, width=width-30) scrbar.config(command=self.list.yview) self.list.config(yscrollcommand=scrbar.set) scrbar.pack(side=RIGHT, fill=Y) self.list.pack(side=LEFT, expand=YES, fill=BOTH) def __init__(self, parent, width): ''' Constructor ''' Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets(width) def log_line(self, msg): self.list.insert(END, msg) # if self.list.size(): # self.list.insert(1, msg) # else: # self.list.insert(END, msg) #
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)
def setPixelList(self): if "pixelListBox" in self.widgetDict.keys(): pixelListBox = self.widgetDict["pixelListBox"] pixelListBox.delete(0, "end") self.widgetDict["kernelListbox"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) else: pixelListbox = Listbox(self) self.widgetDict["pixelListbox"] = pixelListbox scrollbar = Scrollbar(pixelListbox, orient="vertical") pixelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=pixelListbox.yview) self.widgetDict["pixelsLabel"].config(text="Pixels: %s" % len( self.RepLine.getKernel(self.activeCob, self.activeKernel).keys())) pixelListbox.grid(row=3, column=2, rowspan=3, sticky="nsew") pixelListbox.columnconfigure(0, weight=1) pixelListbox.bind("<<ListboxSelect>>", self.updateActivePixel) scrollbar.grid(column=2, sticky="e") cobNumber = self.activeCob[:self.activeCob.index("_")] kernelNumber = self.activeKernel[self.activeKernel.index(" ") + 1:] kernel = self.RepLine.getKernel(int(cobNumber), int(kernelNumber)) for pixelNumber in xrange(len(kernel.keys())): pixelListbox.insert(pixelNumber, "Pixel: %s" % pixelNumber)
class LBChoice(object): '''This is a listbox for returning projects to be unarchived.''' def __init__(self, list_=None, master=None, title=None): '''Must have master, title is optional, li is too.''' self.master = master if self.master is not None: self.top = Toplevel(self.master) else: return self.v = None if list_ is None or not isinstance(list_, list): self.list = [] else: self.list = list_[:] self.top.transient(self.master) self.top.grab_set() self.top.bind("<Return>", self._choose) self.top.bind("<Escape>", self._cancel) if title: self.top.title(title) lf = Frame(self.top) #Sets up the list. lf.pack(side=TOP) scroll_bar = Scrollbar(lf) scroll_bar.pack(side=RIGHT, fill=Y) self.lb = Listbox(lf, selectmode=SINGLE) self.lb.pack(side=LEFT, fill=Y) scroll_bar.config(command=self.lb.yview) self.lb.config(yscrollcommand=scroll_bar.set) self.list.sort() for item in self.list: self.lb.insert(END, item) #Inserts items into the list. bf = Frame(self.top) bf.pack(side=BOTTOM) Button(bf, text="Select", command=self._choose).pack(side=LEFT) Button(bf, text="New", command=self._new).pack(side=LEFT) Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT) def _choose(self, event=None): try: first = self.lb.curselection()[0] self.v = self.list[int(first)] except IndexError: self.v = None self.top.destroy() def _new(self, event=None): self.v = "NEW" self.top.destroy() def _cancel(self, event=None): self.top.destroy() def return_value(self): self.master.wait_window(self.top) return self.v
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [self._listbox.get(i) for i in self._listbox.curselection()] return selected_values
class SelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent) for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _validate_value(self): return bool(self._listbox.curselection()) def _get_value(self): return self._listbox.get(self._listbox.curselection())
class MultipleSelectionDialog(_TkDialog): def __init__(self, message, values): _TkDialog.__init__(self, message, values) def _create_selector(self, parent, values): self._listbox = Listbox(parent, selectmode='multiple') for item in values: self._listbox.insert(END, item) self._listbox.config(width=0) return self._listbox def _get_value(self): selected_values = [ self._listbox.get(i) for i in self._listbox.curselection() ] return selected_values
def printAnts(self): frameAnts = Frame(self.FrameInfo) Text_A = Label(frameAnts, text="Fourmie :") s1 = Scrollbar(frameAnts) l1 = Listbox(frameAnts) id_ants = self.checkAnts() for i in id_ants: l1.insert(i, str(i)) s1.config(command = l1.yview) l1.config(yscrollcommand = s1.set) l1.bind('<ButtonRelease-1>',self.choiceAnt) self.listbox = l1 Text_A.pack(side = TOP) l1.pack(side = LEFT) s1.pack(side = RIGHT) frameAnts.pack() self.printInfoAnt(id_ants[0]) self.frameAnts = frameAnts
def printAnts(self): frameAnts = Frame(self.FrameInfo) Text_A = Label(frameAnts, text="Fourmie :") s1 = Scrollbar(frameAnts) l1 = Listbox(frameAnts) id_ants = self.checkAnts() for i in id_ants: l1.insert(i, str(i)) s1.config(command=l1.yview) l1.config(yscrollcommand=s1.set) l1.bind('<ButtonRelease-1>', self.choiceAnt) self.listbox = l1 Text_A.pack(side=TOP) l1.pack(side=LEFT) s1.pack(side=RIGHT) frameAnts.pack() self.printInfoAnt(id_ants[0]) self.frameAnts = frameAnts
class ScrolledList(Frame): def __init__(self, master,a_function): Frame.__init__(self,master) scrl_bar = Scrollbar(self) self.listbox = Listbox(self) scrl_bar.config(command=self.listbox.yview) scrl_bar.pack(side=RIGHT, fill=Y) self.listbox.config(yscrollcommand=scrl_bar.set) self.listbox.pack(side=LEFT, expand=YES, fill=BOTH) # link double click to the processList self.listbox.bind('<Double-1>', self.processList) # attach a function passed form the master # not this si done as passd function so it could be anything self.passed_function = a_function # get the index of the double clicked itenm and pass the item to # the passed function def processList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.passed_function((index,label)) def load_data(self,d_list): #load the listbox idx = 0 for item in d_list: fparts = item.split('.') # DEBUG print fparts if fparts[-1] == 'csv': # only display thoes files that have not been processed if not(item.startswith("done-")): self.listbox.insert(idx, item) idx += 1 def remove_item(self,idx): self.listbox.delete(idx)
def setKernelList(self): self.kernelList = [] for i in xrange(len(self.RepLine.cobs[self.activeCob])): self.kernelList.append("Kernel: " + str(i + 1)) if "kernelListbox" in self.widgetDict.keys(): kernelListbox = self.widgetDict["kernelListbox"] kernelListbox.delete(0, "end") self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) else: kernelListbox = Listbox(self) self.widgetDict["kernelListbox"] = kernelListbox scrollbar = Scrollbar(kernelListbox, orient="vertical") kernelListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=kernelListbox.yview) self.widgetDict["kernelsLabel"].config(text="Kernels: %s" % len(self.kernelList)) kernelListbox.grid(row=3, column=1, rowspan=3, sticky="nsew") kernelListbox.columnconfigure(0, weight=1) kernelListbox.bind("<<ListboxSelect>>", self.updateActiveKernel) scrollbar.grid(column=1, sticky="e") for kernel in self.kernelList: kernelListbox.insert(self.kernelList.index(kernel), kernel)
def setCobList(self): self.cobList = [] for cob in xrange(len(self.RepLine.cobs.keys())): self.cobList.append( str(cob + 1) + "_" + self.RepLine.accessionName) if "cobListbox" in self.widgetDict.keys(): cobListbox = self.widgetDict["cobListbox"] cobListbox.delete(0, "end") self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) else: cobListbox = Listbox(self) self.widgetDict["cobListbox"] = cobListbox scrollbar = Scrollbar(cobListbox, orient="vertical") cobListbox.config(yscrollcommand=scrollbar.set) scrollbar.config(command=cobListbox.yview) self.widgetDict["cobsLabel"].config(text="Cobs: %s" % len(self.cobList)) cobListbox.grid(row=3, column=0, rowspan=3, sticky="nsew") cobListbox.columnconfigure(0, weight=1) cobListbox.bind("<<ListboxSelect>>", self.updateActiveCob) scrollbar.grid(column=0, sticky="e") for cob in self.cobList: cobListbox.insert(self.cobList.index(cob), cob)
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 DrtGlueDemo(object): def __init__(self, examples): # Set up the main window. self._top = Tk() self._top.title('DRT Glue Demo') # Set up key bindings. self._init_bindings() # Initialize the fonts.self._error = None self._init_fonts(self._top) self._examples = examples self._readingCache = [None for example in examples] # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Set the data to None self._curExample = -1 self._readings = [] self._drs = None self._drsWidget = None self._error = None self._init_glue() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_exampleListbox(self._top) self._init_readingListbox(self._top) self._init_canvas(self._top) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_glue(self): tagger = RegexpTagger( [('^(David|Mary|John)$', 'NNP'), ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'), ('^(go|order|vanish|find|approach)$', 'VB'), ('^(a)$', 'ex_quant'), ('^(every)$', 'univ_quant'), ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'), ('^(big|gray|former)$', 'JJ'), ('^(him|himself)$', 'PRP') ]) depparser = MaltParser(tagger=tagger) self._glue = DrtGlue(depparser=depparser, remove_duplicates=False) def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = Font(family='helvetica', weight='bold', size=self._size.get()) self._font = Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = Font(family='helvetica', weight='bold', size=big) def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill='both', side='left', padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text='Examples') self._exampleList_label.pack() self._exampleList = Listbox(self._exampleFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._exampleList.pack(side='right', fill='both', expand=1) for example in self._examples: self._exampleList.insert('end', (' %s' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient='vertical') self._exampleList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side='left', fill='y') # If they select a example, apply it. self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select) def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill='both', side='left', padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text='Readings') self._readingList_label.pack() self._readingList = Listbox(self._readingFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._readingList.pack(side='right', fill='both', expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient='vertical') self._readingList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side='right', fill='y') self._populate_readingListbox() def _populate_readingListbox(self): # Populate the listbox with integers self._readingList.delete(0, 'end') for i in range(len(self._readings)): self._readingList.insert('end', (' %s' % (i+1))) self._readingList.config(height=min(len(self._readings), 25), width=5) # If they select a example, apply it. self._readingList.bind('<<ListboxSelect>>', self._readingList_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('n', self.next) self._top.bind('<space>', self.next) self._top.bind('p', self.prev) self._top.bind('<BackSpace>', self.prev) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button(buttonframe, text='Prev', background='#90c0d0', foreground='black', command=self.prev,).pack(side='left') Button(buttonframe, text='Next', background='#90c0d0', foreground='black', command=self.next,).pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2) self._redraw() def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='q') menubar.add_cascade(label='File', underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label='Next', underline=0, command=self.next, accelerator='n, Space') actionmenu.add_command(label='Previous', underline=0, command=self.prev, accelerator='p, Backspace') menubar.add_cascade(label='Action', underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton(label='Remove Duplicates', underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator='r') menubar.add_cascade(label='Options', underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old DRS, widgets, etc. if self._drsWidget is not None: self._drsWidget.clear() if self._drs: self._drsWidget = DrsWidget( self._canvas, self._drs ) self._drsWidget.draw() if self._error: self._drsWidget = DrsWidget( self._canvas, self._error ) self._drsWidget.draw() ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def prev(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or before) the first item if index <= 0: self._select_previous_example() else: self._readingList_store_selection(index-1) else: #select its first reading self._readingList_store_selection(readingListSize-1) else: self._select_previous_example() def _select_previous_example(self): #if the current example is not the first example if self._curExample > 0: self._exampleList_store_selection(self._curExample-1) else: #go to the last example self._exampleList_store_selection(len(self._examples)-1) def next(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # if there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or past) the last item if index >= (readingListSize-1): self._select_next_example() else: self._readingList_store_selection(index+1) else: #select its first reading self._readingList_store_selection(0) else: self._select_next_example() def _select_next_example(self): #if the current example is not the last example if self._curExample < len(self._examples)-1: self._exampleList_store_selection(self._curExample+1) else: #go to the first example self._exampleList_store_selection(0) def about(self, *e): ABOUT = ("NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"+ "Written by Daniel H. Garrette") TITLE = 'About: NLTK DRT Glue Demo' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size+2))) self._redraw() def _toggle_remove_duplicates(self): self._glue.remove_duplicates = not self._glue.remove_duplicates self._exampleList.selection_clear(0, 'end') self._readings = [] self._populate_readingListbox() self._readingCache = [None for ex in self._examples] self._curExample = -1 self._error = None self._drs = None self._redraw() def _exampleList_select(self, event): selection = self._exampleList.curselection() if len(selection) != 1: return self._exampleList_store_selection(int(selection[0])) def _exampleList_store_selection(self, index): self._curExample = index example = self._examples[index] self._exampleList.selection_clear(0, 'end') if example: cache = self._readingCache[index] if cache: if isinstance(cache, list): self._readings = cache self._error = None else: self._readings = [] self._error = cache else: try: self._readings = self._glue.parse_to_meaning(example) self._error = None self._readingCache[index] = self._readings except Exception, e: self._readings = [] self._error = DrtVariableExpression(Variable('Error: ' + str(e))) self._readingCache[index] = self._error #add a star to the end of the example self._exampleList.delete(index) self._exampleList.insert(index, (' %s *' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) self._populate_readingListbox() self._exampleList.selection_set(index) self._drs = None self._redraw()
class ShiftReduceApp(object): """ A graphical tool for exploring the shift-reduce parser. The tool displays the parser's stack and the remaining text, and allows the user to control the parser's operation. In particular, the user can shift tokens onto the stack, and can perform reductions on the top elements of the stack. A "step" button simply steps through the parsing process, performing the operations that ``nltk.parse.ShiftReduceParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingShiftReduceParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title("Shift Reduce Parser Application") # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animating_lock = 0 self._animate = IntVar(self._top) self._animate.set(10) # = medium # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Initialize fonts. self._init_fonts(self._top) # Set up key bindings. self._init_bindings() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # A popup menu for reducing. self._reduce_menu = Menu(self._canvas, tearoff=0) # Reset the demo, and set the feedback frame to empty. self.reset() self._lastoper1["text"] = "" ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget("size")) self._boldfont = tkFont.Font(family="helvetica", weight="bold", size=self._size.get()) self._font = tkFont.Font(family="helvetica", size=self._size.get()) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill="both", side="left", padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text="Available Reductions") self._prodlist_label.pack() self._prodlist = Listbox( self._prodframe, selectmode="single", relief="groove", background="white", foreground="#909090", font=self._font, selectforeground="#004040", selectbackground="#c0f0c0", ) self._prodlist.pack(side="right", fill="both", expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert("end", (" %s" % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if 1: # len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient="vertical") self._prodlist.config(yscrollcommand=listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side="left", fill="y") # If they select a production, apply it. self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select) # When they hover over a production, highlight it. self._hover = -1 self._prodlist.bind("<Motion>", self._highlight_hover) self._prodlist.bind("<Leave>", self._clear_hover) def _init_bindings(self): # Quit self._top.bind("<Control-q>", self.destroy) self._top.bind("<Control-x>", self.destroy) self._top.bind("<Alt-q>", self.destroy) self._top.bind("<Alt-x>", self.destroy) # Ops (step, shift, reduce, undo) self._top.bind("<space>", self.step) self._top.bind("<s>", self.shift) self._top.bind("<Alt-s>", self.shift) self._top.bind("<Control-s>", self.shift) self._top.bind("<r>", self.reduce) self._top.bind("<Alt-r>", self.reduce) self._top.bind("<Control-r>", self.reduce) self._top.bind("<Delete>", self.reset) self._top.bind("<u>", self.undo) self._top.bind("<Alt-u>", self.undo) self._top.bind("<Control-u>", self.undo) self._top.bind("<Control-z>", self.undo) self._top.bind("<BackSpace>", self.undo) # Misc self._top.bind("<Control-p>", self.postscript) self._top.bind("<Control-h>", self.help) self._top.bind("<F1>", self.help) self._top.bind("<Control-g>", self.edit_grammar) self._top.bind("<Control-t>", self.edit_sentence) # Animation speed control self._top.bind("-", lambda e, a=self._animate: a.set(20)) self._top.bind("=", lambda e, a=self._animate: a.set(10)) self._top.bind("+", lambda e, a=self._animate: a.set(4)) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill="none", side="bottom") Button(buttonframe, text="Step", background="#90c0d0", foreground="black", command=self.step).pack(side="left") Button( buttonframe, text="Shift", underline=0, background="#90f090", foreground="black", command=self.shift ).pack(side="left") Button( buttonframe, text="Reduce", underline=0, background="#90f090", foreground="black", command=self.reduce ).pack(side="left") Button(buttonframe, text="Undo", underline=0, background="#f0a0a0", foreground="black", command=self.undo).pack( side="left" ) def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del") filemenu.add_command(label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p") filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x") menubar.add_cascade(label="File", underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g") editmenu.add_command(label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t") menubar.add_cascade(label="Edit", underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space") rulemenu.add_separator() rulemenu.add_command(label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s") rulemenu.add_command(label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r") rulemenu.add_separator() rulemenu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u") menubar.add_cascade(label="Apply", underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton( label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar ) viewmenu.add_separator() viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label="View", underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0) animatemenu.add_radiobutton( label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator="-" ) animatemenu.add_radiobutton( label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator="=" ) animatemenu.add_radiobutton( label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator="+" ) menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", underline=0, command=self.about) helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1") menubar.add_cascade(label="Help", underline=0, menu=helpmenu) parent.config(menu=menubar) def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text="Last Operation:", font=self._font) self._lastoper_label.pack(side="left") lastoperframe = Frame(feedbackframe, relief="sunken", border=1) lastoperframe.pack(fill="x", side="right", expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font) self._lastoper2 = Label( lastoperframe, anchor="w", width=30, foreground="#004040", background="#f0f0f0", font=self._font ) self._lastoper1.pack(side="left") self._lastoper2.pack(side="left", fill="x", expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background="white", width=525, closeenough=10, border=2, relief="sunken") self._cframe.pack(expand=1, fill="both", side="top", pady=2) canvas = self._canvas = self._cframe.canvas() self._stackwidgets = [] self._rtextwidgets = [] self._titlebar = canvas.create_rectangle(0, 0, 0, 0, fill="#c0f0f0", outline="black") self._exprline = canvas.create_line(0, 0, 0, 0, dash=".") self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080") size = self._size.get() + 4 self._stacklabel = TextWidget(canvas, "Stack", color="#004040", font=self._boldfont) self._rtextlabel = TextWidget(canvas, "Remaining Text", color="#004040", font=self._boldfont) self._cframe.add_widget(self._stacklabel) self._cframe.add_widget(self._rtextlabel) ######################################### ## Main draw procedure ######################################### def _redraw(self): scrollregion = self._canvas["scrollregion"].split() (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion] # Delete the old stack & rtext widgets. for stackwidget in self._stackwidgets: self._cframe.destroy_widget(stackwidget) self._stackwidgets = [] for rtextwidget in self._rtextwidgets: self._cframe.destroy_widget(rtextwidget) self._rtextwidgets = [] # Position the titlebar & exprline (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4) self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10) # Position the titlebar labels.. (x1, y1, x2, y2) = self._stacklabel.bbox() self._stacklabel.move(5 - x1, 3 - y1) (x1, y1, x2, y2) = self._rtextlabel.bbox() self._rtextlabel.move(cx2 - x2 - 5, 3 - y1) # Draw the stack. stackx = 5 for tok in self._parser.stack(): if isinstance(tok, Tree): attribs = { "tree_color": "#4080a0", "tree_width": 2, "node_font": self._boldfont, "node_color": "#006060", "leaf_color": "#006060", "leaf_font": self._font, } widget = tree_to_treesegment(self._canvas, tok, **attribs) widget.node()["color"] = "#000000" else: widget = TextWidget(self._canvas, tok, color="#000000", font=self._font) widget.bind_click(self._popup_reduce) self._stackwidgets.append(widget) self._cframe.add_widget(widget, stackx, y) stackx = widget.bbox()[2] + 10 # Draw the remaining text. rtextwidth = 0 for tok in self._parser.remaining_text(): widget = TextWidget(self._canvas, tok, color="#000000", font=self._font) self._rtextwidgets.append(widget) self._cframe.add_widget(widget, rtextwidth, y) rtextwidth = widget.bbox()[2] + 4 # Allow enough room to shift the next token (for animations) if len(self._rtextwidgets) > 0: stackx += self._rtextwidgets[0].width() # Move the remaining text to the correct location (keep it # right-justified, when possible); and move the remaining text # label, if necessary. stackx = max(stackx, self._stacklabel.width() + 25) rlabelwidth = self._rtextlabel.width() + 10 if stackx >= cx2 - max(rtextwidth, rlabelwidth): cx2 = stackx + max(rtextwidth, rlabelwidth) for rtextwidget in self._rtextwidgets: rtextwidget.move(4 + cx2 - rtextwidth, 0) self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0) midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) (x1, y1, x2, y2) = self._stacklabel.bbox() # Set up binding to allow them to shift a token by dragging it. if len(self._rtextwidgets) > 0: def drag_shift(widget, midx=midx, self=self): if widget.bbox()[0] < midx: self.shift() else: self._redraw() self._rtextwidgets[0].bind_drag(drag_shift) self._rtextwidgets[0].bind_click(self.shift) # Draw the stack top. self._highlight_productions() def _draw_stack_top(self, widget): # hack.. midx = widget.bbox()[2] + 50 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) def _highlight_productions(self): # Highlight the productions that can be reduced. self._prodlist.selection_clear(0, "end") for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Button Callbacks ######################################### def destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._parser.initialize(self._sent) self._lastoper1["text"] = "Reset App" self._lastoper2["text"] = "" self._redraw() def step(self, *e): if self.reduce(): return 1 elif self.shift(): return 1 else: if len(self._parser.parses()) > 0: self._lastoper1["text"] = "Finished:" self._lastoper2["text"] = "Success" else: self._lastoper1["text"] = "Finished:" self._lastoper2["text"] = "Failure" def shift(self, *e): if self._animating_lock: return if self._parser.shift(): tok = self._parser.stack()[-1] self._lastoper1["text"] = "Shift:" self._lastoper2["text"] = "%r" % tok if self._animate.get(): self._animate_shift() else: self._redraw() return 1 return 0 def reduce(self, *e): if self._animating_lock: return production = self._parser.reduce() if production: self._lastoper1["text"] = "Reduce:" self._lastoper2["text"] = "%s" % production if self._animate.get(): self._animate_reduce() else: self._redraw() return production def undo(self, *e): if self._animating_lock: return if self._parser.undo(): self._redraw() def postscript(self, *e): self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) ######################################### ## Menubar callbacks ######################################### def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) # self._stacklabel['font'] = ('helvetica', -size-4, 'bold') # self._rtextlabel['font'] = ('helvetica', -size-4, 'bold') # self._lastoper_label['font'] = ('helvetica', -size) # self._lastoper1['font'] = ('helvetica', -size) # self._lastoper2['font'] = ('helvetica', -size) # self._prodlist['font'] = ('helvetica', -size) # self._prodlist_label['font'] = ('helvetica', -size-2, 'bold') self._redraw() def help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, "Help: Shift-Reduce Parser Application", (__doc__).strip(), width=75, font="fixed") except: ShowText(self._top, "Help: Shift-Reduce Parser Application", (__doc__).strip(), width=75) def about(self, *e): ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper" TITLE = "About: Shift-Reduce Parser Application" try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, "end") for production in self._productions: self._prodlist.insert("end", (" %s" % production)) def edit_sentence(self, *e): sentence = string.join(self._sent) title = "Edit Text" instr = "Enter a new sentence to parse." EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sent): self._sent = sent.split() # [XX] use tagged? self.reset() ######################################### ## Reduce Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill="both", side="left", padx=2, after=self._feedbackframe) self._lastoper1["text"] = "Show Grammar" else: self._prodframe.pack_forget() self._lastoper1["text"] = "Hide Grammar" self._lastoper2["text"] = "" def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) production = self._parser.reduce(self._productions[index]) if production: self._lastoper1["text"] = "Reduce:" self._lastoper2["text"] = "%s" % production if self._animate.get(): self._animate_reduce() else: self._redraw() else: # Reset the production selections. self._prodlist.selection_clear(0, "end") for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) def _popup_reduce(self, widget): # Remove old commands. productions = self._parser.reducible_productions() if len(productions) == 0: return self._reduce_menu.delete(0, "end") for production in productions: self._reduce_menu.add_command(label=str(production), command=self.reduce) self._reduce_menu.post(self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()) ######################################### ## Animations ######################################### def _animate_shift(self): # What widget are we shifting? widget = self._rtextwidgets[0] # Where are we shifting from & to? right = widget.bbox()[0] if len(self._stackwidgets) == 0: left = 5 else: left = self._stackwidgets[-1].bbox()[2] + 10 # Start animating. dt = self._animate.get() dx = (left - right) * 1.0 / dt self._animate_shift_frame(dt, widget, dx) def _animate_shift_frame(self, frame, widget, dx): if frame > 0: self._animating_lock = 1 widget.move(dx, 0) self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx) else: # but: stacktop?? # Shift the widget to the stack. del self._rtextwidgets[0] self._stackwidgets.append(widget) self._animating_lock = 0 # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() def _animate_reduce(self): # What widgets are we shifting? numwidgets = len(self._parser.stack()[-1]) # number of children widgets = self._stackwidgets[-numwidgets:] # How far are we moving? if isinstance(widgets[0], TreeSegmentWidget): ydist = 15 + widgets[0].node().height() else: ydist = 15 + widgets[0].height() # Start animating. dt = self._animate.get() dy = ydist * 2.0 / dt self._animate_reduce_frame(dt / 2, widgets, dy) def _animate_reduce_frame(self, frame, widgets, dy): if frame > 0: self._animating_lock = 1 for widget in widgets: widget.move(0, dy) self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy) else: del self._stackwidgets[-len(widgets) :] for widget in widgets: self._cframe.remove_widget(widget) tok = self._parser.stack()[-1] if not isinstance(tok, Tree): raise ValueError() label = TextWidget(self._canvas, str(tok.node), color="#006060", font=self._boldfont) widget = TreeSegmentWidget(self._canvas, label, widgets, width=2) (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 if not self._stackwidgets: x = 5 else: x = self._stackwidgets[-1].bbox()[2] + 10 self._cframe.add_widget(widget, x, y) self._stackwidgets.append(widget) # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() # # Delete the old widgets.. # del self._stackwidgets[-len(widgets):] # for widget in widgets: # self._cframe.destroy_widget(widget) # # # Make a new one. # tok = self._parser.stack()[-1] # if isinstance(tok, Tree): # attribs = {'tree_color': '#4080a0', 'tree_width': 2, # 'node_font': bold, 'node_color': '#006060', # 'leaf_color': '#006060', 'leaf_font':self._font} # widget = tree_to_treesegment(self._canvas, tok.type(), # **attribs) # widget.node()['color'] = '#000000' # else: # widget = TextWidget(self._canvas, tok.type(), # color='#000000', font=self._font) # widget.bind_click(self._popup_reduce) # (x1, y1, x2, y2) = self._stacklabel.bbox() # y = y2-y1+10 # if not self._stackwidgets: x = 5 # else: x = self._stackwidgets[-1].bbox()[2] + 10 # self._cframe.add_widget(widget, x, y) # self._stackwidgets.append(widget) # self._redraw() self._animating_lock = 0 ######################################### ## Hovering. ######################################### def _highlight_hover(self, event): # What production are we hovering over? index = self._prodlist.nearest(event.y) if self._hover == index: return # Clear any previous hover highlighting. self._clear_hover() # If the production corresponds to an available reduction, # highlight the stack. selection = [int(s) for s in self._prodlist.curselection()] if index in selection: rhslen = len(self._productions[index].rhs()) for stackwidget in self._stackwidgets[-rhslen:]: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.node()["color"] = "#00a000" else: stackwidget["color"] = "#00a000" # Remember what production we're hovering over. self._hover = index def _clear_hover(self, *event): # Clear any previous hover highlighting. if self._hover == -1: return self._hover = -1 for stackwidget in self._stackwidgets: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.node()["color"] = "black" else: stackwidget["color"] = "black"
class simpleapp_tk(tk.Tk): def __init__(self, parent): ## class derives from Tkinter --> call its constructor tk.Tk.__init__(self, parent) ## keep track of the parent self.parent = parent self.initialize() def initialize(self): listFrame = Frame(self) listFrame.pack(side=TOP, fill=BOTH, expand=True) scrollbary = Scrollbar(listFrame, orient=VERTICAL) scrollbary.pack(side=RIGHT, fill=Y) scrollbarx = Scrollbar(listFrame, orient=HORIZONTAL) scrollbarx.pack(side=BOTTOM, fill=X) ##bd --> border self.listbox = Listbox(listFrame, bd=0, selectmode=SINGLE, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set) #self.listbox.bind('<<ListboxSelect>>',self.OnSelectClick) scrollbary.config(command=self.listbox.yview) scrollbarx.config(command=self.listbox.xview) # initialize with data from file self.populateFrom() self.listbox.config(width=self.listbox.winfo_reqwidth() ) #width=self.listbox.winfo_reqwidth() self.listbox.pack(side=LEFT, fill=BOTH, expand=True) #fill=Y, expand=False #self.listbox.focus_set() buttonFrame = Frame(self) buttonFrame.pack(fill=X) self.Path = tk.StringVar() self.Path.set('') self.SourcePath = tk.Entry(buttonFrame, textvariable=self.Path) b = Button(buttonFrame, text="TODO") b.bind('<Button-1>', self.OnDeleteSingleClick) b.pack(side=RIGHT) debugFrame = Frame(self) debugFrame.pack(side=BOTTOM, fill=X) self.selectedPath = tk.StringVar() self.pathLabel = tk.Label(debugFrame, textvariable=self.selectedPath, bg="white", anchor=tk.W) self.pathLabel.pack(side=LEFT, fill=X, expand=True) self.update() ## fix the size of the window by setting the window size to its own size w = self.winfo_screenwidth() h = self.winfo_screenheight() self.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_reqwidth(), self.winfo_reqheight(), w - self.winfo_reqwidth() - 20, 0)) #self.geometry() ## update(): Tkinter has finished rendering all widgets and evaluating their size self.update() self.minsize(self.winfo_reqwidth(), self.winfo_reqheight()) def populateFrom(self): pass def OnDeleteSingleClick(self, event): print '====DELETESINGLE====' #print self.listbox.get(tk.ANCHOR) #print list(self.listbox.get(0, END)) #self.listbox.delete(tk.ANCHOR) def OnDeleteAllClick(self, event): print '====DELETEALL===='
class DrtGlueDemo(object): def __init__(self, examples): # Set up the main window. self._top = Tk() self._top.title('DRT Glue Demo') # Set up key bindings. self._init_bindings() # Initialize the fonts.self._error = None self._init_fonts(self._top) self._examples = examples self._readingCache = [None for example in examples] # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Set the data to None self._curExample = -1 self._readings = [] self._drs = None self._drsWidget = None self._error = None self._init_glue() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_exampleListbox(self._top) self._init_readingListbox(self._top) self._init_canvas(self._top) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_glue(self): tagger = RegexpTagger([ ('^(David|Mary|John)$', 'NNP'), ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'), ('^(go|order|vanish|find|approach)$', 'VB'), ('^(a)$', 'ex_quant'), ('^(every)$', 'univ_quant'), ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'), ('^(big|gray|former)$', 'JJ'), ('^(him|himself)$', 'PRP') ]) depparser = MaltParser(tagger=tagger) self._glue = DrtGlue(depparser=depparser, remove_duplicates=False) def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = Font(family='helvetica', weight='bold', size=self._size.get()) self._font = Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get() - 2 else: big = self._size.get() + 2 self._bigfont = Font(family='helvetica', weight='bold', size=big) def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill='both', side='left', padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text='Examples') self._exampleList_label.pack() self._exampleList = Listbox(self._exampleFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._exampleList.pack(side='right', fill='both', expand=1) for example in self._examples: self._exampleList.insert('end', (' %s' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient='vertical') self._exampleList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side='left', fill='y') # If they select a example, apply it. self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select) def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill='both', side='left', padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text='Readings') self._readingList_label.pack() self._readingList = Listbox(self._readingFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._readingList.pack(side='right', fill='both', expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient='vertical') self._readingList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side='right', fill='y') self._populate_readingListbox() def _populate_readingListbox(self): # Populate the listbox with integers self._readingList.delete(0, 'end') for i in range(len(self._readings)): self._readingList.insert('end', (' %s' % (i + 1))) self._readingList.config(height=min(len(self._readings), 25), width=5) # If they select a example, apply it. self._readingList.bind('<<ListboxSelect>>', self._readingList_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('n', self.next) self._top.bind('<space>', self.next) self._top.bind('p', self.prev) self._top.bind('<BackSpace>', self.prev) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button( buttonframe, text='Prev', background='#90c0d0', foreground='black', command=self.prev, ).pack(side='left') Button( buttonframe, text='Next', background='#90c0d0', foreground='black', command=self.next, ).pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1, y1, x2, y2) self._redraw() def _init_canvas(self, parent): self._cframe = CanvasFrame( parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='q') menubar.add_cascade(label='File', underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label='Next', underline=0, command=self.next, accelerator='n, Space') actionmenu.add_command(label='Previous', underline=0, command=self.prev, accelerator='p, Backspace') menubar.add_cascade(label='Action', underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton(label='Remove Duplicates', underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator='r') menubar.add_cascade(label='Options', underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old DRS, widgets, etc. if self._drsWidget is not None: self._drsWidget.clear() if self._drs: self._drsWidget = DrsWidget(self._canvas, self._drs) self._drsWidget.draw() if self._error: self._drsWidget = DrsWidget(self._canvas, self._error) self._drsWidget.draw() ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def prev(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or before) the first item if index <= 0: self._select_previous_example() else: self._readingList_store_selection(index - 1) else: #select its first reading self._readingList_store_selection(readingListSize - 1) else: self._select_previous_example() def _select_previous_example(self): #if the current example is not the first example if self._curExample > 0: self._exampleList_store_selection(self._curExample - 1) else: #go to the last example self._exampleList_store_selection(len(self._examples) - 1) def next(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # if there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or past) the last item if index >= (readingListSize - 1): self._select_next_example() else: self._readingList_store_selection(index + 1) else: #select its first reading self._readingList_store_selection(0) else: self._select_next_example() def _select_next_example(self): #if the current example is not the last example if self._curExample < len(self._examples) - 1: self._exampleList_store_selection(self._curExample + 1) else: #go to the first example self._exampleList_store_selection(0) def about(self, *e): ABOUT = ( "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n" + "Written by Daniel H. Garrette") TITLE = 'About: NLTK DRT Glue Demo' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size + 2))) self._redraw() def _toggle_remove_duplicates(self): self._glue.remove_duplicates = not self._glue.remove_duplicates self._exampleList.selection_clear(0, 'end') self._readings = [] self._populate_readingListbox() self._readingCache = [None for ex in self._examples] self._curExample = -1 self._error = None self._drs = None self._redraw() def _exampleList_select(self, event): selection = self._exampleList.curselection() if len(selection) != 1: return self._exampleList_store_selection(int(selection[0])) def _exampleList_store_selection(self, index): self._curExample = index example = self._examples[index] self._exampleList.selection_clear(0, 'end') if example: cache = self._readingCache[index] if cache: if isinstance(cache, list): self._readings = cache self._error = None else: self._readings = [] self._error = cache else: try: self._readings = self._glue.parse_to_meaning(example) self._error = None self._readingCache[index] = self._readings except Exception as e: self._readings = [] self._error = DrtVariableExpression( Variable('Error: ' + str(e))) self._readingCache[index] = self._error #add a star to the end of the example self._exampleList.delete(index) self._exampleList.insert(index, (' %s *' % example)) self._exampleList.config(height=min( len(self._examples), 25), width=40) self._populate_readingListbox() self._exampleList.selection_set(index) self._drs = None self._redraw() def _readingList_select(self, event): selection = self._readingList.curselection() if len(selection) != 1: return self._readingList_store_selection(int(selection[0])) def _readingList_store_selection(self, index): reading = self._readings[index] self._readingList.selection_clear(0, 'end') if reading: self._readingList.selection_set(index) self._drs = reading.simplify().normalize().resolve_anaphora() self._redraw()
class Application(Frame): def compress(self, sCTRL, dCTRL, eCTRL, gCTRL): allCTRL = { 'Student': sCTRL, 'Discipline': dCTRL, 'Enroll': eCTRL, 'Grade': gCTRL } pickle.dump(allCTRL, open("save.p", "wb")) def compare(self): if self.oCont >= self.Max: self.Max = self.oCont return def reader(self, Input, InputNumber): try: Input.getvar((str(InputNumber))) except TclError as tcl: s = str(tcl) return s.split("\"")[1] def clearText(self): self.textFrame.delete('1.0', END) def Srefresh(self): controller = self._studentControl.getCurentRepo().getStudents() curList = self.sList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Drefresh(self): controller = self._disciplineControl.getCurentRepo().getDisciplines() curList = self.dList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Erefresh(self): controller = self._enrolControl.getCurentRepo().getEnroll() curList = self.eList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def Grefresh(self): controller = self._gradeControl.getCurentRepo().getGrades() curList = self.gList curList.delete(0, END) controller.sort() for index in controller: curList.insert(END, index) def refreshALL(self): self.Srefresh() self.Drefresh() self.Erefresh() self.Grefresh() def SreadID(self, string): return string[11:string.index('|') - 1] def DreadID(self, string): return string[15:string.index('|') - 1] def EreadID(self, string): return [ string[12:string.index('|') - 1], string[string.index('|') + 15:-2] ] def sPopup(self, event): self.sMenu.post(event.x_root, event.y_root) def dPopup(self, event): self.dMenu.post(event.x_root, event.y_root) def ePopup(self, event): self.eMenu.post(event.x_root, event.y_root) def gPopup(self, event): self.gMenu.post(event.x_root, event.y_root) def displayError(self, msg): tkMessageBox.showerror('Error', msg) def NewFile(self): self._studentControl.setRepo(deepcopy(student(1, ''))) self._disciplineControl.setRepo(deepcopy(discipline(1, ''))) self._enrolControl.setRepo(deepcopy(enroll(1, 1))) self._gradeControl.setRepo(deepcopy(grade(1, 1))) self.refreshALL() ''' #============================================# :STUDENT: #============================================# ''' def add_Student(self): try: top = tk.Toplevel() top.title('Input') Input = Window2('Enter student ID: ', 'Enter student Name: ', top) Input.mainloop() top.destroy() if not Input.getvar(str( Input.Input1)) == None and not Input.getvar( str(Input.Input2)) == None: studentID = Input.getvar(str(Input.Input1)) name = Input.getvar(str(Input.Input2)) print studentID print name Valid().ID(studentID) Valid().name(name) self._studentControl.getCurentRepo().addStudent( student(int(studentID), name)) self._studentControl.create(int(studentID), name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except idError: self.displayError('Invalid ID') def remove_Student(self): try: index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) name = '' eList = [] gList = [] for Student in self._studentControl.getCurentRepo().getStudents(): if int(Student.getId()) == studentID: name = Student.getName() for enroll in self._enrolControl.getCurentRepo().getEnroll(): if enroll.get_student_id() == studentID: eList.append(enroll) for grade in self._gradeControl.getCurentRepo().getGrades(): if int(grade.getStudentID()) == studentID: gList.append(grade) try: self._studentControl.removeStudent(studentID) except classException: pass try: self._enrolControl.removeEnrollStudent(studentID) except classException: pass try: self._gradeControl.removeGradeStudent(studentID) except classException: pass self._studentControl.delete(studentID, eList, gList, name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_StudentID(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New ID', top) Input.mainloop() top.destroy() index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) if not Input.getvar(str(Input.Input1)) == None: newID = Input.getvar(str(Input.Input1)) newID = int(newID) self._studentControl.getCurentRepo().updateStudentID( studentID, newID) self._enrolControl.getCurentRepo().updateStudentID( studentID, newID) self._gradeControl.getCurentRepo().updateGradeStudentID( int(studentID), newID) self._studentControl.updateID(studentID, newID) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_StudentName(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New name', top) Input.mainloop() top.destroy() index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) oldName = self.sList.get(index)[self.sList.get(index).index('|') + 9:-2] if not Input.getvar(str(Input.Input1)) == None: newName = Input.getvar(str(Input.Input1)) Valid().name(newName) self._studentControl.getCurentRepo().updateStudentName( studentID, newName) self._studentControl.updateName(studentID, oldName, newName) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #=============================================# :DISCIPLINE: #=============================================# ''' def add_Discipline(self): try: top = tk.Toplevel() top.title('Input') Input = Window2('Enter discipline ID: ', 'Enter discipline Name: ', top) Input.mainloop() top.destroy() if not Input.getvar(str(Input.Input1)) == None or not Input.getvar( str(Input.Input2)) == None: disciplineID = Input.getvar(str(Input.Input1)) name = Input.getvar(str(Input.Input2)) Valid().name(name) Valid().ID(disciplineID) self._disciplineControl.getCurentRepo().addDiscipline( discipline(int(disciplineID), name)) self._disciplineControl.create(int(disciplineID), name) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') except idError: self.displayError('Invalid ID') def remove_Discipline(self): try: index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) name = '' eList = [] gList = [] for Discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if int(Discipline.getId()) == disciplineID: name = Discipline.getName() for enroll in self._enrolControl.getCurentRepo().getEnroll(): if enroll.get_discipline_id() == disciplineID: eList.append(enroll) for grade in self._gradeControl.getCurentRepo().getGrades(): if grade.getDisciplineID() == disciplineID: gList.append(grade) try: self._disciplineControl.removeDiscipline(disciplineID) except classException: pass try: self._gradeControl.removeGradeDiscipline(disciplineID) except classException: pass try: self._enrolControl.removeEnrollDiscipline(disciplineID) except classException: pass try: self._disciplineControl.delete(disciplineID, eList, gList, name) except classException: pass self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_DisciplineID(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New ID', top) Input.mainloop() top.destroy() index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) if not Input.getvar(str(Input.Input1)) == None: newID = Input.getvar(str(Input.Input1)) newID = int(newID) self._disciplineControl.getCurentRepo().updateDisciplineID( disciplineID, newID) self._enrolControl.getCurentRepo().updateDisciplineID( disciplineID, newID) self._gradeControl.getCurentRepo().updateGradeDisciplineID( disciplineID, newID) self._disciplineControl.updateID(disciplineID, newID) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def update_DisciplineName(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('New name', top) Input.mainloop() top.destroy() index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) oldName = self.dList.get(index)[self.dList.get(index).index('|') + 8:-2] if not Input.getvar(str(Input.Input1)) == None: newName = Input.getvar(str(Input.Input1)) Valid().name(newName) self._disciplineControl.getCurentRepo().updateDisciplineName( disciplineID, newName) self._disciplineControl.updateName(disciplineID, oldName, newName) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #===================================================# :ENROLL: #===================================================# ''' def remove_Enroll(self): try: index = self.eList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disicplineID = int(IDs[1]) self.eList.delete(ANCHOR) self._gradeControl.removeGrade(enroll(studentID, disicplineID)) self._enrolControl.removeEnroll(enroll(studentID, disicplineID)) self.Erefresh() self.Grefresh() self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def add_Enroll(self): try: index = self.sList.curselection() studentID = self.SreadID(self.sList.get(index)) studentID = int(studentID) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) #try: self._enrolControl.addEnroll(enroll(studentID, disciplineID)) #except ValueError: #self.displayError('Enrollment allready exists') self._enrolControl.create(enroll(studentID, disciplineID)) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') def add_EnrollGrade(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('Grade: ', top) Input.mainloop() top.destroy() index = self.eList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disciplineID = int(IDs[1]) if not Input.getvar(str(Input.Input1)) == None: gradeValue = Input.getvar(str(Input.Input1)) gradeValue = float(gradeValue) Valid().grade(gradeValue) self._gradeControl.addGrade(grade(disciplineID, studentID), gradeValue) self.Grefresh() self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #=======================================================# :GRADE: #=======================================================# ''' def add_Grade(self): try: top = tk.Toplevel() top.title('Input') Input = WindowRemove('Grade: ', top) Input.mainloop() top.destroy() index = self.gList.curselection() IDs = self.EreadID(self.eList.get(index)) studentID = int(IDs[0]) disciplineID = int(IDs[1]) if not Input.getvar(str(Input.Input1)) == None: gradeValue = Input.getvar(str(Input.Input1)) gradeValue = float(gradeValue) Valid().grade(gradeValue) self._gradeControl.addGrade(grade(disciplineID, studentID), gradeValue) self._gradeControl.create(grade(disciplineID, studentID), gradeValue) self.refreshALL() except ValueError: self.displayError('Invalid Input') except NameError: self.displayError('Invalid Name') except TclError: self.displayError('No item selected') ''' #================================================# :SEARCH: #================================================# ''' def SearchALL(self): top = tk.Toplevel() top.title('Input') Input = WindowRemove('Search: ', top) Input.mainloop() top.destroy() searchString = Input.getvar(str(Input.Input1)) top = tk.Toplevel() top.title('Serch Results') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) top.text.insert(END, 'Disciplines:') for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if searchString.lower() in str(discipline.getId()).lower() or str( discipline.getId()).lower() in searchString.lower( ) or searchString.lower() in discipline.getName().lower( ) or discipline.getName().lower() in searchString.lower(): top.text.insert(END, discipline) top.text.insert(END, 'Students:') for student in self._studentControl.getCurentRepo().getStudents(): if searchString.lower() in str(student.getId()).lower() or str( student.getId()).lower() in searchString.lower( ) or searchString.lower() in student.getName().lower( ) or student.getName().lower() in searchString.lower(): top.text.insert(END, student) ''' #===============================================# :STATISCTICS: #===============================================# ''' def StudentEnrollA(self): try: top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) SList = self._enrolControl.studentEnrollA(disciplineID) for index in SList: top.text.insert(END, index) del SList[:] except TclError: top.destroy() self.displayError('No disicpline Selected') def StudentEnrollB(self): try: top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) index = self.dList.curselection() disciplineID = self.DreadID(self.dList.get(index)) disciplineID = int(disciplineID) SList = [[' ', -1]] for grade in self._gradeControl.getCurentRepo().getGrades(): if grade.getDisciplineID() == disciplineID: for student in self._studentControl.getCurentRepo( ).getStudents(): if student.getId() == grade.getStudentID(): if grade.getGrade() != []: gradeAvg = self.listAvg( grade.getGrade(), grade.getGradeSize()) SList.append([student.getName(), gradeAvg]) SList.sort(key=itemgetter(1), reverse=True) del SList[-1] for index in SList: top.text.insert(END, index) del SList[:] except TclError: top.destroy() self.displayError('No disicpline Selected') def FailingStudents(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] for grade in self._gradeControl.getCurentRepo().getGrades(): for student in self._studentControl.getCurentRepo().getStudents(): for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): if grade.getStudentID() == student.getId(): if grade.getDisciplineID() == discipline.getId(): if grade.getGrade() != []: gradeAvg = self.listAvg( grade.getGrade(), grade.getGradeSize()) if gradeAvg < 5: sList.append([ student.getName(), discipline.getName() ]) for index in sList: top.text.insert(END, '\n' + index[0] + ' - ' + index[1]) del sList[:] def BestStudents(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] gList = [] sName = '' for student in self._studentControl.getCurentRepo().getStudents(): for grade in self._gradeControl.getCurentRepo().getGrades(): if student.getId() == grade.getStudentID(): if (grade.getGrade() != []): gAvg = self.listAvg(grade.getGrade(), grade.getGradeSize()) gList.append(gAvg) sName = student.getName() if gList != []: sAvg = self.listAvg(gList, len(gList)) sList.append([sName, round(sAvg, 2)]) sList.sort(key=itemgetter(1), reverse=True) for index in range(1, len(sList)): top.text.insert( END, str(sList[index][0] + ' - ' + str(sList[index][1]))) del sList[:] def DisciplineH(self): top = tk.Toplevel() top.title('Enrollment List') top.text = Listbox(top) top.text.grid(row=0, column=0) top.text.config(width=50) sList = [['', '']] gList = [] dName = '' for discipline in self._disciplineControl.getCurentRepo( ).getDisciplines(): for grade in self._gradeControl.getCurentRepo().getGrades(): if discipline.getId() == grade.getDisciplineID(): if (grade.getGrade() != []): gAvg = self.listAvg(grade.getGrade(), grade.getGradeSize()) gList.append(gAvg) dName = discipline.getName() if gList != []: sAvg = self.listAvg(gList, len(gList)) sList.append([dName, round(sAvg, 2)]) sList.sort(key=itemgetter(1), reverse=True) for index in range(1, len(sList)): top.text.insert( END, '\n' + str(sList[index][0]) + ' - ' + str(sList[index][1])) del sList[:] ''' #======================================# :EDIT: #======================================# ''' def undo(self, event): self._undoControl.undo() self.refreshALL() def redo(self, event): self._undoControl.redo() self.refreshALL() ''' #===========================================================================================# :Widgets: #===========================================================================================# ''' def createWidgets(self): ''' #==================================================# :TOPBAR: #==================================================# ''' self.fileButton = Menubutton(self, text='File', relief='flat') self.fileButton.grid(row=0, column=0) self.fileButton.menu = Menu(self.fileButton, tearoff=0) self.fileButton["menu"] = self.fileButton.menu self.fileButton.menu.add_command(label="New", command=self.NewFile) self.fileButton.menu.add_command(label="Exit", command=self.quit) self.eButton = Menubutton(self, text="Enrollment", relief='flat') self.eButton.grid(row=0, column=1) self.eButton.menu = Menu(self.eButton, tearoff=0) self.eButton["menu"] = self.eButton.menu self.eButton.menu.add_command(label="Add Enrollment", command=self.add_Enroll) self.statButton = Menubutton(self, text="Statistics", relief='flat') self.statButton.grid(row=0, column=2) self.statButton.menu = Menu(self.statButton, tearoff=0) self.statButton["menu"] = self.statButton.menu self.discMenu = Menu(tearoff=0) self.discMenu.add_command(label="Sort by name", command=self.StudentEnrollA) self.discMenu.add_command(label="Sort by grade", command=self.StudentEnrollB) self.statButton.menu.add_cascade( label="Students Enrolled at disicpline", menu=self.discMenu) self.statButton.menu.add_command(label="Failing Students", command=self.FailingStudents) self.statButton.menu.add_command(label="Best Students", command=self.BestStudents) self.statButton.menu.add_command(label="Discipline Averages", command=self.DisciplineH) self.searchButton = Menubutton(self, text="Search", relief='flat') self.searchButton.grid(row=0, column=3) self.searchButton.menu = Menu(self.searchButton, tearoff=0) self.searchButton["menu"] = self.searchButton.menu self.searchButton.menu.add_command(label="Search", command=self.SearchALL) self.editButton = Menubutton(self, text="Edit", relief='flat') self.editButton.grid(row=0, column=4) self.editButton.menu = Menu(self.editButton, tearoff=0) self.editButton["menu"] = self.editButton.menu self.editButton.menu.add_command(label="Undo", command=self.undo) self.editButton.menu.add_command(label="Redo", command=self.redo) self.root.bind('<Control-z>', self.undo) self.root.bind('<Control-y>', self.redo) ''' #===================================================# :Student: #===================================================# ''' self.sbar = Label(self, text='Student list', fg='white', bg='#3B9C9C', width=49) self.sbar.grid(row=1, column=0, columnspan=16) self.sList = Listbox(self, exportselection=0) for index in self._studentControl.getCurentRepo().getStudents(): self.sList.insert(END, index) self.sList.grid(row=2, column=0, columnspan=16) self.sList.config(width=57, height=40) self.sMenu = Menu(self, tearoff=0) self.sMenu.add_command(label="Add Student", command=self.add_Student) self.sMenu.add_command(label="Remove Student", command=self.remove_Student) self.sMenu.add_command(label='Update Student ID', command=self.update_StudentID) self.sMenu.add_command(label='Update Student name', command=self.update_StudentName) self.sMenu.add_command(label='Refresh', command=self.Srefresh) self.sList.bind("<Button-3>", self.sPopup) ''' #===================================================# :Discipline: #===================================================# ''' self.dbar = Label(self, text='Discipline list', fg='white', bg='#3B9C9C', width=49) self.dbar.grid(row=1, column=16, columnspan=16) self.dList = Listbox(self, exportselection=0) for index in self._disciplineControl.getCurentRepo().getDisciplines(): self.dList.insert(END, index) self.dList.grid(row=2, column=16, columnspan=16) self.dList.config(width=57, height=40) self.dMenu = Menu(self, tearoff=0) self.dMenu.add_command(label="Add Discipline", command=self.add_Discipline) self.dMenu.add_command(label="Remove Discipline", command=self.remove_Discipline) self.dMenu.add_command(label='Update Discipline ID', command=self.update_DisciplineID) self.dMenu.add_command(label='Update Discipline name', command=self.update_DisciplineName) self.dMenu.add_command(label='Refresh', command=self.Drefresh) self.dList.bind("<Button-3>", self.dPopup) ''' #===================================================# :Enroll: #===================================================# ''' self.ebar = Label(self, text='Enroll list', fg='white', bg='#3B9C9C', width=49) self.ebar.grid(row=1, column=32, columnspan=16) self.eList = Listbox(self, exportselection=0) for index in self._enrolControl.getCurentRepo().getEnroll(): self.eList.insert(END, '\n' + str(index)) self.eList.grid(row=2, column=32, columnspan=16) self.eList.config(width=57, height=40) self.eMenu = Menu(self, tearoff=0) self.eMenu.add_command(label="Remove Enrollment", command=self.remove_Enroll) self.eMenu.add_command(label="Grade Student", command=self.add_EnrollGrade) self.eMenu.add_command(label='Refresh', command=self.Erefresh) self.eList.bind("<Button-3>", self.ePopup) ''' #===================================================# :Grade: #===================================================# ''' self.gbar = Label(self, text='Grade list', fg='white', bg='#3B9C9C', width=49) self.gbar.grid(row=1, column=48, columnspan=16) self.gList = Listbox(self, exportselection=0) for index in self._gradeControl.getCurentRepo().getGrades(): self.gList.insert(END, '\n' + str(index)) self.gList.grid(row=2, column=48, columnspan=16) self.gList.config(width=57, height=40) self.gMenu = Menu(self, tearoff=0) self.gMenu.add_command(label="Grade Student", command=self.add_Grade) self.gMenu.add_command(label='Refresh', command=self.Grefresh) self.gList.bind("<Button-3>", self.gPopup) def __init__(self, studentControl, disciplineControl, gradeControl, enrolControl, U1, master=None): Frame.__init__(self, master) self.pack() self.grid() self.Max = 0 self.oCont = 0 self.root = master self._studentControl = studentControl self._disciplineControl = disciplineControl self._gradeControl = gradeControl self._enrolControl = enrolControl self._undoControl = U1 self.createWidgets() @staticmethod def listAvg(myList, size): s = 0.0 for index in range(size): s += myList[index] s /= size return s
class Application(Frame): """Main application class""" json_file_name = "functions.json" # should be none after tests json_data = None def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.create_widgets() master.title("Regula falsi") master.minsize(width=100, height=100) master.config(menu=self.menubar) def calculate(self): """Does all the work""" item_number = self.fields.curselection() polynomial = self.json_data["functions"][int(item_number[0])] result_floating = None result_interval = None if self.json_data["method"] == "regula_falsi": try: result_floating = regula_falsi(polynomial["a"], polynomial["b"], function_from_list, polynomial["coeff"] ) except MyError as error: result_floating = error.value except ZeroDivisionError: result_floating = "Unfortunately, division by 0 happened" try: result_interval = regula_falsi_interval(polynomial["a"], polynomial["b"], function_from_list, polynomial["coeff"] ) result_interval = result_interval.format('%.20E')[9:] result_interval = result_interval[:-1] except MyError as error: result_interval = error.value elif self.json_data["method"] == "newton": try: result_floating = newton(polynomial["x"], polynomial["epsilon"], polynomial["max_iterations"], function_from_list, polynomial["coeff"], polynomial["derivative_coeff"] ) except ZeroDivisionError: result_floating = "Unfortunately, division by zero happened" except MyError as error: result_floating = error.value try: result_interval = newton_interval(polynomial["x"], polynomial["epsilon"], polynomial["max_iterations"], function_from_list, polynomial["coeff"], polynomial["derivative_coeff"] ) result_interval = result_interval.format('%.20E')[9:] result_interval = result_interval[:-1] except MyError as error: result_interval = error.value else: result_interval = "You propably" result_floating = "gave me wrong JSON" self.show_result_floating.config(text=result_interval) self.show_result_interval.config(text=result_floating) def read_json_file(self): """Reads function coefficients from json files""" self.fields.delete(0, END) self.json_file_name = load_file() with open(self.json_file_name) as json_file: self.json_data = json.load(json_file) for item in self.json_data["functions"]: self.fields.insert(END, item["coeff"]) def create_widgets(self): """Creates buttons on the window and binds actions to them""" #listbox for the equations self.fields = Listbox(self, selectmode=SINGLE) self.fields.config(width=100) self.fields.pack() #button for calculating self.calculate_button = Button(self) self.calculate_button["text"] = "Calculate" self.calculate_button["command"] = self.calculate self.calculate_button.pack({"side": "left"}) #to the end self.show_result_floating = Message(self, width=250) self.show_result_floating.pack() #second Message self.show_result_interval = Message(self, width=250) self.show_result_interval.pack() #adding menu buttons to the window self.menubar = Menu(self) self.menubar.add_command(label="Load file", command=self.read_json_file) self.menubar.add_command(label="Quit", command=self.quit)
class RecursiveDescentApp(object): """ A graphical tool for exploring the recursive descent parser. The tool displays the parser's tree and the remaining text, and allows the user to control the parser's operation. In particular, the user can expand subtrees on the frontier, match tokens on the frontier against the text, and backtrack. A "step" button simply steps through the parsing process, performing the operations that ``RecursiveDescentParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingRecursiveDescentParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Recursive Descent Parser Application') # Set up key bindings. self._init_bindings() # Initialize the fonts. self._init_fonts(self._top) # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animation_frames = IntVar(self._top) self._animation_frames.set(5) self._animating_lock = 0 self._autostep = 0 # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # Initialize the parser. self._parser.initialize(self._sent) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = tkFont.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkFont.Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get() - 2 else: big = self._size.get() + 2 self._bigfont = tkFont.Font(family='helvetica', weight='bold', size=big) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Expansions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand=listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('e', self.expand) #self._top.bind('<Alt-e>', self.expand) #self._top.bind('<Control-e>', self.expand) self._top.bind('m', self.match) self._top.bind('<Alt-m>', self.match) self._top.bind('<Control-m>', self.match) self._top.bind('b', self.backtrack) self._top.bind('<Alt-b>', self.backtrack) self._top.bind('<Control-b>', self.backtrack) self._top.bind('<Control-z>', self.backtrack) self._top.bind('<BackSpace>', self.backtrack) self._top.bind('a', self.autostep) #self._top.bind('<Control-a>', self.autostep) self._top.bind('<Control-space>', self.autostep) self._top.bind('<Control-c>', self.cancel_autostep) self._top.bind('<space>', self.step) self._top.bind('<Delete>', self.reset) self._top.bind('<Control-p>', self.postscript) #self._top.bind('<h>', self.help) #self._top.bind('<Alt-h>', self.help) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) #self._top.bind('<g>', self.toggle_grammar) #self._top.bind('<Alt-g>', self.toggle_grammar) #self._top.bind('<Control-g>', self.toggle_grammar) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button( buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step, ).pack(side='left') Button( buttonframe, text='Autostep', background='#90c0d0', foreground='black', command=self.autostep, ).pack(side='left') Button(buttonframe, text='Expand', underline=0, background='#90f090', foreground='black', command=self.expand).pack(side='left') Button(buttonframe, text='Match', underline=0, background='#90f090', foreground='black', command=self.match).pack(side='left') Button(buttonframe, text='Backtrack', underline=0, background='#f0a0a0', foreground='black', command=self.backtrack).pack(side='left') # Replace autostep... # self._autostep_button = Button(buttonframe, text='Autostep', # underline=0, command=self.autostep) # self._autostep_button.pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1, y1, x2, y2) self._redraw() def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame( parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Match', underline=0, command=self.match, accelerator='Ctrl-m') rulemenu.add_command(label='Expand', underline=0, command=self.expand, accelerator='Ctrl-e') rulemenu.add_separator() rulemenu.add_command(label='Backtrack', underline=0, command=self.backtrack, accelerator='Ctrl-b') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animation_frames, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animation_frames, value=10, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animation_frames, value=5, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animation_frames, value=2, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Helper ######################################### def _get(self, widget, treeloc): for i in treeloc: widget = widget.subtrees()[i] if isinstance(widget, TreeSegmentWidget): widget = widget.node() return widget ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old tree, widgets, etc. if self._tree is not None: self._cframe.destroy_widget(self._tree) for twidget in self._textwidgets: self._cframe.destroy_widget(twidget) if self._textline is not None: self._canvas.delete(self._textline) # Draw the tree. helv = ('helvetica', -self._size.get()) bold = ('helvetica', -self._size.get(), 'bold') attribs = { 'tree_color': '#000000', 'tree_width': 2, 'node_font': bold, 'leaf_font': helv, } tree = self._parser.tree() self._tree = tree_to_treesegment(canvas, tree, **attribs) self._cframe.add_widget(self._tree, 30, 5) # Draw the text. helv = ('helvetica', -self._size.get()) bottom = y = self._cframe.scrollregion()[3] self._textwidgets = [ TextWidget(canvas, word, font=self._font) for word in self._sent ] for twidget in self._textwidgets: self._cframe.add_widget(twidget, 0, 0) twidget.move(0, bottom - twidget.bbox()[3] - 5) y = min(y, twidget.bbox()[1]) # Draw a line over the text, to separate it from the tree. self._textline = canvas.create_line(-5000, y - 5, 5000, y - 5, dash='.') # Highlight appropriate nodes. self._highlight_nodes() self._highlight_prodlist() # Make sure the text lines up. self._position_text() def _redraw_quick(self): # This should be more-or-less sufficient after an animation. self._highlight_nodes() self._highlight_prodlist() self._position_text() def _highlight_nodes(self): # Highlight the list of nodes to be checked. bold = ('helvetica', -self._size.get(), 'bold') for treeloc in self._parser.frontier()[:1]: self._get(self._tree, treeloc)['color'] = '#20a050' self._get(self._tree, treeloc)['font'] = bold for treeloc in self._parser.frontier()[1:]: self._get(self._tree, treeloc)['color'] = '#008080' def _highlight_prodlist(self): # Highlight the productions that can be expanded. # Boy, too bad tkinter doesn't implement Listbox.itemconfig; # that would be pretty useful here. self._prodlist.delete(0, 'end') expandable = self._parser.expandable_productions() untried = self._parser.untried_expandable_productions() productions = self._productions for index in range(len(productions)): if productions[index] in expandable: if productions[index] in untried: self._prodlist.insert(index, ' %s' % productions[index]) else: self._prodlist.insert(index, ' %s (TRIED)' % productions[index]) self._prodlist.selection_set(index) else: self._prodlist.insert(index, ' %s' % productions[index]) def _position_text(self): # Line up the text widgets that are matched against the tree numwords = len(self._sent) num_matched = numwords - len(self._parser.remaining_text()) leaves = self._tree_leaves()[:num_matched] xmax = self._tree.bbox()[0] for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] widget['color'] = '#006040' leaf['color'] = '#006040' widget.move(leaf.bbox()[0] - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # Line up the text widgets that are not matched against the tree. for i in range(len(leaves), numwords): widget = self._textwidgets[i] widget['color'] = '#a0a0a0' widget.move(xmax - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # If we have a complete parse, make everything green :) if self._parser.currently_complete(): for twidget in self._textwidgets: twidget['color'] = '#00a000' # Move the matched leaves down to the text. for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0 dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10) leaf.move(0, dy) def _tree_leaves(self, tree=None): if tree is None: tree = self._tree if isinstance(tree, TreeSegmentWidget): leaves = [] for child in tree.subtrees(): leaves += self._tree_leaves(child) return leaves else: return [tree] ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._autostep = 0 self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset Application' self._lastoper2['text'] = '' self._redraw() def autostep(self, *e): if self._animation_frames.get() == 0: self._animation_frames.set(2) if self._autostep: self._autostep = 0 else: self._autostep = 1 self._step() def cancel_autostep(self, *e): #self._autostep_button['text'] = 'Autostep' self._autostep = 0 # Make sure to stop auto-stepping if we get any user input. def step(self, *e): self._autostep = 0 self._step() def match(self, *e): self._autostep = 0 self._match() def expand(self, *e): self._autostep = 0 self._expand() def backtrack(self, *e): self._autostep = 0 self._backtrack() def _step(self): if self._animating_lock: return # Try expanding, matching, and backtracking (in that order) if self._expand(): pass elif self._parser.untried_match() and self._match(): pass elif self._backtrack(): pass else: self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' self._autostep = 0 # Check if we just completed a parse. if self._parser.currently_complete(): self._autostep = 0 self._lastoper2['text'] += ' [COMPLETE PARSE]' def _expand(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.expand() if rv is not None: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = rv self._prodlist.selection_clear(0, 'end') index = self._productions.index(rv) self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = '(all expansions tried)' return 0 def _match(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.match() if rv is not None: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = rv self._animate_match(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = '(failed)' return 0 def _backtrack(self, *e): if self._animating_lock: return if self._parser.backtrack(): elt = self._parser.tree() for i in self._parser.frontier()[0]: elt = elt[i] self._lastoper1['text'] = 'Backtrack' self._lastoper2['text'] = '' if isinstance(elt, Tree): self._animate_backtrack(self._parser.frontier()[0]) else: self._animate_match_backtrack(self._parser.frontier()[0]) return 1 else: self._autostep = 0 self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' return 0 def about(self, *e): ABOUT = ("NLTK Recursive Descent Parser Application\n" + "Written by Edward Loper") TITLE = 'About: Recursive Descent Parser Application' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def help(self, *e): self._autostep = 0 # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size + 2))) self._redraw() ######################################### ## Expand Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' # def toggle_grammar(self, *e): # self._show_grammar = not self._show_grammar # if self._show_grammar: # self._prodframe.pack(fill='both', expand='y', side='left', # after=self._feedbackframe) # self._lastoper1['text'] = 'Show Grammar' # else: # self._prodframe.pack_forget() # self._lastoper1['text'] = 'Hide Grammar' # self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) old_frontier = self._parser.frontier() production = self._parser.expand(self._productions[index]) if production: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = production self._prodlist.selection_clear(0, 'end') self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.expandable_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Animation ######################################### def _animate_expand(self, treeloc): oldwidget = self._get(self._tree, treeloc) oldtree = oldwidget.parent() top = not isinstance(oldtree.parent(), TreeSegmentWidget) tree = self._parser.tree() for i in treeloc: tree = tree[i] widget = tree_to_treesegment(self._canvas, tree, node_font=self._boldfont, leaf_color='white', tree_width=2, tree_color='white', node_color='white', leaf_font=self._font) widget.node()['color'] = '#20a050' (oldx, oldy) = oldtree.node().bbox()[:2] (newx, newy) = widget.node().bbox()[:2] widget.move(oldx - newx, oldy - newy) if top: self._cframe.add_widget(widget, 0, 5) widget.move(30 - widget.node().bbox()[0], 0) self._tree = widget else: oldtree.parent().replace_child(oldtree, widget) # Move the children over so they don't overlap. # Line the children up in a strange way. if widget.subtrees(): dx = (oldx + widget.node().width() / 2 - widget.subtrees()[0].bbox()[0] / 2 - widget.subtrees()[0].bbox()[2] / 2) for subtree in widget.subtrees(): subtree.move(dx, 0) self._makeroom(widget) if top: self._cframe.destroy_widget(oldtree) else: oldtree.destroy() colors = [ 'gray%d' % (10 * int(10 * x / self._animation_frames.get())) for x in range(self._animation_frames.get(), 0, -1) ] # Move the text string down, if necessary. dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1] if dy > 0: for twidget in self._textwidgets: twidget.move(0, dy) self._canvas.move(self._textline, 0, dy) self._animate_expand_frame(widget, colors) def _makeroom(self, treeseg): """ Make sure that no sibling tree bbox's overlap. """ parent = treeseg.parent() if not isinstance(parent, TreeSegmentWidget): return index = parent.subtrees().index(treeseg) # Handle siblings to the right rsiblings = parent.subtrees()[index + 1:] if rsiblings: dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10 for sibling in rsiblings: sibling.move(dx, 0) # Handle siblings to the left if index > 0: lsibling = parent.subtrees()[index - 1] dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10) treeseg.move(dx, 0) # Keep working up the tree. self._makeroom(parent) def _animate_expand_frame(self, widget, colors): if len(colors) > 0: self._animating_lock = 1 widget['color'] = colors[0] for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = colors[0] else: subtree['color'] = colors[0] self._top.after(50, self._animate_expand_frame, widget, colors[1:]) else: widget['color'] = 'black' for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = 'black' else: subtree['color'] = 'black' self._redraw_quick() widget.node()['color'] = 'black' self._animating_lock = 0 if self._autostep: self._step() def _animate_backtrack(self, treeloc): # Flash red first, if we're animating. if self._animation_frames.get() == 0: colors = [] else: colors = ['#a00000', '#000000', '#a00000'] colors += [ 'gray%d' % (10 * int(10 * x / (self._animation_frames.get()))) for x in range(1, self._animation_frames.get() + 1) ] widgets = [self._get(self._tree, treeloc).parent()] for subtree in widgets[0].subtrees(): if isinstance(subtree, TreeSegmentWidget): widgets.append(subtree.node()) else: widgets.append(subtree) self._animate_backtrack_frame(widgets, colors) def _animate_backtrack_frame(self, widgets, colors): if len(colors) > 0: self._animating_lock = 1 for widget in widgets: widget['color'] = colors[0] self._top.after(50, self._animate_backtrack_frame, widgets, colors[1:]) else: for widget in widgets[0].subtrees(): widgets[0].remove_child(widget) widget.destroy() self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack(self, treeloc): widget = self._get(self._tree, treeloc) node = widget.parent().node() dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) / max(1, self._animation_frames.get())) self._animate_match_backtrack_frame(self._animation_frames.get(), widget, dy) def _animate_match(self, treeloc): widget = self._get(self._tree, treeloc) dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) / max(1, self._animation_frames.get())) self._animate_match_frame(self._animation_frames.get(), widget, dy) def _animate_match_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_frame, frame - 1, widget, dy) else: widget['color'] = '#006040' self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_backtrack_frame, frame - 1, widget, dy) else: widget.parent().remove_child(widget) widget.destroy() self._animating_lock = 0 if self._autostep: self._step() def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = string.join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sentence): self._sent = sentence.split() #[XX] use tagged? self.reset()
destState.grid(column=1 , row=1, sticky="nw") destState.state(['readonly']) destState.bind("<<ComboboxSelected>>", acceptStatesSelected) acceptStatesTextVariable=StringVar() acceptStatestEntry = ttk.Entry(innersampleFrame,width=4,textvariable=acceptStatesTextVariable) acceptStatestEntry.grid(column=1 , row=1, sticky="e") listFrame=ttk.LabelFrame(sampleFrame) listFrame.grid(column=0,row=1,sticky="ewns") scrollBar = Scrollbar(listFrame) scrollBar.pack(side=RIGHT, fill=Y) listBoxTop = Listbox(listFrame, selectmode=SINGLE,width=10,height=5) listBoxTop.pack(fill=BOTH) scrollBar.config(command=listBoxTop.yview) listBoxTop.config(yscrollcommand=scrollBar.set) sampleInputOption=Checkbutton(listFrame,text='Display Automata',variable=sInputCheck) sampleInputOption.pack(side=tk.LEFT, fill='x',anchor='w') sampleInputOption.bind('<ButtonRelease-1>',displaysampleAutomata) nb.add(master_bar, text="Sample Input") def generateSampleAutomata(): try: import time start_time=time.time() if len(samplePad.get())<2: tkMessageBox.showerror("Empty trace","Sample trace is empty.Please select a trace log.") return #try:
def create_widgets(): global list_box, canvas, label, zoom_label # root = Tk() # list_box = Listbox(root, exportselection=False) list_box.grid(row=0, column=0, rowspan=2, sticky=NS) cardsets_list = list(cardsets_dict) cardsets_list.sort() for cs in cardsets_list: list_box.insert(END, cs) list_box.bind('<<ListboxSelect>>', show_cardset) # sb = Scrollbar(root) sb.grid(row=0, column=1, rowspan=2, sticky=NS) list_box.config(yscrollcommand=sb.set) sb.config(command=list_box.yview) # canvas = Canvas(root, bg='#5eab6b') canvas.grid(row=0, column=2, sticky=NSEW) canvas.bind('<4>', lambda e: canvas.yview_scroll(-5, 'unit')) canvas.bind('<5>', lambda e: canvas.yview_scroll(5, 'unit')) # sb = Scrollbar(root) sb.grid(row=0, column=3, sticky=NS) canvas.config(yscrollcommand=sb.set) sb.config(command=canvas.yview) # if True: sb = Scrollbar(root, orient=HORIZONTAL) sb.grid(row=1, column=2, sticky=EW) canvas.config(xscrollcommand=sb.set) sb.config(command=canvas.xview) # label = Label(root) label.grid(row=2, column=0, columnspan=4) # b_frame = Frame(root) b_frame.grid(row=3, column=0, columnspan=4, sticky=EW) button = Button(b_frame, text='Quit', command=root.quit, width=8) button.pack(side=RIGHT) button = Button(b_frame, text='Info', command=show_info, width=8) button.pack(side=RIGHT) if Image: global rotate_var, filter_var rotate_var = IntVar(root) filter_var = StringVar(root) button = Button(b_frame, text=' + ', command=zoom_in) button.pack(side=LEFT) button = Button(b_frame, text=' - ', command=zoom_out) button.pack(side=LEFT) button = Button(b_frame, text=' = ', command=zoom_cancel) button.pack(side=LEFT) button = Checkbutton(b_frame, text='Rotate', indicatoron=0, selectcolor=b_frame['bg'], width=8, variable=rotate_var, command=show_cardset) button.pack(side=LEFT, fill='y') om = OptionMenu(b_frame, filter_var, 'NEAREST', 'BILINEAR', 'BICUBIC', 'ANTIALIAS', command=show_cardset) filter_var.set('NEAREST') om.pack(side=LEFT, fill='y') zoom_label = Label(b_frame) zoom_label.pack(side=LEFT) # root.columnconfigure(2, weight=1) root.rowconfigure(0, weight=1) root.title('Show Cardsets') return root
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 LeftNavView(Canvas): def __init__(self, controller, parent): # prev: def __init__(self, main_window, player_, left_nav): self.controller = controller self.parent = parent self.app = self.parent.app self.enabled = False def build(self): if self.enabled: self.redraw() else: self.build_left_nav_menu() self.enabled = True def build_left_nav_menu(self): app = self.app main_window = self.app.main_controller.view player = self.app.game.player # global left_nav, left_canvas, left left_nav = Frame(main_window, height=main_window.sh, width=200, background=app.conf.left_nav_background) left_nav.place(x=0, y=0) # left = LeftNav(main_window, player, left_nav) self.selected_planet = player.selected_planet if isset(player.selected_ship): self.selected_ship_name = player.selected_ship.name else: self.selected_ship_name = "" self.main_window = main_window self.selected_ship_id = 0 self.planet_images = [] self.left_canvas = Canvas(left_nav) self.left_canvas.config(background=app.conf.left_nav_background, highlightthickness=0, height=main_window.sh, width=200) self.left_canvas.place(x=0, y=0) if app.conf.debug_lines == 1: self.left_canvas.create_line(0, 0, 200, main_window.sh, fill='red') self.left_canvas.create_line(200, 0, 0, main_window.sh, fill='red') # left nav values self.logo_image = Image.open(app.conf.title_image_path) self.logo_image.thumbnail([198, 48], Image.ANTIALIAS) self.logo_image_res = ImageTk.PhotoImage(self.logo_image) self.new_planet_image = self.logo_image_res self.planet_images.append(self.new_planet_image) self.label_logo = Label(self.left_canvas, image=self.logo_image_res) self.label_logo.config(background=app.conf.left_nav_background) self.label_logo.planet_image_res = self.logo_image_res # keep a reference! self.label_logo.place(anchor='n', x=100, y=0) # Resources Set row = 0 self.resources_start_y = 55 self.resources_canvas = Canvas(self.left_canvas) self.resources_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.resources_canvas.grid_propagate(False) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) self.label_resources = Label(self.resources_canvas, text="Resources:", fg=app.conf.main_text_color) self.label_resources.config(background=app.conf.left_nav_background) self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets = Label(self.resources_canvas, text="Planets:", fg=app.conf.second_text_color) self.label_planets.config(background=app.conf.left_nav_background) self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val = Label(self.resources_canvas, text=str(len(player.owned_planets)) , fg=app.conf.second_text_color) self.label_planets_val.config(background=app.conf.left_nav_background) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships = Label(self.resources_canvas, text="Ships:", fg=app.conf.second_text_color) self.label_ships.config(background=app.conf.left_nav_background) self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val = Label(self.resources_canvas, text=len(player.ships), fg=app.conf.second_text_color) self.label_ships_val.config(background=app.conf.left_nav_background) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies = Label(self.resources_canvas, text="Allies:", fg=app.conf.second_text_color) self.label_allies.config(background=app.conf.left_nav_background) self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val = Label(self.resources_canvas, text=len(player.allies), fg=app.conf.second_text_color) self.label_allies_val.config(background=app.conf.left_nav_background) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies = Label(self.resources_canvas, text="Enemies:", fg=app.conf.second_text_color) self.label_enemies.config(background=app.conf.left_nav_background) self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val = Label(self.resources_canvas, text=len(player.enemies), fg=app.conf.second_text_color) self.label_enemies_val.config(background=app.conf.left_nav_background) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator = Label(self.resources_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator.config(background=app.conf.left_nav_background) self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas = Canvas(self.left_canvas) self.left_buttons_canvas.config(background=app.conf.left_nav_background, height=200, width=200, highlightthickness=0, border=0) self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet = Button(self.left_buttons_canvas, text="Next Planet", padx=60 , highlightbackground=app.conf.left_nav_background) self.button_next_ship = Button(self.left_buttons_canvas, text="Next Ship" , highlightbackground=app.conf.left_nav_background) self.button_home_planet = Button(self.left_buttons_canvas, text="Home Planet" , highlightbackground=app.conf.left_nav_background) self.button_end_turn = Button(self.left_buttons_canvas, text="End Turn" , highlightbackground=app.conf.left_nav_background) self.button_next_planet.bind("<Button-1>", self.controller.button_next_planet_clicked) self.button_next_ship.bind("<Button-1>", self.controller.button_next_ship_clicked) self.button_home_planet.bind("<Button-1>", self.controller.button_home_planet_clicked) self.button_end_turn.bind("<Button-1>", self.controller.button_end_turn_clicked) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas = Canvas(self.left_canvas) self.planet_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.planet_info_canvas.grid_propagate(False) self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info = Label(self.planet_info_canvas, text="Planet Info:", fg=app.conf.main_text_color) self.label_planet_info.config(background=app.conf.left_nav_background) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name = Label(self.planet_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_planet_name.config(background=app.conf.left_nav_background) self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val = Label(self.planet_info_canvas, text=str(player.selected_planet.name) , fg=app.conf.second_text_color) self.label_planet_name_val.config(background=app.conf.left_nav_background) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals = Label(self.planet_info_canvas, text="Metals:", fg=app.conf.second_text_color) self.label_planet_metals.config(background=app.conf.left_nav_background) self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val = Label(self.planet_info_canvas, text=str(player.selected_planet.metals) , fg=app.conf.second_text_color) self.label_planet_metals_val.config(background=app.conf.left_nav_background) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food = Label(self.planet_info_canvas, text="Food:", fg=app.conf.second_text_color) self.label_planet_food.config(background=app.conf.left_nav_background) self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val = Label(self.planet_info_canvas, text=str(player.selected_planet.food) , fg=app.conf.second_text_color) self.label_planet_food_val.config(background=app.conf.left_nav_background) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain = Label(self.planet_info_canvas, text="Terrain:", fg=app.conf.second_text_color) self.label_planet_terrain.config(background=app.conf.left_nav_background) self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val = Label(self.planet_info_canvas, text=str(get_terrain(player.selected_planet.terrain)) , fg=app.conf.second_text_color) self.label_planet_terrain_val.config(background=app.conf.left_nav_background) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p = Label(self.planet_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_p.config(background=app.conf.left_nav_background) self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if isset(self.selected_ship_name): if app.conf.debug == 1: print "Showing Selected Ship (init)" current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: if app.conf.debug == 1: print "No Selected Ship Detected (init)" row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=4, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') if app.conf.debug == 1: print "CreatedLine:", 0, " ", 0, " ", main_window.sw-200, " ", main_window.sh-200 print "CreatedLine:", main_window.sw-200, " ", 0, " ", 0, " ", main_window.sh-200 print "CurrWin0:", convert_coords_x(main_window, 0), convert_coords_y(main_window, 0) if app.conf.debug == 1: print "Displayed: left_nav,", main_window.sh, ",200" def poll_ship_list(self, event): w = event.widget index = int(w.curselection()[0]) new_ship_name = w.get(index) if isset(self.selected_ship_name): if self.selected_ship_name == "": if new_ship_name != self.selected_ship_name: self.ship_selction_has_changed(new_ship_name) self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() if app.conf.debug == 1: print "SelectedShip:", self.selected_ship_name self.redraw(self.main_window, self.player) else: self.selected_ship_name = new_ship_name self.selected_ship_id = w.curselection() self.app.debug(("SelectedShip:", self.selected_ship_name)) self.redraw() def redraw(self): app = self.app main_window = app.main_controller.view player = app.game.player self.player = player app.debug("Redrawing Left Nav") self.label_logo.place(anchor='n', x=100, y=0) self.resources_canvas.config(background=app.conf.left_nav_background, height=main_window.sh-self.resources_start_y-202, width=198, highlightthickness=0, border=0) self.resources_canvas.place(anchor='nw', x=0, y=self.resources_start_y) row = 0 self.label_resources.grid(row=row, column=0, sticky='w') row += 1 self.label_planets.grid(row=row, column=0, sticky='w') self.label_planets_val.config(text=str(len(player.owned_planets))) self.label_planets_val.grid(row=row, column=1, sticky='e') row += 1 self.label_ships.grid(row=row, column=0, sticky='w') self.label_ships_val.config(text=len(player.ships)) self.label_ships_val.grid(row=row, column=1, sticky='e') row += 1 self.label_allies.grid(row=row, column=0, sticky='w') self.label_allies_val.config(text=len(player.allies)) self.label_allies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_enemies.grid(row=row, column=0, sticky='w') self.label_enemies_val.config(text=len(player.enemies)) self.label_enemies_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator.grid(row=row, columnspan=2, sticky='e,w') # left nav buttons self.left_buttons_start_y = main_window.sh-112 if self.left_buttons_start_y < 500: self.left_buttons_start_y = 500 self.left_buttons_canvas.place(anchor='n', x=100, y=self.left_buttons_start_y) self.button_next_planet.grid(row=0, column=0, sticky='w,e') self.button_next_ship.grid(row=1, column=0, sticky='w,e') self.button_home_planet.grid(row=2, column=0, sticky='w,e') self.button_end_turn.grid(row=3, column=0, sticky='w,e') app.debug(("Left Buttons Start Y:", self.left_buttons_start_y)) # Planet Info Set row = 0 self.planet_info_start_y = self.resources_start_y + 115 self.planet_info_canvas.place(anchor='nw', x=0, y=self.planet_info_start_y) self.label_planet_info.grid(row=row, column=0, sticky='w') row += 1 self.label_planet_name.grid(row=row, column=0, sticky='w') self.label_planet_name_val.config(text=str(player.selected_planet.name)) self.label_planet_name_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_metals.grid(row=row, column=0, sticky='w') self.label_planet_metals_val.config(text=str(player.selected_planet.metals)) self.label_planet_metals_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_food.grid(row=row, column=0, sticky='w') self.label_planet_food_val.config(text=str(player.selected_planet.food)) self.label_planet_food_val.grid(row=row, column=1, sticky='e') row += 1 self.label_planet_terrain.grid(row=row, column=0, sticky='w') self.label_planet_terrain_val.config(text=str(get_terrain(player.selected_planet.terrain))) self.label_planet_terrain_val.grid(row=row, column=1, sticky='e') row += 1 self.label_separator_p.grid(row=row, columnspan=2, sticky='e,w') # prep for ship section if isset(self.ship_select_canvas): self.ship_select_canvas.destroy() # ship info row = 0 self.ship_select_start_y = self.planet_info_start_y + 115 self.ship_select_canvas = Canvas(self.left_canvas) self.ship_select_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_select_canvas.grid_propagate(False) self.ship_select_canvas.place(anchor='nw', x=0, y=self.ship_select_start_y) self.label_ship_select = Label(self.ship_select_canvas, text="Select Ship:", fg=app.conf.main_text_color) self.label_ship_select.config(background=app.conf.left_nav_background) self.label_ship_select.grid(row=row, column=0, sticky='w') # future implementation # if selected_ship.name != '': if self.selected_ship_name != "": app.debug("Showing Selected Ship (redraw)") current_ship = player.get_ship(self.selected_ship_name) row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) self.listbox_ship.config(selectmode=SINGLE) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.selection_set(self.selected_ship_id) self.listbox_ship.grid(row=row, columnspan=4, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row = 0 self.ship_info_start_y = self.ship_select_start_y + 200 self.ship_info_canvas = Canvas(self.left_canvas) self.ship_info_canvas.config(background=app.conf.left_nav_background, width=198, highlightthickness=0, border=0) self.ship_info_canvas.grid_propagate(False) self.ship_info_canvas.place(anchor='nw', x=0, y=self.ship_info_start_y) self.label_ship_info = Label(self.ship_info_canvas, text="Ship Info:", fg=app.conf.main_text_color) self.label_ship_info.config(background=app.conf.left_nav_background) self.label_ship_info.grid(row=row, column=0, sticky='w') row += 1 self.label_ship_name = Label(self.ship_info_canvas, text="Name:", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_name_val = Label(self.ship_info_canvas, text=current_ship.name , fg=app.conf.second_text_color) self.label_ship_name_val.config(background=app.conf.left_nav_background) self.label_ship_name_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_attack = Label(self.ship_info_canvas, text="Attack:", fg=app.conf.second_text_color) self.label_ship_attack.config(background=app.conf.left_nav_background) self.label_ship_attack.grid(row=row, column=0, sticky='w') self.label_ship_attack_val = Label(self.ship_info_canvas, text=current_ship.attack , fg=app.conf.second_text_color) self.label_ship_attack_val.config(background=app.conf.left_nav_background) self.label_ship_attack_val.grid(row=row, column=1, sticky='e') self.label_ship_defense = Label(self.ship_info_canvas, text="Defense:", fg=app.conf.second_text_color) self.label_ship_defense.config(background=app.conf.left_nav_background) self.label_ship_defense.grid(row=row, column=2, sticky='w') self.label_ship_defense_val = Label(self.ship_info_canvas, text=current_ship.defense , fg=app.conf.second_text_color) self.label_ship_defense_val.config(background=app.conf.left_nav_background) self.label_ship_defense_val.grid(row=row, column=3, sticky='e') row += 1 self.label_ship_storage = Label(self.ship_info_canvas, text="Storage:", fg=app.conf.second_text_color) self.label_ship_storage.config(background=app.conf.left_nav_background) self.label_ship_storage.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_storage_val = Label(self.ship_info_canvas, text=current_ship.storage , fg=app.conf.second_text_color) self.label_ship_storage_val.config(background=app.conf.left_nav_background) self.label_ship_storage_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_ship_seats = Label(self.ship_info_canvas, text="Seats:", fg=app.conf.second_text_color) self.label_ship_seats.config(background=app.conf.left_nav_background) self.label_ship_seats.grid(row=row, column=0, columnspan=2, sticky='w') self.label_ship_seats_val = Label(self.ship_info_canvas, text=current_ship.seats , fg=app.conf.second_text_color) self.label_ship_seats_val.config(background=app.conf.left_nav_background) self.label_ship_seats_val.grid(row=row, column=2, columnspan=2, sticky='e') row += 1 self.label_separator_s = Label(self.ship_info_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w') else: app.debug("No Selected Ship Detected (redraw)") row += 1 self.listbox_ship = Listbox(self.ship_select_canvas, width=198 , background=app.conf.alternate_left_nav_background, borderwidth=1) for ship in player.ships: self.listbox_ship.insert(END, ship.name) self.listbox_ship.grid(row=row, columnspan=2, sticky='w,e') self.listbox_ship.bind('<<ListboxSelect>>', self.poll_ship_list) row += 1 self.label_ship_name = Label(self.ship_select_canvas, text="No Ship Selected", fg=app.conf.second_text_color) self.label_ship_name.config(background=app.conf.left_nav_background) self.label_ship_name.grid(row=row, columnspan=2, sticky='w') row += 1 self.label_separator_s = Label(self.ship_select_canvas, text="", fg=app.conf.left_nav_background, width=24) self.label_separator_s.config(background=app.conf.left_nav_background) self.label_separator_s.grid(row=row, columnspan=4, sticky='e,w')
class StatePopup(object): def __init__(self, master, default_value, state_probs): top = self.top = Toplevel(master.canvas) self.master = master self.l = Label(top, text="New State") self.l.grid(row=0, column=0, columnspan=2) self.lb = Listbox( top ) # OptionMenu(top, Tkinter.StringVar().set(self.states[-1]), *self.states) self.lb.insert("end", "0") for i, (state, color) in enumerate(self.master.trail.colorlist.items()): str = ",".join(["{:x}".format(x) for x in state]) self.lb.insert("end", str) self.lb.itemconfig(i + 1, {"bg": color}) self.lb.grid(row=1, column=1, padx=MARGIN_LR / 2, pady=MARGIN_TB) self.lb.config(height=5, width=8) self.lb.bind( "<Double-Button-1>", lambda x: self.set_text(self.lb.get(self.lb.curselection()))) self.e = Entry(top) self.e.insert(0, default_value) self.e.bind("<Control-KeyRelease-a>", lambda x: self.select_all()) self.e.grid(row=1, column=0, sticky=N, padx=MARGIN_LR / 2, pady=MARGIN_TB) self.e.select_range(0, 'end') self.e.icursor('end') self.e.focus() self.b = Button(top, text='Ok', command=self.check_cleanup) self.top.protocol("WM_DELETE_WINDOW", self.close) self.b.grid(row=3, column=0, columnspan=2) self.l2 = Label(top, text="Probabilities") self.l2.grid(row=4, column=0, columnspan=2) for i, x in enumerate(state_probs): # if x > 0: # l = Label(top, text=hex(i)[2:] + ":" + str(x)) # l.pack() pass self.top.bind("<Return>", lambda x: self.check_cleanup()) self.top.bind("<Escape>", lambda x: self.close()) self.value = None self.top.wait_visibility() # stop interaction in other gui self.top.grab_set() def set_text(self, text): self.e.delete(0, 'end') self.e.insert(0, text) def select_all(event): event.e.select_range(0, 'end') # move cursor to the end event.e.icursor('end') return 'break' def check_cleanup(self): newstate = self.e.get() if newstate == "": self.value = range( 0, 2**(self.master.trail.statebitsize / self.master.trail.statesize)) elif newstate == "*": self.value = range( 1, 2**(self.master.trail.statebitsize / self.master.trail.statesize)) else: try: state = [] for x in newstate.split(","): x = x.strip() x = int(x, 16) assert x < 2**(self.master.trail.statebitsize / self.master.trail.statesize) state.append(x) assert len(state) > 0 self.value = state except Exception as e: print "Exception: " + str(e) self.value = None return self.close() def close(self): self.top.grab_release() self.top.destroy()
class ArduinoSetup: def __init__(self, master, args): self.master = master self.master.minsize(width=360, height=600) self.master.title(PROJECT_TEXT) # GUI PROPS self.padXOut = 5 self.padYOut = 3 self.padXIn = 5 self.padYIn = 3 self.frameRelief = GROOVE self.frameBorder = 2 self.infoFG = "teal" self.selectBG = "teal" self.textBG = "white" self.errorBG = "red" self.vAction = StringVar() if args.verify: self.vAction.set("--verify") elif args.upload: self.vAction.set("--upload") else: self.vAction.set("") self.verify = args.verify self.upload = args.upload self.vPath = StringVar() self.vPath.set(args.arduino) self.vBoard = StringVar() self.vBoard.set(args.board) self.vPort = StringVar() self.vPort.set(args.port) self.vFile = StringVar() self.vFile.set(args.file) # GUI WIDGETS self.errorPath = True self.errorBoard = True self.errorPort = True self.errorFile = True self.enablePath = True self.enableBoard = True self.enablePort = True self.enableFile = True if self.vPath.get() != "": self.enablePath = False if self.vBoard.get() != "": self.enableBoard = False if self.vPort.get() != "": self.enablePort = False if self.vFile.get() != "": self.enableFile = False if self.enablePath: optArdu = {} optArdu["defaultextension"] = ".exe" optArdu["filetypes"] = [("exe files", ".exe"), ("all files", ".*")] # options['initialdir'] = 'C:\\' optArdu["initialfile"] = "arduino.exe" optArdu["parent"] = master optArdu["title"] = "Open arduino.exe" if system() == WINDOWS: pathexample = """Example: C:/Program Files/Arduino/arduino.exe""" else: pathexample = """Location of arduino executable""" self.vcmdPath = master.register(self.validatePath) self.framePath = LabelFrame(master, text="Arduino.exe path:", bd=self.frameBorder, relief=self.frameRelief) self.entryPath = Entry( self.framePath, bg=self.textBG, validate="all", validatecommand=(self.vcmdPath, "%P"), textvar=self.vPath, selectbackground=self.selectBG, ) self.entryPath.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.buttonPath = Button( self.framePath, text="Find arduino...", command=lambda: self.openPath(optArdu, self.vPath) ) self.buttonPath.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelPathInfo = Label(self.framePath, fg=self.infoFG, text=pathexample) self.labelPathInfo.pack(fill=X) self.framePath.pack(fill=X, padx=self.padXOut, pady=self.padYOut) if self.enableBoard: self.vcmdBoard = master.register(self.validateBoard) self.frameBoard = LabelFrame(master, text="Board:", bd=self.frameBorder, relief=self.frameRelief) self.entryBoard = Entry( self.frameBoard, bg=self.textBG, validate="all", validatecommand=(self.vcmdBoard, "%P"), textvar=self.vBoard, selectbackground=self.selectBG, ) self.entryBoard.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelBoardInfo = Label(self.frameBoard, fg=self.infoFG, text="""package:arch:board[:parameters]""") self.labelBoardInfo.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.textBoardExample = Text(self.frameBoard, fg=self.infoFG, width=50, height=6) self.textBoardExample.insert( END, """Packages: arduino, sparkfun, ... Arch: avr, sam, ... Boards: uno, mega, promicro, ... Parameters: cpu=CPU, ... Example: arduino:avr:nano:cpu=atmega168 SparkFun:avr:promicro:cpu=8MHzatmega32U4""", ) self.textBoardExample.config(state=DISABLED) self.textBoardExample.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.frameBoard.pack(fill=X, padx=self.padXOut, pady=self.padYOut) if self.enablePort: self.framePort = LabelFrame(master, text="Port:", bd=self.frameBorder, relief=self.frameRelief) if system() == WINDOWS: self.ports = serial_ports() # only for testing # self.ports.append(("COM", "Device 123")) self.frameListbox = Frame(self.framePort) scrollbar = Scrollbar(self.frameListbox) scrollbar.pack(side=RIGHT, fill=Y) self.listboxPort = Listbox( self.frameListbox, height=2, bg=self.textBG, selectbackground=self.selectBG, yscrollcommand=scrollbar.set, ) scrollbar.config(command=self.listboxPort.yview) self.listboxPort.insert(END, *self.ports) self.listboxPort.pack(fill=BOTH, expand=1) self.listboxPort.bind("<<ListboxSelect>>", self.portSelected) self.frameListbox.pack(fill=BOTH, expand=1, padx=self.padXIn, pady=self.padYIn) self.labelPortInfo = Label(self.framePort, fg=self.infoFG, text="port | port name | device name") self.labelPortInfo.pack(side=BOTTOM, fill=X, padx=self.padXIn, pady=self.padYIn) else: self.vcmdPort = master.register(self.validatePort) self.entryPort = Entry( self.framePort, bg=self.textBG, validate="all", validatecommand=(self.vcmdPort, "%P"), textvar=self.vPort, selectbackground=self.selectBG, ) self.entryPort.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelPortInfo = Label(self.framePort, fg=self.infoFG, text="""Example: /dev/ttyUSB0""") self.labelPortInfo.pack(side=BOTTOM, fill=X, padx=self.padXIn, pady=self.padYIn) self.framePort.pack(fill=BOTH, expand=1, padx=self.padXOut, pady=self.padYOut) if self.enableFile: optFile = {} optFile["defaultextension"] = ".ino" optFile["filetypes"] = [("arduino source files", ".ino"), ("all files", ".*")] # options['initialdir'] = 'C:\\' optFile["initialfile"] = "" optFile["parent"] = master optFile["title"] = "Open arduino source code" self.vcmdFile = master.register(self.validateFile) self.frameFile = LabelFrame(master, text="Source code path:", bd=self.frameBorder, relief=self.frameRelief) self.entryFile = Entry( self.frameFile, bg=self.textBG, validate="all", validatecommand=(self.vcmdFile, "%P"), textvar=self.vFile, selectbackground=self.selectBG, ) self.entryFile.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.buttonFile = Button( self.frameFile, text="Find source code...", command=lambda: self.openPath(optFile, self.vFile) ) self.buttonFile.pack(fill=X, padx=self.padXIn, pady=self.padYIn) self.labelFileInfo = Label( self.frameFile, fg=self.infoFG, text="""Source code to compile (file extension .ino)""" ) self.labelFileInfo.pack(fill=X) self.frameFile.pack(fill=X, padx=self.padXOut, pady=self.padYOut) # BOTTOM side items (reversed order) self.frameAbout = Frame(master, cursor="heart") self.labelAbout = Label(self.frameAbout, text=COPYRIGHT_TEXT, fg=self.infoFG) self.labelAbout.pack(side=LEFT) self.buttonAbout = Button( self.frameAbout, text="About app...", fg=self.infoFG, command=self.openAboutBox, borderwidth=1 ) self.buttonAbout.pack(side=RIGHT) self.frameAbout.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) if self.vAction.get() != "": self.buttonContinue = Button(master, text="Continue", command=self.doContinue) self.buttonContinue.pack(fill=X, padx=self.padXOut, pady=self.padYOut) else: if self.verify is False: self.buttonVerify = Button(master, text="Verify", command=self.doVerify) self.buttonVerify.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) if self.upload is False: self.buttonUpload = Button(master, text="Upload", command=self.doUpload) self.buttonUpload.pack(side=BOTTOM, fill=X, padx=self.padXOut, pady=self.padYOut) def openAboutBox(self): dialog = AboutDialog(self.master) def portSelected(self, P): self.errorPort = False self.listboxPort.config(bg=self.textBG) try: porti = map(int, self.listboxPort.curselection())[0] self.vPort.set(self.ports[porti][0]) except (IndexError): self.errorPort = True self.listboxPort.config(bg=self.errorBG) # only for linux def validatePort(self, P): if self.vPort.get() == "" and P == "": self.errorPort = True self.entryPort.config(bg=self.errorBG) return False else: self.errorPort = False self.entryPort.config(bg=self.textBG) return True def validatePath(self, P): if self.vPath.get() == "" and P == "": self.errorPath = True self.entryPath.config(bg=self.errorBG) return False else: self.errorPath = False self.entryPath.config(bg=self.textBG) return True def validateBoard(self, P): if self.vBoard.get() == "" and P == "": self.errorBoard = True self.entryBoard.config(bg=self.errorBG) return False else: self.errorBoard = False self.entryBoard.config(bg=self.textBG) return True def validateFile(self, P): if self.vFile.get() == "" and P == "": self.errorFile = True self.entryFile.config(bg=self.errorBG) return False else: self.errorFile = False self.entryFile.config(bg=self.textBG) return True def openPath(self, opt, sv): sv.set(tkFileDialog.askopenfilename(**opt)) def doVerify(self): self.vAction.set("--verify") self.doContinue() def doUpload(self): self.vAction.set("--upload") self.doContinue() def doContinue(self): if self.enablePath: self.validatePath(self.vPath.get()) else: self.errorPath = False if self.enableBoard: self.validateBoard(self.vBoard.get()) else: self.errorBoard = False if self.enableFile: self.validateFile(self.vFile.get()) else: self.errorFile = False if self.enablePort and system() != WINDOWS: print self.vPort.get() self.validatePort(self.vPort.get()) else: self.errorPort = False self.doAction() def doAction(self): result = 3 if self.errorPath or self.errorBoard or self.errorPort or self.errorFile: print "something missing" return command = '"' command += self.vPath.get() command += '" ' + self.vAction.get() command += " --board " + self.vBoard.get() command += " --port " + self.vPort.get() command += " --verbose" command += ' "' + self.vFile.get() command += '"' print "command:", command print "Please wait ..." sys.stdout.flush() self.master.destroy() p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() print output result = p.returncode
class App(Frame): def __init__(self, master, settings): self.master = master self.settings = settings Frame.__init__(self, master, relief=SUNKEN, bd=2) self.master.protocol('WM_DELETE_WINDOW', self.quitApp) self.objNumber = 1 self.modified = False self.preview = True self.lbMap = [] self.lbSelection = None self.stlFrame = StlFrame(self, scale=settings.scale) self.stlFrame.grid(row=1, column=1, rowspan=4, sticky=N) self.lbFrame = LabelFrame(self, text=" File List ") self.lbFrame.grid(row=1, column=2, padx=5, pady=5, sticky=N) self.bFrame = Frame(self) self.bFrame.grid(row=2, column=2, padx=5, sticky=N) self.lbFiles = Listbox(self.lbFrame, width=60) self.lbFiles.grid(row=1,column=1,sticky=N+E+W+S) self.sbFiles = Scrollbar(self.lbFrame, command=self.lbFiles.yview, orient="vertical") self.sbFiles.grid(column=2, row=1, sticky=N+S+E) self.lbFiles.config(yscrollcommand=self.sbFiles.set) self.lbFiles.bind("<ButtonRelease>", self.doClickList) self.imgAdd = self.loadImage("add.gif") self.bAdd = Button(self.bFrame, image=self.imgAdd, width=48, height=48, command=self.doAdd) self.bAdd.grid(row=1, column=1, pady=2, padx=2, sticky=N) createToolTip(self.bAdd, "Add an STL file to the plate") self.imgClone = self.loadImage("clone.gif") self.bClone = Button(self.bFrame, image=self.imgClone, width=48, height=48, command=self.doClone, state=DISABLED) self.bClone.grid(row=1, column=2, pady=2, padx=2, sticky=N) createToolTip(self.bClone, "Clone the selected object") self.imgDel = self.loadImage("del.gif") self.bDel = Button(self.bFrame, image=self.imgDel, width=48, height=48, command=self.doDelete, state=DISABLED) self.bDel.grid(row=1, column=3, pady=2, padx=2, sticky=N) createToolTip(self.bDel, "Delete the selected object") self.imgDelAll = self.loadImage("delall.gif") self.bDelAll = Button(self.bFrame, image=self.imgDelAll, width=48, height=48, command=self.doDelAll, state=DISABLED) self.bDelAll.grid(row=1, column=4, pady=2, padx=2, sticky=N) createToolTip(self.bDelAll, "Delete all objects from the plate") self.imgArrange = self.loadImage("arrange.gif") self.bArrange = Button(self.bFrame, image=self.imgArrange, width=48, height=48, command=self.doArrange, state=DISABLED) self.bArrange.grid(row=2, column=1, pady=2, padx=2, sticky=N) createToolTip(self.bArrange, "Arrange the objects to fit") self.imgExport = self.loadImage("export.gif") self.bExport = Button(self.bFrame, image=self.imgExport, width=48, height=48, command=self.doExport, state=DISABLED) self.bExport.grid(row=2, column=4, pady=2, padx=2, sticky=N) createToolTip(self.bExport, "Save the plate to an STL file") self.cbPrev = IntVar() if self.settings.preview: self.cbPrev.set(1) else: self.cbPrev.set(0) self.cbPreview = Checkbutton( self.bFrame, text="Preview", variable=self.cbPrev, command=self.doCbPreview) self.cbPreview.grid(row=3, column=2, pady=5) def doCbPreview(self): if self.cbPrev.get() == 0: self.preview = False else: self.preview = True self.settings.preview = self.preview self.settings.setModified() def loadImage(self, fn): return PhotoImage(file=os.path.join(cmd_folder, "images", fn)) def checkModified(self): if self.modified: if not askyesno("Exit?", "Lose unsaved changes?"): return True return False def quitApp(self): if self.checkModified(): return False self.destroy() self.master.quit() return True def doAdd(self): while True: confirmed = False fn = askopenfilename(filetypes=[("STL files", "*.stl")], initialdir=self.settings.lastdirectory) if fn: if self.preview: subprocess.Popen([self.settings.viewer, fn]) if askyesno("Confirm Add", "Add this object?"): confirmed = True else: confirmed = True else: return if confirmed: self.modified = True self.filename = fn dn = os.path.dirname(fn) if dn != self.settings.lastdirectory: self.settings.lastdirectory = dn self.settings.setModified() name = "OBJECT%03d" % self.objNumber index = self.lbFiles.index(END) self.lbFiles.insert(END, "%2d: %s" % (self.objNumber, fn)) if self.lbSelection is not None: self.lbFiles.selection_clear(self.lbSelection) self.lbFiles.selection_set(index) self.lbSelection = index self.objNumber += 1 stlFile = stltool.stl(filename=fn, name=name) self.lbMap.append(stlFile) self.stlFrame.addStl(stlFile, highlight=True) self.bDel.config(state=NORMAL) self.bDelAll.config(state=NORMAL) self.bExport.config(state=NORMAL) self.bArrange.config(state=NORMAL) self.bClone.config(state=NORMAL) return def doClone(self): stlObj = self.stlFrame.getSelectedStl() if stlObj is None: return name = "OBJECT%03d" % self.objNumber index = self.lbFiles.index(END) self.lbFiles.insert(END, "%2d: %s" % (self.objNumber, stlObj.filename)) if self.lbSelection is not None: self.lbFiles.selection_clear(self.lbSelection) self.lbFiles.selection_set(index) self.lbSelection = index self.objNumber += 1 s = stlObj.clone(name=name) self.lbMap.append(s) self.stlFrame.addStl(s, highlight=True) def doDelete(self): self.modified = True if self.lbSelection is not None: del self.lbMap[self.lbSelection] self.lbFiles.delete(self.lbSelection) self.lbSelection = None self.stlFrame.delStl() if self.stlFrame.countObjects() == 0: self.modified = False self.bDel.config(state=DISABLED) self.bDelAll.config(state=DISABLED) self.bExport.config(state=DISABLED) self.bArrange.config(state=DISABLED) self.bClone.config(state=DISABLED) def doDelAll(self): if askyesno("Confirm Delete All", "Are you sure you want to delete all objects?"): self.modified = False self.stlFrame.delAll() self.bDel.config(state=DISABLED) self.bDelAll.config(state=DISABLED) self.bExport.config(state=DISABLED) self.bArrange.config(state=DISABLED) self.bClone.config(state=DISABLED) self.lbFiles.delete(0, END) self.lbMap = [] self.lbSelection = None self.objNumber = 1 def doExport(self): self.stlFrame.commit() objs = self.stlFrame.getStls() facets = [] for o in objs: facets.extend(o.facets) fn = asksaveasfilename(parent=self, title="Export to File", filetypes=[("STL files", "*.stl")], initialdir=self.settings.lastdirectory, defaultextension=".stl") if not fn: return stltool.emitstl(fn, facets=facets, objname="PlaterObject", binary=False) self.modified = False def setModified(self, flag=True): self.modified = flag def setSelection(self, stlObj): found = False for i in range(len(self.lbMap)): o = self.lbMap[i] if o.name == stlObj.name: found = True break if not found: return if self.lbSelection is not None: self.lbFiles.selection_clear(self.lbSelection) self.lbFiles.selection_set(i) self.lbSelection = i def doClickList(self, *arg): items = self.lbFiles.curselection() try: i = int(items[0]) except: return if i < 0 or i >= len(self.lbMap): return self.stlFrame.setSelectionByName(self.lbMap[i].name) def doArrange(self): self.stlFrame.arrange()
class FirmwareParms: def __init__(self, app, prtr, settings, log): self.app = app self.printer = prtr self.settings = settings self.log = log self.readingFirmware = False self.reportOnly = False self.top = None self.parameters = {} self.groups = {} groups = [] for s in FirmwareSettings: grp = s.split('_')[0] if grp not in groups: if grp not in grporder: print "Unknown group: %s" % grp else: groups.append(grp) g = self.groups[grp] = paramGroup(grp, grpinfo[grp][GRPLABEL]) else: g = self.groups[grp] p = self.parameters[s] = param(s, pinfo[s][PLABEL], eepVal = self.settings.firmware[s], width=pinfo[s][PWIDTH]) g.addParam(p) def isActive(self): return self.top != None def start(self, reportOnly=False): self.got92 = False self.got201 = False self.got203 = False self.got204 = False self.got205 = False self.got206 = False self.got301 = False self.reportOnly = reportOnly self.app.readingFirmware = True self.printer.send_now("M503") def checkComplete(self): if self.got92 and self.got201 and self.got203 and self.got204 and self.got204 and self.got206 and self.got301: self.app.readingFirmware = False; self.app.event_generate(MWM_FIRMWARECOMPLETE) return True else: return False def m92(self, x, y, z, e): self.parameters['m92_x'].setFlash(x) self.parameters['m92_y'].setFlash(y) self.parameters['m92_z'].setFlash(z) self.parameters['m92_e'].setFlash(e) self.got92 = True return self.checkComplete() def m201(self, x, y, z, e): self.parameters['m201_x'].setFlash(x) self.parameters['m201_y'].setFlash(y) self.parameters['m201_z'].setFlash(z) self.parameters['m201_e'].setFlash(e) self.got201 = True return self.checkComplete() def m203(self, x, y, z, e): self.parameters['m203_x'].setFlash(x) self.parameters['m203_y'].setFlash(y) self.parameters['m203_z'].setFlash(z) self.parameters['m203_e'].setFlash(e) self.got203 = True return self.checkComplete() def m204(self, s, t): self.parameters['m204_s'].setFlash(s) self.parameters['m204_t'].setFlash(t) self.got204 = True return self.checkComplete() def m205(self, s, t, b, x, z, e): self.parameters['m205_s'].setFlash(s) self.parameters['m205_t'].setFlash(t) self.parameters['m205_b'].setFlash(b) self.parameters['m205_x'].setFlash(x) self.parameters['m205_z'].setFlash(z) self.parameters['m205_e'].setFlash(e) self.got205 = True return self.checkComplete() def m206(self, x, y, z): self.parameters['m206_x'].setFlash(x) self.parameters['m206_y'].setFlash(y) self.parameters['m206_z'].setFlash(z) self.got206 = True return self.checkComplete() def m301(self, p, i, d): self.parameters['m301_p'].setFlash(p) self.parameters['m301_i'].setFlash(i) self.parameters['m301_d'].setFlash(d) self.got301 = True return self.checkComplete() def reportComplete(self): if self.reportOnly: return self.parameters if self.top != None: self.updateFlashDisplay() if self.readingFirmware: self.readingFirmware = False for s in FirmwareSettings: p = self.parameters[s] v = p.getFlash() p.setEEProm(v) self.settings.firmware[s] = v self.settings.setModified() self.updateEEPromDisplay() return None self.top = Toplevel(self.app) self.top.protocol('WM_DELETE_WINDOW', self.delTop) self.top.title("Firmware Parameters") gf = LabelFrame(self.top, text="") gf.grid(row=1, column=1, rowspan=len(grporder), padx=10, pady=10, sticky=N+S+E+W) l = Label(gf, text="Profiles:") l.grid(row=1, column=1, columnspan=2, pady=10) self.profList = Listbox(gf) self.profList.grid(row=2, column=1, columnspan=2, sticky=N+S+E+W) self.yScroll = Scrollbar (gf, orient=VERTICAL) self.yScroll.grid (row=2, column=3, sticky=N+S) self.profList.config(yscrollcommand=self.yScroll.set) self.yScroll.config(command=self.profList.yview) self.profList.bind('<ButtonRelease-1>', self.profSel) l = Label(gf, text=" ") l.grid(row=3, column=1, columnspan=2, pady=10) l = Label(gf, text="New Profile Name") l.grid(row=4, column=1, columnspan=2) self.newProf = Entry(gf, width=12) self.newProf.grid(row=5, column=1, columnspan=2) self.cbOWrite = IntVar() self.cbOverWrite = Checkbutton(gf, text="Over-Write", variable=self.cbOWrite) self.cbOverWrite.grid(row=6, column=1, sticky=W) self.bSave = Button(gf, width=12, text="Save", command = self.doSave) self.bSave.grid(row=6, column=2) l = Label(gf, text=" ") l.grid(row=7, column=1, columnspan=2, pady=10) self.cbCDel = IntVar() self.cbConfirmDelete = Checkbutton(gf, text="Delete", variable=self.cbCDel, command=self.cbDoConfirmDelete, state=DISABLED) self.cbConfirmDelete.grid(row=8, column=1, sticky=W) self.bDel = Button(gf, width=12, text="Delete", command = self.doDelete, state=DISABLED) self.bDel.grid(row=8, column=2) gf = LabelFrame(self.top, text="") gf.grid(row=len(grporder)+1, column=1, sticky=N+S+E+W, padx=10) self.bToEEProm = Button(gf, text='Copy Flash -> EEPROM', command=self.doFlashToEEProm, width = 20) self.bToEEProm.place(relx=0.5, rely=0.5, y=-20, anchor=CENTER) self.bFromEEProm = Button(gf, text='Copy EEPROM -> Flash', command=self.doEEPromToFlash, width = 20) self.bFromEEProm.place(relx=0.5, rely=0.5, y=20, anchor=CENTER) self.entryWidgets = {} self.buttons = {} self.allButtons = {} self.flashWidgets = {} self.eepromWidgets = {} f = Frame(self.top) f.grid(row=1, column=2, columnspan=4, sticky=N+W+E+W) t = Label(f, text="Flash EEProm", width=68, anchor=E) t.grid(row=1, column=1, sticky=E) Row = 2 for g in grporder: glf = LabelFrame(self.top, text=self.groups[g].getLabel(), width=10, height=10) glf.grid(row=Row, column = 2, columnspan=4, sticky=N+W+E+S) gRow = 1 for p in self.groups[g]: t = Label(glf, text=p.getLabel(), width=18, anchor=E) t.grid(row=gRow, column=1) w = self.entryWidgets[p.getTag()] = Entry(glf, width=10, justify=RIGHT) w.grid(row=gRow, column=2) w = self.buttons[p.getTag()] = Button(glf, text="->", width=2, height=1, command=lambda prm=p: self.profButton(prm)) w.grid(row=gRow, column=3) l = Label(glf, text=p.displayFlash(), width=14, anchor=E) l.grid(row=gRow, column=5) self.flashWidgets[p.getTag()] = l l = Label(glf, text=p.displayEEProm(), width=14, anchor=E) l.grid(row=gRow, column=6) self.eepromWidgets[p.getTag()] = l gRow += 1 w = self.allButtons[g] = Button(glf, text="All\n->", command=lambda prm=g: self.allButton(self.groups[prm])) w.grid(row=1, column=4, rowspan=gRow-1, sticky=N+E+W+S) Row += 1 self.loadProfiles() self.top.geometry("850x920+50+50") return None def loadProfiles(self, name=None): self.profList.delete(0, END) self.profList.insert(END, EMPTY) self.profiles = self.settings.getProfiles() match = 0 px = 1 for pn in self.profiles: self.profList.insert(END, pn) if pn == name: match = px px += 1 self.profList.selection_set(match) self.profSel() def cbDoConfirmDelete(self): if self.cbCDel.get() == 1: self.bDel.config(state=NORMAL) else: self.bDel.config(state=DISABLED) def doDelete(self): try: item = int(self.profList.curselection()[0]) except: item = 0 if item == 0: return prof = self.profiles[item-1] self.settings.delProfile(prof) self.loadProfiles() def profSel(self, *arg): try: item = int(self.profList.curselection()[0]) except: item = 0 if item == 0: self.cbConfirmDelete.config(state=DISABLED) self.bDel.config(state=DISABLED) for s in FirmwareSettings: p = self.parameters[s] p.setProf(None) else: self.cbConfirmDelete.config(state=NORMAL) self.cbCDel.set(0) prof = self.profiles[item-1] po = self.settings.getProfile(prof) for s in FirmwareSettings: p = self.parameters[s] p.setProf(po.getAttrib(s)) self.updateProfDisplay() def doSave(self): np = self.newProf.get().strip() if np == "": showerror("Write Error", "New Profile name required", parent=self.top) return if np in self.profiles and self.cbOWrite.get() == 0: showerror("Write Error", "Must check over-write for an existing profile", parent=self.top) return p = self.settings.getProfile(np) newProf = False if p == None: p = self.settings.addProfile(np) newProf = True for s in FirmwareSettings: val = self.entryWidgets[s].get() if self.valueValid(val): p.setAttrib(s, float(val)) else: p.delAttrib(s) if newProf: self.loadProfiles(p.getName()) def doFlashToEEProm(self): for s in FirmwareSettings: p = self.parameters[s] v = p.getFlash() p.setEEProm(v) self.settings.firmware[s] = v self.eepromWidgets[s].config(text=self.parameters[s].displayEEProm()) self.settings.setModified() self.log.logMsg("Committing to EEProm") self.printer.send_now("M500") def updateFlashDisplay(self): for s in FirmwareSettings: self.flashWidgets[s].config(text=self.parameters[s].displayFlash()) def updateEEPromDisplay(self): for s in FirmwareSettings: self.eepromWidgets[s].config(text=self.parameters[s].displayEEProm()) def updateProfDisplay(self): for s in FirmwareSettings: self.entryWidgets[s].delete(0, END) self.entryWidgets[s].insert(0, self.parameters[s].displayProf()) def doEEPromToFlash(self): self.readingFirmware = True self.got92 = False self.got201 = False self.got203 = False self.got204 = False self.got205 = False self.got206 = False self.got301 = False self.app.readingFirmware = True self.printer.send_now("M501") def valueValid(self, v): if v == None: return False if v == "": return False try: vf = float(v) return True except: return False def profButton(self, p): ptag = p.getTag() cmd, pn = ptag.split('_') val = self.entryWidgets[ptag].get() if self.valueValid(val): vf = float(val) self.parameters[ptag].setFlash(vf) dspv = self.parameters[ptag].displayFlash().strip() self.flashWidgets[ptag].config(text=dspv) self.printer.send_now("%s %s%s" % (cmd.upper(), pn.upper(), dspv)) self.log.logMsg("setting %s - %s to %s" % (self.groups[cmd].getLabel(), self.parameters[ptag].getLabel(), dspv)) else: self.log.logMsg("Bad parameter value") def allButton(self, g): gtag = g.getTag() cmd = gtag.upper() hasParams = False for p in self.groups[gtag]: ptag = p.getTag() pn = p.tag.split('_')[1] val = self.entryWidgets[ptag].get() if self.valueValid(val): hasParams = True vf = float(val) self.parameters[ptag].setFlash(vf) dspv = self.parameters[ptag].displayFlash().strip() self.flashWidgets[ptag].config(text=dspv) self.log.logMsg("setting %s - %s to %s" % (self.groups[gtag].getLabel(), self.parameters[ptag].getLabel(), dspv)) cmd += " %s%s" % (pn.upper(), dspv) else: self.log.logMsg("Bad parameter value: %s" % self.parameters[ptag].getLabel()) if hasParams: self.printer.send_now(cmd) else: self.log.logMsg("No parameters entered") def delTop(self): self.top.destroy() self.top = None
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.target_keep_profile_var = IntVar() self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if (data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self.confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase self.keepProfileCheckbutton = Checkbutton( self, text="Keep User Profile (BETA)", variable=self.target_keep_profile_var) self.keepProfileCheckbutton.grid(row=5, column=0, columnspan=4, sticky="W") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label(self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry(self, textvariable=self.bidVar, width="30") self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest': self.logger.log( 'Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.logger.log(self.bidVar.get() + ' is invalid: ' + str(len(self.bidVar.get()))) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): # if the value is '' or 'latest', the set the build_id option as ''. buildId = self.bidVar.get() if buildId == 'latest': buildId = '' elif len(buildId) != 14: self.printErr("Invalid build ID: " + buildId + ", reset to latest") buildId = '' self.bidVar.set('latest') else: if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get( self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if (PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if (PathParser._GAIA in package): params.append(PathParser._GAIA) if (PathParser._GECKO in package): params.append(PathParser._GECKO) keep_profile = (self.target_keep_profile_var.get() == 1) archives = self.controller.do_download(params) self.controller.do_flash(params, archives, keep_profile=keep_profile) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[self.deviceList.get( self.deviceList.curselection())] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: self.logger.log('Invalid build ID: ' + buildId + ', reset to latest', status_callback=self.printErr) buildId = '' self.bidVar.set('latest') package = self.controller.getPackages( self.data[device][version][eng]['src'], build_id=buildId) for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
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 ActionModulation(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.parent = parent self.intensityValue = 0.0 self.initUI() def initUI(self): self.frame = Frame(self.parent, relief=RAISED,borderwidth=1) #panel with the information to be introduced #self.grid(row=0,column=0) self.position = PanelInformation.PanelInformation(self.frame) self.position.getFrame().grid(row=0,column=0) self.position.setLabelXLabel("Position X:") self.position.setLabelYLabel("Position Y:") self.position.setLabelThetaLabel("Position Theta:") self.velocity = PanelInformation.PanelInformation(self.frame) self.velocity.getFrame().grid(row=1,column=0) self.velocity.setLabelXLabel("Walk Shoulder:") self.velocity.setLabelYLabel("Walk torso:") self.velocity.setLabelThetaLabel("Pose:") #panel for the emotion intensity self.frameIntensity = Frame(self.frame, relief=RAISED,borderwidth=1) self.frameIntensity.grid(row = 4, column = 0) self.labelIntensity = Label(self.frameIntensity,text="Intensity:") self.labelIntensity.grid(row=0,column=0) self.intensity = Scale(self.frameIntensity, from_=0, to = 1,command=self.onScale) self.intensity.grid(row = 1, column = 0) self.var = IntVar() self.labelInfoIntensity = Label(self.frameIntensity, text=0, textvariable=self.var) self.labelInfoIntensity.grid(row = 2, column = 0) #panel with the robot's information self.positionInfo = PanelInformation.PanelInformation(self.frame) self.positionInfo.setDisableEntry() self.positionInfo.getFrame().grid(row=0,column=2) self.positionInfo.setLabelXLabel("Position X:") self.positionInfo.setLabelYLabel("Position Y:") self.positionInfo.setLabelThetaLabel("Position Theta:") self.velocityInfo = PanelInformation.PanelInformation(self.frame) self.velocityInfo.setDisableEntry() self.velocityInfo.getFrame().grid(row=1,column=2) self.velocityInfo.setLabelXLabel("Velocity X:") self.velocityInfo.setLabelYLabel("Velocity Y:") self.velocityInfo.setLabelThetaLabel("Velocity Theta:") #emotions and actions self.frameEmotionAction = Frame(self.frame, relief=RAISED,borderwidth=1) self.frameEmotionAction.grid(row=2,column=0,columnspan=3) self.labelEmotion = Label(self.frameEmotionAction,text="Emotion:") self.labelEmotion.grid(row=0,column=0) scrollbar = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar.grid(row=0,column=3) self.listEmotion = Listbox(self.frameEmotionAction,height=4) self.listEmotion.grid(row=0,column=2) self.listEmotion.bind("<<ListboxSelect>>", self.onSelectEmotion) #the new emotions should be added here self.emotions = ['neutral','angry','happy','sad','fear','content'] for item in self.emotions: self.listEmotion.insert(END,item) self.listEmotion.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.listEmotion.yview) self.labelAction = Label(self.frameEmotionAction,text="Action:") self.labelAction.grid(row=0,column=4) scrollbar2 = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar2.grid(row=0,column=6) self.listAction = Listbox(self.frameEmotionAction,height=4) self.listAction.grid(row=0,column=5) #the new actions should be added here self.actions = ['not_do_anything','oscillate_shoulder','oscillate_body','move_shoulder','move_body','move_torso','oscillate_torso','walk'] for item in self.actions: self.listAction.insert(END,item) self.listAction.config(yscrollcommand=scrollbar2.set) self.listAction.bind("<<ListboxSelect>>", self.onSelectAction) scrollbar2.config(command=self.listAction.yview) self.actionSelected = "do_nothing" self.emotionSelected = "neutral" def getFrame(self): return self.frame def onScale(self, val): v = format(float(val),'.2f') self.intensityValue = v self.var.set(v) def getIntensity(self): return self.intensityValue def onSelectAction(self,val): sender = val.widget idx = sender.curselection() self.actionSelected = sender.get(idx) def onSelectEmotion(self,val): sender = val.widget idx = sender.curselection() self.emotionSelected = sender.get(idx) def getListEmotion(self): return self.emotionSelected def getListAction(self): return self.actionSelected def getPanelPosition(self): return self.position def getPanelVelocity(self): return self.velocity def getPanelInfoPosition(self): return self.positionInfo def getPanelInfoVelocity(self): return self.velocityInfo
class ListPage(BasePage): def __init__(self, parent, controller): BasePage.__init__(self, parent, controller) self.mutex = Lock() def prepare(self): self.deviceList.config(state='normal') self.versionList.config(state='disabled') self.engList.config(state='disabled') self.packageList.config(state='disabled') self.ok.config(state='disabled') self.setData(self.controller.data) self.setDeviceList(self.data.keys()) self.controller.setDefault(self, self.controller.loadOptions()) self.deviceList.focus_force() def printErr(self, message): self.errLog.config(text=message) def setData(self, data): self.data = data def setupView(self, title="Select your flash", data=None): if(data): self.setData(data) self.errLog = Label(self, text="") self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE") self.desc = Label(self, text=title, font=TITLE_FONT) self.desc.grid(row=0, column=0, columnspan=2) self.ok = Button(self, text='Next', command=lambda: self. confirm()) self.ok.grid(row=4, column=3, sticky="E") self.ok.config(state="disabled") self.deviceLabel = Label(self, text="Device", font=TITLE_FONT) self.deviceLabel.grid(row=1, column=0) self.deviceList = Listbox(self, exportselection=0) self.deviceList.grid(row=2, column=0) self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect) self.deviceList.config(state="disabled") self.versionLabel = Label(self, text="Branch", font=TITLE_FONT) self.versionLabel.grid(row=1, column=1) self.versionList = Listbox(self, exportselection=0) self.versionList.grid(row=2, column=1) self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect) self.versionList.config(state="disabled") self.engLabel = Label(self, text="Build Type", font=TITLE_FONT) self.engLabel.grid(row=1, column=2) self.engList = Listbox(self, exportselection=0) self.engList.grid(row=2, column=2) self.engList.bind('<<ListboxSelect>>', self.engOnSelect) self.engList.config(state="disabled") self.packageLabel = Label( self, text="Gecko/Gaia/Full", font=TITLE_FONT) self.packageLabel.grid(row=1, column=3) self.packageList = Listbox(self, exportselection=0) self.packageList.grid(row=2, column=3) self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect) self.packageList.config(state="disabled") self.bidVar = StringVar() Label(self, text="Build ID").grid(row=3, column=0, sticky='E') self.bidInput = Entry( self, textvariable=self.bidVar, width="30") self.bidInput.grid( row=3, column=1, columnspan=2, sticky="W") self.bidVar.set('latest') # binding unfocus for build id field self.bidInput.bind('<FocusOut>', self.updateBuildId) # binding the Return Key to each componments self.deviceList.bind('<Return>', self.pressReturnKey) self.versionList.bind('<Return>', self.pressReturnKey) self.engList.bind('<Return>', self.pressReturnKey) self.packageList.bind('<Return>', self.pressReturnKey) self.bidInput.bind('<Return>', self.pressReturnKey) self.ok.bind('<Return>', self.pressReturnKey) def selection_all_checked(self): result = False if len(self.deviceList.curselection()) == 0: self.logger.log('Please select device.', status_callback=self.printErr) self.ok.config(state="disabled") self.deviceList.focus_set() elif len(self.versionList.curselection()) == 0: self.logger.log('Please select branch.', status_callback=self.printErr) self.ok.config(state="disabled") self.versionList.focus_set() elif len(self.engList.curselection()) == 0: self.logger.log('Please select user or engineer build.', status_callback=self.printErr) self.ok.config(state="disabled") self.engList.focus_set() elif len(self.packageList.curselection()) == 0: self.logger.log('Please select package to flash.', status_callback=self.printErr) self.ok.config(state="disabled") self.packageList.focus_set() elif len(self.bidVar.get()) == 0: self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr) self.bidVar.set('latest') else: result = True return result def updateBuildId(self, event=None): if len(self.engList.curselection()) != 0: self.refreshPackageList() def pressReturnKey(self, event=None): if self.selection_all_checked(): self.ok.config(state="disabled") self.confirm() def deviceOnSelect(self, evt): self.setVersionList() def versionOnSelect(self, evt): self.setEngList() def engOnSelect(self, evt): self.refreshPackageList() # hard coded right now def packageOnSelect(self, evt): self.ok.config(state="normal") def confirm(self): self.mutex.acquire() try: if self.selection_all_checked(): self.ok.config(state="disabled") params = [] package = self.packageList.get(self.packageList.curselection()[0]) self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr) if(PathParser._IMAGES in package): params.append(PathParser._IMAGES) else: if(PathParser._GAIA in package): params.append(PathParser._GAIA) if(PathParser._GECKO in package): params.append(PathParser._GECKO) self.controller.doFlash(params) self.packageList.select_clear(0, END) self.controller.transition(self) finally: self.mutex.release() def setDeviceList(self, device=[]): self.deviceList.delete(0, END) for li in device: self.deviceList.insert(END, li) def setVersionList(self, version=[]): if len(version) == 0: version = self.data[ self.deviceList.get(self.deviceList.curselection()) ] self.versionList.config(state="normal") self.engList.config(state="disabled") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.versionList.delete(0, END) for li in version: self.versionList.insert(END, li) def setEngList(self, eng=[]): if len(eng) == 0: device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.data[device][version] self.engList.config(state="normal") self.packageList.config(state="disabled") self.ok.config(state="disabled") self.engList.delete(0, END) for li in eng: self.engList.insert(END, li) def refreshPackageList(self): self.mutex.acquire() try: self.packageList.config(state="normal") self.ok.config(state="normal") self.packageList.delete(0, END) device = self.deviceList.get(self.deviceList.curselection()) version = self.versionList.get(self.versionList.curselection()) eng = self.engList.get(self.engList.curselection()) # if the value is '' or 'latest', the set the build_id option as ''. buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get() package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId) if len(package) == 0: package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES] for li in package: self.packageList.insert(END, li) finally: self.mutex.release()
class Ordered_Listbox(Frame): def __init__(self, master, data=None, ascending_order=True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs): Frame.__init__(self, master) self._ignore_case = ignore_case self._ascending_order = ascending_order master.grid_rowconfigure(0, weight=1) master.grid_columnconfigure(0, weight=1) self._listbox = Listbox(self, *kwargs) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: self._vbar = Scrollbar(self, takefocus=0, command=self._listbox.yview, **scrollbar_kwargs) self._vbar.grid(row=0, column=1, sticky=N + S) if autoscroll: self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l)) else: self._listbox.config(yscrollcommand=self._vbar.set) if hscrollbar: self._hbar = Scrollbar(self, takefocus=0, command=self._listbox.xview, **scrollbar_kwargs) self._hbar.grid(row=0, column=1, sticky=E + W) if autoscroll: self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l)) else: self._listbox.config(xscrollcommand=self._hbar.set) if data is not None: for item in data: self.add_item(item) def add_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.insert(index, item) def delete_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.delete(index - 1) def selected_items(self): list_of_items = [] for index in self._listbox.curselection(): list_of_items.append(self._listbox.get(index)) return list_of_items def selected_item(self): return self._listbox.curselection()[0] def deselect_all(self): self._listbox.selection_clear(0, END) def select(self, item): index = self.index(item) if index is None: return self._listbox.selection_set(index) def deselect(self, item): index = self.index(item) if index is None: return self._listbox.selection_clear(index) def index(self, item): list_of_items = self._listbox.get(0, END) try: index = list_of_items.index(item) except ValueError: return None return index def bind(self, event, handler): self._listbox.bind(event, handler) def clear(self): self._listbox.delete(1, END) def __iter__(self): return self.items @property def items(self): return self._listbox.get(0, END)
class ShiftReduceApp(object): """ A graphical tool for exploring the shift-reduce parser. The tool displays the parser's stack and the remaining text, and allows the user to control the parser's operation. In particular, the user can shift tokens onto the stack, and can perform reductions on the top elements of the stack. A "step" button simply steps through the parsing process, performing the operations that ``nltk.parse.ShiftReduceParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingShiftReduceParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Shift Reduce Parser Application') # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animating_lock = 0 self._animate = IntVar(self._top) self._animate.set(10) # = medium # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Initialize fonts. self._init_fonts(self._top) # Set up key bindings. self._init_bindings() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # A popup menu for reducing. self._reduce_menu = Menu(self._canvas, tearoff=0) # Reset the demo, and set the feedback frame to empty. self.reset() self._lastoper1['text'] = '' ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = tkFont.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkFont.Font(family='helvetica', size=self._size.get()) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Reductions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if 1: #len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand=listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) # When they hover over a production, highlight it. self._hover = -1 self._prodlist.bind('<Motion>', self._highlight_hover) self._prodlist.bind('<Leave>', self._clear_hover) def _init_bindings(self): # Quit self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Alt-q>', self.destroy) self._top.bind('<Alt-x>', self.destroy) # Ops (step, shift, reduce, undo) self._top.bind('<space>', self.step) self._top.bind('<s>', self.shift) self._top.bind('<Alt-s>', self.shift) self._top.bind('<Control-s>', self.shift) self._top.bind('<r>', self.reduce) self._top.bind('<Alt-r>', self.reduce) self._top.bind('<Control-r>', self.reduce) self._top.bind('<Delete>', self.reset) self._top.bind('<u>', self.undo) self._top.bind('<Alt-u>', self.undo) self._top.bind('<Control-u>', self.undo) self._top.bind('<Control-z>', self.undo) self._top.bind('<BackSpace>', self.undo) # Misc self._top.bind('<Control-p>', self.postscript) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) # Animation speed control self._top.bind('-', lambda e, a=self._animate: a.set(20)) self._top.bind('=', lambda e, a=self._animate: a.set(10)) self._top.bind('+', lambda e, a=self._animate: a.set(4)) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom') Button( buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step, ).pack(side='left') Button(buttonframe, text='Shift', underline=0, background='#90f090', foreground='black', command=self.shift).pack(side='left') Button(buttonframe, text='Reduce', underline=0, background='#90f090', foreground='black', command=self.reduce).pack(side='left') Button(buttonframe, text='Undo', underline=0, background='#f0a0a0', foreground='black', command=self.undo).pack(side='left') def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Shift', underline=0, command=self.shift, accelerator='Ctrl-s') rulemenu.add_command(label='Reduce', underline=0, command=self.reduce, accelerator='Ctrl-r') rulemenu.add_separator() rulemenu.add_command(label='Undo', underline=0, command=self.undo, accelerator='Ctrl-u') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', width=525, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() self._stackwidgets = [] self._rtextwidgets = [] self._titlebar = canvas.create_rectangle(0, 0, 0, 0, fill='#c0f0f0', outline='black') self._exprline = canvas.create_line(0, 0, 0, 0, dash='.') self._stacktop = canvas.create_line(0, 0, 0, 0, fill='#408080') size = self._size.get() + 4 self._stacklabel = TextWidget(canvas, 'Stack', color='#004040', font=self._boldfont) self._rtextlabel = TextWidget(canvas, 'Remaining Text', color='#004040', font=self._boldfont) self._cframe.add_widget(self._stacklabel) self._cframe.add_widget(self._rtextlabel) ######################################### ## Main draw procedure ######################################### def _redraw(self): scrollregion = self._canvas['scrollregion'].split() (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion] # Delete the old stack & rtext widgets. for stackwidget in self._stackwidgets: self._cframe.destroy_widget(stackwidget) self._stackwidgets = [] for rtextwidget in self._rtextwidgets: self._cframe.destroy_widget(rtextwidget) self._rtextwidgets = [] # Position the titlebar & exprline (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4) self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10) # Position the titlebar labels.. (x1, y1, x2, y2) = self._stacklabel.bbox() self._stacklabel.move(5 - x1, 3 - y1) (x1, y1, x2, y2) = self._rtextlabel.bbox() self._rtextlabel.move(cx2 - x2 - 5, 3 - y1) # Draw the stack. stackx = 5 for tok in self._parser.stack(): if isinstance(tok, Tree): attribs = { 'tree_color': '#4080a0', 'tree_width': 2, 'node_font': self._boldfont, 'node_color': '#006060', 'leaf_color': '#006060', 'leaf_font': self._font } widget = tree_to_treesegment(self._canvas, tok, **attribs) widget.node()['color'] = '#000000' else: widget = TextWidget(self._canvas, tok, color='#000000', font=self._font) widget.bind_click(self._popup_reduce) self._stackwidgets.append(widget) self._cframe.add_widget(widget, stackx, y) stackx = widget.bbox()[2] + 10 # Draw the remaining text. rtextwidth = 0 for tok in self._parser.remaining_text(): widget = TextWidget(self._canvas, tok, color='#000000', font=self._font) self._rtextwidgets.append(widget) self._cframe.add_widget(widget, rtextwidth, y) rtextwidth = widget.bbox()[2] + 4 # Allow enough room to shift the next token (for animations) if len(self._rtextwidgets) > 0: stackx += self._rtextwidgets[0].width() # Move the remaining text to the correct location (keep it # right-justified, when possible); and move the remaining text # label, if necessary. stackx = max(stackx, self._stacklabel.width() + 25) rlabelwidth = self._rtextlabel.width() + 10 if stackx >= cx2 - max(rtextwidth, rlabelwidth): cx2 = stackx + max(rtextwidth, rlabelwidth) for rtextwidget in self._rtextwidgets: rtextwidget.move(4 + cx2 - rtextwidth, 0) self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0) midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) (x1, y1, x2, y2) = self._stacklabel.bbox() # Set up binding to allow them to shift a token by dragging it. if len(self._rtextwidgets) > 0: def drag_shift(widget, midx=midx, self=self): if widget.bbox()[0] < midx: self.shift() else: self._redraw() self._rtextwidgets[0].bind_drag(drag_shift) self._rtextwidgets[0].bind_click(self.shift) # Draw the stack top. self._highlight_productions() def _draw_stack_top(self, widget): # hack.. midx = widget.bbox()[2] + 50 self._canvas.coords(self._stacktop, midx, 0, midx, 5000) def _highlight_productions(self): # Highlight the productions that can be reduced. self._prodlist.selection_clear(0, 'end') for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Button Callbacks ######################################### def destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset App' self._lastoper2['text'] = '' self._redraw() def step(self, *e): if self.reduce(): return 1 elif self.shift(): return 1 else: if len(self._parser.parses()) > 0: self._lastoper1['text'] = 'Finished:' self._lastoper2['text'] = 'Success' else: self._lastoper1['text'] = 'Finished:' self._lastoper2['text'] = 'Failure' def shift(self, *e): if self._animating_lock: return if self._parser.shift(): tok = self._parser.stack()[-1] self._lastoper1['text'] = 'Shift:' self._lastoper2['text'] = '%r' % tok if self._animate.get(): self._animate_shift() else: self._redraw() return 1 return 0 def reduce(self, *e): if self._animating_lock: return production = self._parser.reduce() if production: self._lastoper1['text'] = 'Reduce:' self._lastoper2['text'] = '%s' % production if self._animate.get(): self._animate_reduce() else: self._redraw() return production def undo(self, *e): if self._animating_lock: return if self._parser.undo(): self._redraw() def postscript(self, *e): self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) ######################################### ## Menubar callbacks ######################################### def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) #self._stacklabel['font'] = ('helvetica', -size-4, 'bold') #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold') #self._lastoper_label['font'] = ('helvetica', -size) #self._lastoper1['font'] = ('helvetica', -size) #self._lastoper2['font'] = ('helvetica', -size) #self._prodlist['font'] = ('helvetica', -size) #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold') self._redraw() def help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Shift-Reduce Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Shift-Reduce Parser Application', (__doc__ or '').strip(), width=75) def about(self, *e): ABOUT = ("NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper") TITLE = 'About: Shift-Reduce Parser Application' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = string.join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sent): self._sent = sent.split() #[XX] use tagged? self.reset() ######################################### ## Reduce Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) production = self._parser.reduce(self._productions[index]) if production: self._lastoper1['text'] = 'Reduce:' self._lastoper2['text'] = '%s' % production if self._animate.get(): self._animate_reduce() else: self._redraw() else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.reducible_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) def _popup_reduce(self, widget): # Remove old commands. productions = self._parser.reducible_productions() if len(productions) == 0: return self._reduce_menu.delete(0, 'end') for production in productions: self._reduce_menu.add_command(label=str(production), command=self.reduce) self._reduce_menu.post(self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()) ######################################### ## Animations ######################################### def _animate_shift(self): # What widget are we shifting? widget = self._rtextwidgets[0] # Where are we shifting from & to? right = widget.bbox()[0] if len(self._stackwidgets) == 0: left = 5 else: left = self._stackwidgets[-1].bbox()[2] + 10 # Start animating. dt = self._animate.get() dx = (left - right) * 1.0 / dt self._animate_shift_frame(dt, widget, dx) def _animate_shift_frame(self, frame, widget, dx): if frame > 0: self._animating_lock = 1 widget.move(dx, 0) self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx) else: # but: stacktop?? # Shift the widget to the stack. del self._rtextwidgets[0] self._stackwidgets.append(widget) self._animating_lock = 0 # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() def _animate_reduce(self): # What widgets are we shifting? numwidgets = len(self._parser.stack()[-1]) # number of children widgets = self._stackwidgets[-numwidgets:] # How far are we moving? if isinstance(widgets[0], TreeSegmentWidget): ydist = 15 + widgets[0].node().height() else: ydist = 15 + widgets[0].height() # Start animating. dt = self._animate.get() dy = ydist * 2.0 / dt self._animate_reduce_frame(dt / 2, widgets, dy) def _animate_reduce_frame(self, frame, widgets, dy): if frame > 0: self._animating_lock = 1 for widget in widgets: widget.move(0, dy) self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy) else: del self._stackwidgets[-len(widgets):] for widget in widgets: self._cframe.remove_widget(widget) tok = self._parser.stack()[-1] if not isinstance(tok, Tree): raise ValueError() label = TextWidget(self._canvas, str(tok.node), color='#006060', font=self._boldfont) widget = TreeSegmentWidget(self._canvas, label, widgets, width=2) (x1, y1, x2, y2) = self._stacklabel.bbox() y = y2 - y1 + 10 if not self._stackwidgets: x = 5 else: x = self._stackwidgets[-1].bbox()[2] + 10 self._cframe.add_widget(widget, x, y) self._stackwidgets.append(widget) # Display the available productions. self._draw_stack_top(widget) self._highlight_productions() # # Delete the old widgets.. # del self._stackwidgets[-len(widgets):] # for widget in widgets: # self._cframe.destroy_widget(widget) # # # Make a new one. # tok = self._parser.stack()[-1] # if isinstance(tok, Tree): # attribs = {'tree_color': '#4080a0', 'tree_width': 2, # 'node_font': bold, 'node_color': '#006060', # 'leaf_color': '#006060', 'leaf_font':self._font} # widget = tree_to_treesegment(self._canvas, tok.type(), # **attribs) # widget.node()['color'] = '#000000' # else: # widget = TextWidget(self._canvas, tok.type(), # color='#000000', font=self._font) # widget.bind_click(self._popup_reduce) # (x1, y1, x2, y2) = self._stacklabel.bbox() # y = y2-y1+10 # if not self._stackwidgets: x = 5 # else: x = self._stackwidgets[-1].bbox()[2] + 10 # self._cframe.add_widget(widget, x, y) # self._stackwidgets.append(widget) #self._redraw() self._animating_lock = 0 ######################################### ## Hovering. ######################################### def _highlight_hover(self, event): # What production are we hovering over? index = self._prodlist.nearest(event.y) if self._hover == index: return # Clear any previous hover highlighting. self._clear_hover() # If the production corresponds to an available reduction, # highlight the stack. selection = [int(s) for s in self._prodlist.curselection()] if index in selection: rhslen = len(self._productions[index].rhs()) for stackwidget in self._stackwidgets[-rhslen:]: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.node()['color'] = '#00a000' else: stackwidget['color'] = '#00a000' # Remember what production we're hovering over. self._hover = index def _clear_hover(self, *event): # Clear any previous hover highlighting. if self._hover == -1: return self._hover = -1 for stackwidget in self._stackwidgets: if isinstance(stackwidget, TreeSegmentWidget): stackwidget.node()['color'] = 'black' else: stackwidget['color'] = 'black'
def transitionSelection(tracelog,*args): # start of child window GUI code root = Toplevel() root.title("Manual Transition selection") root.resizable(width=FALSE, height=FALSE) # frame mainFrame = ttk.Frame(root, width="364", padding="4 4 8 8") mainFrame.grid(column=0, row=0) labelSource=ttk.Label(mainFrame,text="Source", justify=LEFT) labelSource.grid(column=0, row=0, sticky="e") srcState = ttk.Combobox(mainFrame,width=10) srcState.delete(0, END) srcState['values'] = ([k for k in tracelog]) srcState.grid(column=1, row=0, sticky="e") srcState.state(['readonly']) # Destination label labelDestination=ttk.Label(mainFrame,text="Destination",justify=LEFT) labelDestination.grid(column=0, row=1, sticky="e") # destination combobox destState = ttk.Combobox(mainFrame,width=10) destState.delete(0, END) destState['values'] = ([get_num(k) for k in tracelog]) destState.grid(column=1, row=1, sticky="e") destState.state(['readonly']) listFrame=ttk.LabelFrame(root) listFrame.grid(column=0,row=2,sticky="we") scrollBar = Scrollbar(listFrame) scrollBar.pack(side=RIGHT, fill=Y) listBoxTop = Listbox(listFrame, selectmode=SINGLE,width=20,height=10) listBoxTop.pack(fill=BOTH) scrollBar.config(command=listBoxTop.yview) listBoxTop.config(yscrollcommand=scrollBar.set) def addItemsToList(): if len(srcState.get())==0: tkMessageBox.showerror("No Source Entry","Please select a source state first") root.focus() return else: st=get_apha(srcState.get()) set_listTop(listBoxTop,str(get_num(srcState.get())) +'-->'+ str(destState.get()) + '[label='+st+']') manualMappingList.append(str(get_num(srcState.get())) +'-->'+ str(destState.get())) transitionDict[get_num(srcState.get())]=st generateFSMGraph() def removeMapFromList(): try: if len(listBoxTop.get(0, END))==0 or listBoxTop.curselection() is None: tkMessageBox.showerror("Empty List", "The mapping list is empty") return else: selection=listBoxTop.curselection() value = listBoxTop.get(selection[0]) ch='' for c in value: if c=='[': #Strip out characters after the symbol [ break else: ch +=c #when we remove an entry from the listbox, we also update the manual mapping list manualMappingList.remove(ch) listBoxTop.delete(selection) #remove the selected entry from listbox generateFSMGraph() transitionDict={} #reset the transition dictionary to capture updated entries from the listBox except (IndexError,AttributeError,ValueError): tkMessageBox.showerror("Error", "Please select an entry if exists or try again") def generateFSMGraph(): if len(listBoxTop.get(0, END))==0: tkMessageBox.showerror("No entry","There is no mapping entry.Please add mapping entry first") return try: for e in transitionDict: print transitionDict[e] stateMap1[int(e)]={} for m in manualMappingList: st=[int(s) for s in m.split('-->') if s.isdigit()] #extract digits in a mapping entry if str(e)==str(st[0]) and str(e)==str(st[1]): stateMap1[int(e)][int(st[0])]=transitionDict[e] elif str(e)!=str(st[1]) and str(e)==str(st[0]): stateMap1[int(e)][int(st[1])]=transitionDict[e] #callback functions drawStateTransitionGraph() loadFSMImage() except (ValueError,IndexError,GraphvizError,AttributeError): pass def closeWindowTop(): root.destroy() #Add a button inside the tab btnAdd=ttk.Button(mainFrame,text="Add",width=10,command=addItemsToList) btnAdd.grid(column=2,row=0) btnRemove=ttk.Button(mainFrame,text="Remove",width=10,command=removeMapFromList) btnRemove.grid(column=2,row=1) #Add frame to hold buttons btnFrame=ttk.LabelFrame(root) btnFrame.grid(column=0,row=3,sticky="we") btnCancel=ttk.Button(btnFrame,text="Close",width=13,command=closeWindowTop) btnCancel.pack(side=RIGHT,fill=X) btnOk=ttk.Button(btnFrame,text="Generate FSM",width=13,command=generateFSMGraph) btnOk.pack(side=RIGHT, fill=X) def set_listTop(Listbox,sMap): try: index=Listbox.curselection()[0] #Check if there is an existing entry in the listbox except IndexError: index=END for i,listbox_entry in enumerate(Listbox.get(0, END)): if listbox_entry == sMap: tkMessageBox.showinfo("Entry", "There is already an entry for this transition.") return Listbox.insert(index, sMap) def drawStateTransitionGraph(): #Here we appy the state transitions to create a finite state machine ktail = FiniteStateMachine('K-TAIL') for nx,kvx in stateMap1.items(): for c in kvx: State(nx).update({kvx[c]:State(c)}) print 'State Transition: ' +str(nx) + '-->'+str(c) + '[label='+kvx[c] +']' #Define initial state if nx==0: nx=State(0, initial=True) #Create a state machine print '------------------------------------------------------------------------------------' #Check if there is existing graph data try: graph=get_graph(ktail) if graph!=None: graph.draw('../graph/ktail.png', prog='dot') print graph else: pass except GraphvizError: tkMessageBox.ERROR # padding for widgets for child in mainFrame.winfo_children(): child.grid_configure(padx=4, pady=4) root.mainloop()
class Ordered_Listbox(Frame): def __init__(self, master, data=None, ascending_order = True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs): Frame.__init__(self, master) self._ignore_case = ignore_case self._ascending_order = ascending_order master.grid_rowconfigure(0, weight=1) master.grid_columnconfigure(0, weight=1) self._listbox = Listbox(self, *kwargs) self._listbox.grid(row=0, column=0, sticky= N+E+W+S) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: self._vbar=Scrollbar(self,takefocus=0, command=self._listbox.yview, **scrollbar_kwargs) self._vbar.grid(row=0, column=1, sticky= N+S) if autoscroll: self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l)) else: self._listbox.config(yscrollcommand=self._vbar.set) if hscrollbar: self._hbar=Scrollbar(self,takefocus=0, command=self._listbox.xview, **scrollbar_kwargs) self._hbar.grid(row=0, column=1, sticky= E+W) if autoscroll: self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l)) else: self._listbox.config(xscrollcommand=self._hbar.set) if data is not None: for item in data: self.add_item(item) def add_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.insert(index, item) def delete_item(self, item): list_of_items = self._listbox.get(0, END) index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order) self._listbox.delete(index-1) def selected_items(self): list_of_items = [] for index in self._listbox.curselection(): list_of_items.append(self._listbox.get(index)) return list_of_items def selected_item(self): return self._listbox.curselection()[0] def deselect_all(self): self._listbox.selection_clear(0, END) def select(self, item): index = self.index(item) if index is None: return self._listbox.selection_set(index) def deselect(self, item): index = self.index(item) if index is None: return self._listbox.selection_clear(index) def index(self, item): list_of_items = self._listbox.get(0, END) try: index = list_of_items.index(item) except ValueError: return None return index def bind(self, event, handler): self._listbox.bind(event, handler) def clear(self): self._listbox.delete(1,END) def __iter__(self): return self.items @property def items(self): return self._listbox.get(0, END)
class TimingReport(Toplevel): def __init__(self, app, printer, settings, logger, *arg): self.app = app self.printer = printer self.settings = settings self.logger = logger self.afterID = None self.selection = None if not self.app.printing: self.logger.logMsg("Report only available while printing") return Toplevel.__init__(self, app, *arg) self.title("Layer by Layer Timing") self.protocol("WM_DELETE_WINDOW", self.doCancel) fUL = Frame(self) fUL.grid(row=1, column=1, rowspan=2, padx=10) l = Label(fUL, text="Choose layer:") l.pack() lbf = Frame(fUL) lbf.pack() self.lbLayers = Listbox(lbf) self.lbLayers.bind("<ButtonRelease-1>", self.clickLayers) self.sb = Scrollbar(lbf, orient=VERTICAL) self.sb.config(command=self.lbLayers.yview) self.lbLayers.config(yscrollcommand=self.sb.set) self.sb.pack(side=RIGHT, fill=Y) self.lbLayers.pack(side=LEFT, fill=BOTH, expand=1) rbf = LabelFrame(fUL, text="Time Format") rbf.pack() self.rbvTimeFmt = StringVar() self.rbvTimeFmt.set(TIME_WALL) rb = Radiobutton(rbf, text="Wall time", variable=self.rbvTimeFmt, value=TIME_WALL, command=self.doTimeFormat) rb.pack(anchor=W) rb = Radiobutton(rbf, text="From start", variable=self.rbvTimeFmt, value=TIME_START, command=self.doTimeFormat) rb.pack(anchor=W) rb = Radiobutton(rbf, text="From now", variable=self.rbvTimeFmt, value=TIME_NOW, command=self.doTimeFormat) rb.pack(anchor=W) fUR = Frame(self) fUR.grid(row=1, column=2, rowspan=2, padx=10) row = 1 lf = LabelFrame(fUR, text="Print Times: ") lf.grid(row=row, column=1) l = Label(lf, text="Start: ", width=12, justify=RIGHT) l.grid(row=1, column=1, padx=10, sticky=E) self.timePStart = Label(lf, text="", anchor=W, justify=LEFT) self.timePStart.grid(row=1, column=3, padx=10) l = Label(lf, text="Elapsed: ", width=12, justify=RIGHT) l.grid(row=2, column=1, padx=10, sticky=E) self.timeElapsed = Label(lf, text="", anchor=W, justify=LEFT) self.timeElapsed.grid(row=2, column=3, padx=10) l = Label(lf, text="Current: ", width=12, justify=RIGHT) l.grid(row=3, column=1, padx=10, sticky=E) self.timeNow = Label(lf, text="", anchor=W, justify=LEFT) self.timeNow.grid(row=3, column=3, padx=10) row += 1 lf = LabelFrame(fUR, text="Layer Start Time: ") lf.grid(row=row, column=1) l = Label(lf, text="original: ", width=12, justify=RIGHT) l.grid(row=1, column=1, padx=10, sticky=E) self.timeOStart = Label(lf, text="", anchor=W, justify=LEFT) self.timeOStart.grid(row=1, column=2, padx=10) l = Label(lf, text="revised: ", width=12, justify=RIGHT) l.grid(row=2, column=1, padx=10, sticky=E) self.timeRStart = Label(lf, text="", anchor=W, justify=LEFT) self.timeRStart.grid(row=2, column=2, padx=10) row += 1 lf = LabelFrame(fUR, text="Time in Layer: ") lf.grid(row=row, column=1) l = Label(lf, text="original: ", width=12, justify=RIGHT) l.grid(row=1, column=2, padx=10, sticky=E) self.timeOLayer = Label(lf, text="", anchor=W, justify=LEFT) self.timeOLayer.grid(row=1, column=3, padx=10) l = Label(lf, text="revised: ", width=12, justify=RIGHT) l.grid(row=2, column=2, padx=10, sticky=E) self.timeRLayer = Label(lf, text="", anchor=W, justify=LEFT) self.timeRLayer.grid(row=2, column=3, padx=10) row += 1 lf = LabelFrame(fUR, text="Layer Finish Time: ") lf.grid(row=row, column=1) l = Label(lf, text="original: ", width=12, justify=RIGHT) l.grid(row=1, column=2, padx=10, sticky=E) self.timeOFinish = Label(lf, text="", anchor=W, justify=LEFT) self.timeOFinish.grid(row=1, column=3, padx=10) l = Label(lf, text="revised: ", width=12, justify=RIGHT) l.grid(row=2, column=2, padx=10, sticky=E) self.timeRFinish = Label(lf, text="", anchor=W, justify=LEFT) self.timeRFinish.grid(row=2, column=3, padx=10) self.ticker() def doTimeFormat(self): self.showValues(); def ticker(self): if self.refresh(): self.afterID = self.app.master.after(5000, self.ticker) def refresh(self): if not self.app.printing: self.doCancel() return False if self.selection != None: currentZ = str(self.layerZ[self.selection]) firstZ = self.layerZ[0] else: currentZ = "" firstZ = None self.now = time.time() self.elapsed = self.now - self.app.startTime foundLayer = False line = self.printer.queueindex thisLayerLine = 0 thisLayerTime = 0.0 thisLayerStart = 0.0 for i in self.app.timeLayers: if i[0] >= line: nextLayerLine = i[0] foundLayer = True break thisLayerLine = i[0] thisLayerTime = i[1] thisLayerStart = i[2] - thisLayerTime if not foundLayer: self.doCancel() return False pct = (line-thisLayerLine)/float(nextLayerLine-thisLayerLine) thisLayerTime *= pct self.ratio = (thisLayerStart+thisLayerTime)/float(self.elapsed) if self.ratio == 0: self.logger.logMsg("Invalid ratio calculated") self.doCancel() return False self.layertime = [] self.layerfinish = [] self.layerZ = [] self.selection = None skipped = 0 for i in self.app.timeLayers: if i[0] >= thisLayerLine: if currentZ == str(i[3]): self.selection = len(self.layerZ) self.layerZ.append(i[3]) self.layertime.append(i[1]) self.layerfinish.append(i[2]) else: skipped += 1 if self.selection == None: self.selection = 0 if len(self.layerZ) == 0: self.logger.logMsg("Unable to find any unprinted layers") self.doCancel() return False if self.layerZ[0] != firstZ: # new first layer - update things self.lbLayers.delete(0, END) ln = skipped for i in self.layerZ: ln += 1 s = "%8.3f (%d)" % (i, ln) self.lbLayers.insert(END, s) self.lbLayers.selection_set(self.selection) self.lbLayers.see(self.selection) s = time.strftime('%H:%M:%S', time.localtime(self.app.startTime)) self.timePStart.config(text=s) s = formatElapsed(self.elapsed) self.timeElapsed.config(text=s) s = time.strftime('%H:%M:%S', time.localtime(self.now)) self.timeNow.config(text=s) self.showValues() return True def doCancel(self): self.app.closeTimingReport() def cleanup(self): if self.afterID != None: self.app.after_cancel(self.afterID) def clickLayers(self, *arg): try: s = int(self.lbLayers.curselection()[0]) except: s = 0 self.selection = s; self.showValues() def showValues(self): mode = self.rbvTimeFmt.get() f = self.layerfinish[self.selection] frev = f/self.ratio l = self.layertime[self.selection] lrev = l/self.ratio s = f-l srev = frev - lrev if mode == TIME_START: so = formatElapsed(s) sr = formatElapsed(srev) fo = formatElapsed(f) fr = formatElapsed(frev) elif mode == TIME_NOW: if s < self.elapsed: so = '< now' else: so = formatElapsed(s-self.elapsed) if srev-self.elapsed < 0: sr = '< now' else: sr = formatElapsed(srev-self.elapsed) if f < self.elapsed: fo = '< now' else: fo = formatElapsed(f-self.elapsed) if frev-self.elapsed < 0: fr = '< now' else: fr = formatElapsed(frev-self.elapsed) elif mode == TIME_WALL: so = time.strftime('%H:%M:%S', time.localtime(s+self.app.startTime)) sr = time.strftime('%H:%M:%S', time.localtime(srev+self.app.startTime)) fo = time.strftime('%H:%M:%S', time.localtime(f+self.app.startTime)) fr = time.strftime('%H:%M:%S', time.localtime(frev+self.app.startTime)) self.timeOStart.config(text=so) self.timeRStart.config(text=sr) self.timeOFinish.config(text=fo) self.timeRFinish.config(text=fr) so = formatElapsed(l) sr = formatElapsed(lrev) self.timeOLayer.config(text=so) self.timeRLayer.config(text=sr)
class ActionModulationTest(threading.Thread): def __init__(self,info_queue,data_queue): threading.Thread.__init__(self) self.info_queue = info_queue self.data_queue = data_queue def run(self): self = Tk() self.title("Test") self.position = PanelInformation.PanelInformation(self) self.position.getFrame().grid(row=0,column=0) self.position.setLabelXLabel("Position X:") self.position.setLabelYLabel("Position Y:") self.position.setLabelThetaLabel("Position Theta:") self.velocity = PanelInformation.PanelInformation(self) self.velocity.getFrame().grid(row=1,column=0) self.velocity.setLabelXLabel("Velocity X:") self.velocity.setLabelYLabel("Velocity Y:") self.velocity.setLabelThetaLabel("Velocity Theta:") self.positionInfo = PanelInformation.PanelInformation(self) self.positionInfo.setDisableEntry() self.positionInfo.getFrame().grid(row=0,column=2) self.positionInfo.setLabelXLabel("Position X:") self.positionInfo.setLabelYLabel("Position Y:") self.positionInfo.setLabelThetaLabel("Position Theta:") self.velocityInfo = PanelInformation.PanelInformation(self) self.velocityInfo.setDisableEntry() self.velocityInfo.getFrame().grid(row=1,column=2) self.velocityInfo.setLabelXLabel("Velocity X:") self.velocityInfo.setLabelYLabel("Velocity Y:") self.velocityInfo.setLabelThetaLabel("Velocity Theta:") self.frameEmotionAction = Frame(self, relief=RAISED,borderwidth=1) self.frameEmotionAction.grid(row=2,column=0,columnspan=3) self.labelEmotion = Label(self.frameEmotionAction,text="Emotion:") self.labelEmotion.grid(row=0,column=0) scrollbar = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar.grid(row=0,column=3) self.listEmotion = Listbox(self.frameEmotionAction,height=2) self.listEmotion.grid(row=0,column=2) self.emotions = ['angry','happy','sad'] for item in self.emotions: self.listEmotion.insert(END,item) self.listEmotion.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.listEmotion.yview) self.labelAction = Label(self.frameEmotionAction,text="Action:") self.labelAction.grid(row=0,column=4) scrollbar2 = Scrollbar(self.frameEmotionAction, orient=VERTICAL) scrollbar2.grid(row=0,column=6) self.listAction = Listbox(self.frameEmotionAction,height=2) self.listAction.grid(row=0,column=5) self.actions = ['oscillate_shoulder','oscillate_body','move_shoulder','move_body','walk','walk_and_speak'] for item in self.actions: self.listAction.insert(END,item) self.listAction.config(yscrollcommand=scrollbar2.set) scrollbar2.config(command=self.listAction.yview) self.frameButtons = Frame(self, relief=RAISED,borderwidth=1) self.frameButtons.grid(row=3,column=0,columnspan=4) self.buttonReset = Button(self.frameButtons,text="Reset") self.buttonReset.grid(row=0,column=0) self.buttonStop = Button(self.frameButtons,text="Stop") self.buttonStop.grid(row=0,column=2) self.buttonSend = Button(self.frameButtons,text="Send") self.buttonSend.grid(row=0,column=4) self.mainloop() def updateInterface(self): print 'update' def printThing(self): self.position.setLabelXLabel("Position XXX:") def configureButtonSend(self,function): pass
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol("WM_DELETE_WINDOW", self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, text="init", command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, text="next slide", command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, text="previous slide", command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, text="start timer", command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, text="pause", command=self.pauseTimer) self.stopButton = Button(self.controlPanel, text="stop", command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, text="delay:") self.timerInput = Entry(self.controlPanel, width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, text="fade:") self.fadeInput = Entry(self.controlPanel, width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, text="standby", command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, text="sync", command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, text="reconnect", command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton( self.controlPanel, text="use all projectors", variable=self.cycle, command=self.cycleToggled ) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, from_=0, to=self.controller.maxTray, label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", command=self.interpretHEXDialog) self.helpmenu.add_command( label="About EktaproGUI", command=lambda: tkMessageBox.showinfo("About EktaproGUI", "EktaproGUI 1.0 (C)opyright Julian Hoch 2010"), ) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) # @UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class DirList(object): def __init__(self, initdir=None): self.top = Tk() self.label = Label( self.top, text='用户管理 v0.8', font=('Helvetica', 12, 'bold'), ) self.label.pack() self.cwd = StringVar(self.top) self.dirl = Label(self.top, fg='blue', font=('Helvetica', 12, 'bold')) self.dirl.pack() self.dirfm = Frame(self.top) self.dirsb = Scrollbar(self.dirfm) self.dirsb.pack(side=RIGHT, fill=Y) self.dirs = Listbox(self.dirfm, height=15, width=50, yscrollcommand=self.dirsb.set) self.dirs.bind('<Double-1>', self.setdirandgo) self.dirsb.config(command=self.dirs.yview) self.dirs.pack(side=LEFT, fill=BOTH) self.dirfm.pack() self.dirn = Entry(self.top, width=50, textvariable=self.cwd) self.dirn.bind('<Return>', self.dols) self.dirn.pack() self.bfm = Frame(self.top) self.clr = Button(self.bfm, text='Clear', command=self.clrdir, activeforeground='white', activebackground='blue') self.ls = Button(self.bfm, text='List Directory', command=self.dols, activeforeground='white', activebackground='green') self.quit = Button(self.bfm, text='Quit', command=self.top.quit, activeforeground='white', activebackground='red') self.clr.pack(side=LEFT) self.ls.pack(side=LEFT) self.quit.pack(side=LEFT) self.bfm.pack() if initdir: self.cwd.set(os.curdir) self.dols() def clrdir(self, ev=None): self.cwd.set('') def setdirandgo(self, ev=None): self.last = self.cwd.get() self.dirs.config(selectbackground='red') check = self.dirs.get(self.dirs.curselection()) if not check: check = os.curdir self.cwd.set(check) self.dols() def dols(self, ev=None): error = '' tdir = self.cwd.get() if not tdir: tdir = os.curdir if not os.path.exists(tdir): error = tdir + ': no such file' elif not os.path.isdir(tdir): error = tdir + ': not a directory' if error: self.cwd.set(error) self.top.update() sleep(2) if not (hasattr(self, 'last') and self.last): self.last = os.curdir self.cwd.set(self.last) self.dirs.config( selectbackground='LightSkyBlue') self.top.update() return self.cwd.set( 'FETCHING DIRECTORY CONTENTS...') self.top.update() dirlist = os.listdir(tdir) dirlist.sort() os.chdir(tdir) self.dirl.config(text=os.getcwd()) self.dirs.delete(0, END) self.dirs.insert(END, os.curdir) self.dirs.insert(END, os.pardir) for eachFile in dirlist: self.dirs.insert(END, eachFile) self.cwd.set(os.curdir) self.dirs.config( selectbackground='LightSkyBlue')
class ListBoxChoice(object): def __init__(self, master=None, title=None, message=None, clist=[], newmessage=None): self.master = master self.value = None self.newmessage = newmessage self.list = clist[:] self.modalPane = Toplevel(self.master) self.modalPane.transient(self.master) self.modalPane.grab_set() self.modalPane.bind("<Return>", self._choose) self.modalPane.bind("<Escape>", self._cancel) if title: self.modalPane.title(title) if message: Label(self.modalPane, text=message).pack(padx=5, pady=5) listFrame = Frame(self.modalPane) listFrame.pack(side=TOP, padx=5, pady=5) scrollBar = Scrollbar(listFrame) scrollBar.pack(side=RIGHT, fill=Y) self.listBox = Listbox(listFrame, selectmode=SINGLE) self.listBox.pack(side=LEFT, fill=Y) scrollBar.config(command=self.listBox.yview) self.listBox.config(yscrollcommand=scrollBar.set) self.list.sort() for item in self.list: self.listBox.insert(END, item) if newmessage is not None: newFrame = Frame(self.modalPane) newFrame.pack(side=TOP, padx=5) Label(newFrame, text=newmessage).pack(padx=5, pady=5) self.entry = Entry(newFrame, width=30) self.entry.pack(side=TOP, padx=5) self.entry.bind("<Return>", self._choose_entry) buttonFrame = Frame(self.modalPane) buttonFrame.pack(side=BOTTOM) chooseButton = Button(buttonFrame, text="Choose", command=self._choose_entry) chooseButton.pack() cancelButton = Button(buttonFrame, text="Cancel", command=self._cancel) cancelButton.pack(side=RIGHT) def _choose_entry(self, event=None): if self.newmessage is None: self._choose() return v = self.entry.get().strip() if v == None or v == "": self._choose() return self.value = v self.modalPane.destroy() def _choose(self, event=None): try: firstIndex = self.listBox.curselection()[0] self.value = self.list[int(firstIndex)] except IndexError: self.value = None self.modalPane.destroy() def _cancel(self, event=None): self.modalPane.destroy() def returnValue(self): self.master.wait_window(self.modalPane) return self.value
class SelectPaths(MyFrame): def __init__(self, topframe=None): MyFrame.__init__(self, topframe=topframe) style = Style() style.theme_use('clam') self.patient_foler_path = "" self.patients = [] self.set_title('Brain segmentation GUI') self.add_ui_components() def add_ui_components(self): # Creating the frames. self.sub_frame1 = Frame(self) self.sub_frame1.grid(column=0, row=0) sub_frame2 = Frame(self) sub_frame2.grid(column=0, row=1) sub_frame3 = Frame(self) sub_frame3.grid(column=0, row=2) sub_frame21 = Frame(sub_frame2) sub_frame21.grid(column=0, row=0) sub_frame22 = Frame(sub_frame2) sub_frame22.grid(padx=20, column=1, row=0) sub_frame221 = Frame(sub_frame22) sub_frame221.grid(row=1, column=0) # Creating the top-menu buttons. self.visualise_button = Button(self.sub_frame1, text="Visualise", command=self.start_visualisation) self.visualise_button.grid(row=0, column=1) self.help_button = Button(self.sub_frame1, text="Help", command=self.open_help) self.help_button.grid(row=0, column=2) # Creating the select modality path. self.modality_label = Label(sub_frame21, text="Path to patient folders", relief=FLAT) self.modality_label.grid(row=1, column=1) self.modality_path_entry = Entry(sub_frame21) self.modality_path_entry.grid(row=2, column=1) #self.modality_path_entry.set(self.patient_folder_path) self.modality_path_button = Button( sub_frame21, text="Choose", command=self.choose_directory_and_import) self.modality_path_button.grid(row=2, column=2) # Creating the patients listbox. self.label_patients = Label(sub_frame22, text="Patients") self.label_patients.grid(row=0, column=0) self.listbox_patients = Listbox(sub_frame221, selectmode='multiple', width=50, height=10) self.listbox_patients.pack(side=LEFT, fill=Y) #self.listbox_patients.grid(row=1, column=0) self.listbox_patients.bind("<Button-1>", self.listbox_changed) self.scrollbar = Scrollbar(sub_frame221) self.scrollbar.pack(side=RIGHT, fill=Y) # attach listbox to scrollbar self.listbox_patients.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.listbox_patients.yview) # Creating the status console. self.status_text = Text(sub_frame3, height=5) self.status_text.grid(column=0, row=0) self.status_text.tag_configure('title', justify='center', font="Arial 10 bold") self.status_text.tag_configure('entry', justify='left', font="Arial 9") self.status_text.insert(END, 'Status Console', 'title') self.status_text_entry_number = 1 self.status_text.configure(state='disabled') # ***** EVENTS - START******************************** def start_visualisation(self): """ Launch visualisation module. Linked to self.visualise_button (Button). """ patient_path = os.path.join(self.patient_folder_path, 'processed_' + self.patients[0]) segmentation_path = os.path.join( patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz') supervoxel_path = os.path.join( patient_path, SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz') # check if the supervoxels and the segmentation exist if not os.path.exists(supervoxel_path): supervoxel_path = None if not os.path.exists(segmentation_path): segmentation_path = None mod_paths = [] for mod in MODALITY_PREFIXES: mod_paths.append(\ os.path.join(patient_path, mod+'_'+self.patients[0]+'.nii.gz')) vis = vv.VisualVolumes(image_paths=mod_paths, segm_path=segmentation_path, supervoxel_id_path=supervoxel_path, topframe=self.master) vis.tkraise() def listbox_changed(self, event): """ Add a patient upon selection in the listbox. Linked to self.listbox_patients (Listbox). """ indices = list(self.listbox_patients.curselection()) selected_idx = self.listbox_patients.nearest(event.y) if selected_idx == -1: return # remove or add a patient index if selected_idx not in indices: indices.append(selected_idx) else: indices.remove(selected_idx) # set self.patients based on the new patient indices and enable visualisation if only one is selected. self.patients = [] for idx in indices: self.patients.append(self.listbox_patients.get(idx).split(' ')[0]) if len(self.patients) == 1: self.visualise_button['state'] = 'enabled' else: self.visualise_button['state'] = 'disabled' def choose_directory_and_import(self): """ Allow the user to select an import path. Linked to self.modality_path_button (Button), and sets self.modality_path_entry (Entry). """ initialdir = DATA_PATH msg = 'Select directory containing patients' path = askdirectory(title=msg, initialdir=initialdir) # update the text box. self.modality_path_entry.delete(0, END) self.modality_path_entry.insert(0, str(path)) # Adding the modality paths after the folder is selected. self.patient_folder_path = self.modality_path_entry.get() if os.path.exists(self.patient_folder_path): patients_validation = os.listdir(self.patient_folder_path) # Checking if the patient has the right modalities and importing the patient. for i, patient in enumerate(patients_validation): # Checking if the patient was already processed. if patient.startswith('processed_') or os.path.exists( os.path.join(self.patient_folder_path, 'processed_' + patient)): print("The files of the patient " + patient + " are already copied") continue # If everything is fine, then it continues to makign folders and copying files # Copying the files into the new folder. valid = self._convert_and_copy_files(patient) if not valid: patients_validation[i] = None # We make a list of patients with only ids for the listbox. valid_patients = [p for p in patients_validation if p is not None] self.list_existing_patients(valid_patients) def _convert_and_copy_files(self, patient): """ Check if all valid files exist for this patient and return True if so. """ # Getting the list of modalities for every patient. patient_path = os.path.join(self.patient_folder_path, patient) modalities = os.listdir(patient_path) # Look for paths valid_paths = {} prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES for prefix in prefices: candidates = [modality \ for modality in modalities \ if modality.startswith(prefix+'.')] if len(candidates) != 1: err = '%s file not identified. Look for ambiguities in %s.' \ % (prefix, patient_path) print(err) return False modality = candidates[0] if not any([ modality.endswith(ext) for ext in ['.mha', '.nii', '.nii.gz'] ]): err = "Image format not recognized: %s. In %s" \ % (modality, patient_path) print(err) return False valid_paths[prefix] = modality # Creating a processed patient folder. os.mkdir(os.path.join(self.patient_folder_path, 'processed_' + patient)) for prefix, basename in valid_paths.iteritems(): shutil.copyfile( os.path.join(self.patient_folder_path, patient, basename), os.path.join(self.patient_folder_path, 'processed_' + patient, prefix + '_' + patient + '.nii.gz')) return True def open_help(self): self.help_window = help_window.HelpWindow() self.help_window.tkraise() # ***** EVENTS - END*************************** def list_existing_patients(self, patients=None): print("Importing existing patients") # We make a list of patients with only ids for the listbox. if patients is None: patients = os.listdir(self.patient_folder_path) self.patients = [] for patient in patients: if not patient.startswith('processed_'): self.patients.append(patient) self.patients.sort() self.populate_patient_listbox(self.patients) if self.listbox_patients.size() > 0: self.listbox_patients.selection_set(0) self.status_text.configure(state='normal') self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Patients are imported.', 'entry') self.status_text_entry_number += 1 self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Please select a patient to proceed', 'entry') self.status_text_entry_number += 1 self.status_text.configure(state='disabled') def populate_patient_listbox(self, patients): self.listbox_patients.delete(0, END) for patient in patients: patient_path = os.path.join(self.patient_folder_path, 'processed_' + patient) #check if a given patient has a label if os.path.exists( os.path.join( patient_path, 'corrected_' + SEGM_PREFIX + '_' + patient + '.nii.gz')): patient = patient + ' - segmentation corrected' self.listbox_patients.insert(END, patient)
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol('WM_DELETE_WINDOW', self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", \ self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, \ text="init", \ command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, \ text="next slide", \ command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, \ text="previous slide", \ command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, \ text="start timer", \ command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, \ text="pause", \ command=self.pauseTimer) self.stopButton = Button(self.controlPanel, \ text="stop", \ command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, \ text="delay:") self.timerInput = Entry(self.controlPanel, \ width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, \ text="fade:") self.fadeInput = Entry(self.controlPanel, \ width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, \ text="standby", \ command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, \ text="sync", \ command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, \ text="reconnect", \ command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton(self.controlPanel, \ text="use all projectors", \ variable=self.cycle, \ command=self.cycleToggled) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, \ label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, \ from_=0, to=self.controller.maxTray, \ label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W , expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", \ command=self.interpretHEXDialog) self.helpmenu.add_command(label="About EktaproGUI", \ command=lambda:tkMessageBox.showinfo("About EktaproGUI", \ "EktaproGUI 1.0 (C)opyright Julian Hoch 2010")) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness \ and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) #@UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" \ and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class Window(Frame): RENDER_PROCESSES = 2 def __init__(self, width, height, scene, tracer, calculate=None): Frame.__init__(self, master=None) if calculate is None: calculate = [0, 0] self.d = calculate self.scene = scene self.after_id = 0 self.tracer = tracer self.width = width self.height = height self.__init_window(height, width) self.master.mainloop() def __init_window(self, height, width): self.master.title = "Ray Py" canvas = Canvas(self.master, width=width, height=height) canvas.pack(side=TOP) self.img = PhotoImage(width=width, height=height) canvas.create_image((width / 2, height / 2), image=self.img, state="normal") self.startButton = Button(self.master, text="Render", command=lambda: self.__onStartPressed()) self.startButton.pack(side=RIGHT) self.resetButton = Button(self.master, text="Reset", command=lambda: self.__onResetPressed()) self.resetButton.config(state="disabled") self.resetButton.pack(side=RIGHT) self.listbox = Listbox(self.master, height=5) self.listbox.bind('<<ListboxSelect>>', self.__selectTracer) self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow", "Recursive", "PathTracer") self.listbox.pack(side=LEFT) self.listbox.selection_set(0) self.listbox.activate(0) self.listbox.focus_set() def __selectTracer(self, evt): value = self.listbox.get(self.listbox.curselection()) if value == "Simple": self.tracer = SimpleRayTracer() elif value == "Shadow": self.tracer = SimpleShadowRayTracer() elif value == "ShadingShadow": self.tracer = ShadingShadowRayTracer(self.scene.eye) elif value == "Recursive": self.tracer = RecursiveRayTracer(self.scene.eye) elif value == "PathTracer": self.tracer = PathTracer(self.scene.eye) def __onStartPressed(self): self.startButton.config(state="disabled") self.listbox.config(state="disabled") self.__draw() def __update(self): if self.finishedQueue.qsize() >= self.RENDER_PROCESSES: self.finishedThreads = self.RENDER_PROCESSES while not self.finishedQueue.empty(): self.finishedQueue.get() if not self.dataQueue.empty(): item = self.dataQueue.get() self.img.put(item[1], item[0]) self.master.update() elif self.finishedThreads == self.RENDER_PROCESSES: for t in self.threads: t.join() self.master.after_cancel(self.after_id) self.resetButton.config(state="active") return self.after_id = self.master.after(0, self.__update) def __draw(self): from processes import BlockProcess from multiprocessing import Queue self.finishedQueue = Queue() self.dataQueue = Queue() self.finishedThreads = 0 self.threads = BlockProcess.forCount(self.RENDER_PROCESSES, self.width, self.height, self.tracer, self.scene, self.dataQueue, self.finishedQueue) for t in self.threads: t.start() self.__update() self.after_id = self.master.after(0, self.__update) def __onResetPressed(self): self.img.blank() self.d = [0, 0] self.resetButton.config(state="disabled") self.startButton.config(state="active") self.listbox.config(state="normal")
class Downloader(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Book downloader") self.style = Style() self.style.theme_use("default") framesearch = Frame(self) framesearch.pack(fill=BOTH) search_label = Label(framesearch, text="Filter books:", padx=5, pady=5, width=15) search_label.pack(side=LEFT) self.search_entry = Entry(framesearch) self.search_entry.pack(side=RIGHT, fill=X) self.search_entry.bind("<Return>", self.searchHandler) #self.search_entry.bind("<Key>", self.searchHandler) framelist = Frame(self, relief=RAISED, borderwidth=1) framelist.pack(fill=BOTH, expand=True) self.lb = Listbox(framelist, height=30) scrollbar = Scrollbar(framelist) scrollbar.pack(side=RIGHT, fill=Y) self.lb.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.lb.yview) self.loadLibrary() for b in self.book_list: self.lb.insert(END, b[0]) self.lb.pack(fill=BOTH) self.pack(fill=BOTH, expand=True) DownButton = Button(self, text="Download", command=self.downloadAction) DownButton.pack(side=RIGHT) def downloadAction(self): bookUrls = [] selected = self.lb.curselection() if len(selected)<1: tkMessageBox.showerror("Select books to Download", "You have to select the books you want to download") return for b in selected: item = self.lb.get(b) for b2 in self.book_list: if item==b2[0]: bookUrls.append(b2[1]) self.lb.delete(b) break for burl in bookUrls: print("Starting thread for %s" % burl) retriver = Retriver() retriver.setUrl(burl) retriver.start() def searchHandler(self, event): filterStr = self.search_entry.get() self.lb.delete(0, END) if filterStr=="": for b in self.book_list: self.lb.insert(END, b[0]) else: for b in self.book_list: if b[0].lower().find(filterStr.lower())>-1: self.lb.insert(END, b[0]) def getPageHTML(self, page_num=1): pageurl = "http://www.allitebooks.com/page/" + str(page_num) fh = urllib.urlopen(pageurl) if fh.getcode()==200: txt= fh.read() fh.close() return txt else: return '' def loadBooksInPage(self, page_num=1): html = self.getPageHTML(page_num) if len(html)==0: return False soup = BeautifulSoup(html, "lxml") for h2 in soup.find_all('h2','entry-title'): alink = h2.a if alink != None: aurl = alink['href'] atxt = alink.text self.book_list.append ( [atxt, aurl] ) print("%i: %s" % (self.books, atxt)) self.books += 1 return True def loadLibrary(self): self.book_list = [] self.books = 0 print("Getting the list of books") p = 1 while(self.loadBooksInPage(p) ): p=p+1 self.book_list.sort() if len(self.book_list)<1: sys.exit("Couldn't find books online, please check your internet access")
class CenterFrame(BasePAFrame): """ фрейм со списком файлов """ def __init__(self, *args, **kwargs): self.w_frame_child = kwargs.pop('child_frame') BasePAFrame.__init__(self, *args, **kwargs) self.w_listbox_files = Listbox(self) self.w_scrollbar_files = Scrollbar(self) self.catalog = None self.catalog_files = [] def _pa_configure(self): BasePAFrame._pa_configure(self) self.w_listbox_files.config(yscrollcommand=self.w_scrollbar_files.set) self.w_scrollbar_files.config(command=self.w_listbox_files.yview) self.w_listbox_files.bind( '<<ListboxSelect>>', self.select_listbox_file) def _pa_layout(self): BasePAFrame._pa_layout(self) w_listbox_files_width = 0.95 self.w_listbox_files.place( relx=0, rely=0, relwidth=w_listbox_files_width, relheight=1) self.w_scrollbar_files.place( relx=w_listbox_files_width, rely=0, relwidth=1-w_listbox_files_width, relheight=1) def set_catalog(self, catalog=None): """ задаем новый каталог для отображения :param catalog: словарь { 'path': путь к каталогу } :return: """ try: current_index = self.w_listbox_files.curselection()[0] except IndexError: current_index = 0 if 0 < current_index < len(self.catalog_files): set_index = current_index + 1 else: set_index = current_index self.catalog = catalog self.catalog_files = [] self.w_listbox_files.delete(0, END) self.w_frame_child.set_file(None) if self.catalog is not None: catalog_path = self.catalog for file_name in os.listdir(catalog_path): file_path = os.path.join(catalog_path, file_name) if os.path.isfile(file_path): self.catalog_files.append({ 'name': file_name, 'path': file_path}) self.catalog_files.sort(key=lambda x: x['name']) catalog_files = [catalog['name'] for catalog in self.catalog_files] self.w_listbox_files.insert(END, *catalog_files) self.w_listbox_files.selection_set(set_index) self.w_listbox_files.see(set_index) self.w_listbox_files.event_generate("<<ListboxSelect>>") def update_catalog(self): self.set_catalog(self.catalog) def select_listbox_file(self, event): """ обработчик выбора файла в списке файлов :param event: :return: """ try: index = self.w_listbox_files.curselection()[0] file_ = self.catalog_files[index] except IndexError: return else: self.w_frame_child.set_file(file_)
class RecursiveDescentApp(object): """ A graphical tool for exploring the recursive descent parser. The tool displays the parser's tree and the remaining text, and allows the user to control the parser's operation. In particular, the user can expand subtrees on the frontier, match tokens on the frontier against the text, and backtrack. A "step" button simply steps through the parsing process, performing the operations that ``RecursiveDescentParser`` would use. """ def __init__(self, grammar, sent, trace=0): self._sent = sent self._parser = SteppingRecursiveDescentParser(grammar, trace) # Set up the main window. self._top = Tk() self._top.title('Recursive Descent Parser Application') # Set up key bindings. self._init_bindings() # Initialize the fonts. self._init_fonts(self._top) # Animations. animating_lock is a lock to prevent the demo # from performing new operations while it's animating. self._animation_frames = IntVar(self._top) self._animation_frames.set(5) self._animating_lock = 0 self._autostep = 0 # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_feedback(self._top) self._init_grammar(self._top) self._init_canvas(self._top) # Initialize the parser. self._parser.initialize(self._sent) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = tkFont.Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = tkFont.Font(family='helvetica', weight='bold', size=self._size.get()) self._font = tkFont.Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = tkFont.Font(family='helvetica', weight='bold', size=big) def _init_grammar(self, parent): # Grammar view. self._prodframe = listframe = Frame(parent) self._prodframe.pack(fill='both', side='left', padx=2) self._prodlist_label = Label(self._prodframe, font=self._boldfont, text='Available Expansions') self._prodlist_label.pack() self._prodlist = Listbox(self._prodframe, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._prodlist.pack(side='right', fill='both', expand=1) self._productions = list(self._parser.grammar().productions()) for production in self._productions: self._prodlist.insert('end', (' %s' % production)) self._prodlist.config(height=min(len(self._productions), 25)) # Add a scrollbar if there are more than 25 productions. if len(self._productions) > 25: listscroll = Scrollbar(self._prodframe, orient='vertical') self._prodlist.config(yscrollcommand = listscroll.set) listscroll.config(command=self._prodlist.yview) listscroll.pack(side='left', fill='y') # If they select a production, apply it. self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('e', self.expand) #self._top.bind('<Alt-e>', self.expand) #self._top.bind('<Control-e>', self.expand) self._top.bind('m', self.match) self._top.bind('<Alt-m>', self.match) self._top.bind('<Control-m>', self.match) self._top.bind('b', self.backtrack) self._top.bind('<Alt-b>', self.backtrack) self._top.bind('<Control-b>', self.backtrack) self._top.bind('<Control-z>', self.backtrack) self._top.bind('<BackSpace>', self.backtrack) self._top.bind('a', self.autostep) #self._top.bind('<Control-a>', self.autostep) self._top.bind('<Control-space>', self.autostep) self._top.bind('<Control-c>', self.cancel_autostep) self._top.bind('<space>', self.step) self._top.bind('<Delete>', self.reset) self._top.bind('<Control-p>', self.postscript) #self._top.bind('<h>', self.help) #self._top.bind('<Alt-h>', self.help) self._top.bind('<Control-h>', self.help) self._top.bind('<F1>', self.help) #self._top.bind('<g>', self.toggle_grammar) #self._top.bind('<Alt-g>', self.toggle_grammar) #self._top.bind('<Control-g>', self.toggle_grammar) self._top.bind('<Control-g>', self.edit_grammar) self._top.bind('<Control-t>', self.edit_sentence) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button(buttonframe, text='Step', background='#90c0d0', foreground='black', command=self.step,).pack(side='left') Button(buttonframe, text='Autostep', background='#90c0d0', foreground='black', command=self.autostep,).pack(side='left') Button(buttonframe, text='Expand', underline=0, background='#90f090', foreground='black', command=self.expand).pack(side='left') Button(buttonframe, text='Match', underline=0, background='#90f090', foreground='black', command=self.match).pack(side='left') Button(buttonframe, text='Backtrack', underline=0, background='#f0a0a0', foreground='black', command=self.backtrack).pack(side='left') # Replace autostep... # self._autostep_button = Button(buttonframe, text='Autostep', # underline=0, command=self.autostep) # self._autostep_button.pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2) self._redraw() def _init_feedback(self, parent): self._feedbackframe = feedbackframe = Frame(parent) feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3) self._lastoper_label = Label(feedbackframe, text='Last Operation:', font=self._font) self._lastoper_label.pack(side='left') lastoperframe = Frame(feedbackframe, relief='sunken', border=1) lastoperframe.pack(fill='x', side='right', expand=1, padx=5) self._lastoper1 = Label(lastoperframe, foreground='#007070', background='#f0f0f0', font=self._font) self._lastoper2 = Label(lastoperframe, anchor='w', width=30, foreground='#004040', background='#f0f0f0', font=self._font) self._lastoper1.pack(side='left') self._lastoper2.pack(side='left', fill='x', expand=1) def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Reset Parser', underline=0, command=self.reset, accelerator='Del') filemenu.add_command(label='Print to Postscript', underline=0, command=self.postscript, accelerator='Ctrl-p') filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='Ctrl-x') menubar.add_cascade(label='File', underline=0, menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label='Edit Grammar', underline=5, command=self.edit_grammar, accelerator='Ctrl-g') editmenu.add_command(label='Edit Text', underline=5, command=self.edit_sentence, accelerator='Ctrl-t') menubar.add_cascade(label='Edit', underline=0, menu=editmenu) rulemenu = Menu(menubar, tearoff=0) rulemenu.add_command(label='Step', underline=1, command=self.step, accelerator='Space') rulemenu.add_separator() rulemenu.add_command(label='Match', underline=0, command=self.match, accelerator='Ctrl-m') rulemenu.add_command(label='Expand', underline=0, command=self.expand, accelerator='Ctrl-e') rulemenu.add_separator() rulemenu.add_command(label='Backtrack', underline=0, command=self.backtrack, accelerator='Ctrl-b') menubar.add_cascade(label='Apply', underline=0, menu=rulemenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_checkbutton(label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar) viewmenu.add_separator() viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) animatemenu = Menu(menubar, tearoff=0) animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animation_frames, value=0) animatemenu.add_radiobutton(label="Slow Animation", underline=0, variable=self._animation_frames, value=10, accelerator='-') animatemenu.add_radiobutton(label="Normal Animation", underline=0, variable=self._animation_frames, value=5, accelerator='=') animatemenu.add_radiobutton(label="Fast Animation", underline=0, variable=self._animation_frames, value=2, accelerator='+') menubar.add_cascade(label="Animate", underline=1, menu=animatemenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) helpmenu.add_command(label='Instructions', underline=0, command=self.help, accelerator='F1') menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Helper ######################################### def _get(self, widget, treeloc): for i in treeloc: widget = widget.subtrees()[i] if isinstance(widget, TreeSegmentWidget): widget = widget.node() return widget ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old tree, widgets, etc. if self._tree is not None: self._cframe.destroy_widget(self._tree) for twidget in self._textwidgets: self._cframe.destroy_widget(twidget) if self._textline is not None: self._canvas.delete(self._textline) # Draw the tree. helv = ('helvetica', -self._size.get()) bold = ('helvetica', -self._size.get(), 'bold') attribs = {'tree_color': '#000000', 'tree_width': 2, 'node_font': bold, 'leaf_font': helv,} tree = self._parser.tree() self._tree = tree_to_treesegment(canvas, tree, **attribs) self._cframe.add_widget(self._tree, 30, 5) # Draw the text. helv = ('helvetica', -self._size.get()) bottom = y = self._cframe.scrollregion()[3] self._textwidgets = [TextWidget(canvas, word, font=self._font) for word in self._sent] for twidget in self._textwidgets: self._cframe.add_widget(twidget, 0, 0) twidget.move(0, bottom-twidget.bbox()[3]-5) y = min(y, twidget.bbox()[1]) # Draw a line over the text, to separate it from the tree. self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.') # Highlight appropriate nodes. self._highlight_nodes() self._highlight_prodlist() # Make sure the text lines up. self._position_text() def _redraw_quick(self): # This should be more-or-less sufficient after an animation. self._highlight_nodes() self._highlight_prodlist() self._position_text() def _highlight_nodes(self): # Highlight the list of nodes to be checked. bold = ('helvetica', -self._size.get(), 'bold') for treeloc in self._parser.frontier()[:1]: self._get(self._tree, treeloc)['color'] = '#20a050' self._get(self._tree, treeloc)['font'] = bold for treeloc in self._parser.frontier()[1:]: self._get(self._tree, treeloc)['color'] = '#008080' def _highlight_prodlist(self): # Highlight the productions that can be expanded. # Boy, too bad tkinter doesn't implement Listbox.itemconfig; # that would be pretty useful here. self._prodlist.delete(0, 'end') expandable = self._parser.expandable_productions() untried = self._parser.untried_expandable_productions() productions = self._productions for index in range(len(productions)): if productions[index] in expandable: if productions[index] in untried: self._prodlist.insert(index, ' %s' % productions[index]) else: self._prodlist.insert(index, ' %s (TRIED)' % productions[index]) self._prodlist.selection_set(index) else: self._prodlist.insert(index, ' %s' % productions[index]) def _position_text(self): # Line up the text widgets that are matched against the tree numwords = len(self._sent) num_matched = numwords - len(self._parser.remaining_text()) leaves = self._tree_leaves()[:num_matched] xmax = self._tree.bbox()[0] for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] widget['color'] = '#006040' leaf['color'] = '#006040' widget.move(leaf.bbox()[0] - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # Line up the text widgets that are not matched against the tree. for i in range(len(leaves), numwords): widget = self._textwidgets[i] widget['color'] = '#a0a0a0' widget.move(xmax - widget.bbox()[0], 0) xmax = widget.bbox()[2] + 10 # If we have a complete parse, make everything green :) if self._parser.currently_complete(): for twidget in self._textwidgets: twidget['color'] = '#00a000' # Move the matched leaves down to the text. for i in range(0, len(leaves)): widget = self._textwidgets[i] leaf = leaves[i] dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0 dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10) leaf.move(0, dy) def _tree_leaves(self, tree=None): if tree is None: tree = self._tree if isinstance(tree, TreeSegmentWidget): leaves = [] for child in tree.subtrees(): leaves += self._tree_leaves(child) return leaves else: return [tree] ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def reset(self, *e): self._autostep = 0 self._parser.initialize(self._sent) self._lastoper1['text'] = 'Reset Application' self._lastoper2['text'] = '' self._redraw() def autostep(self, *e): if self._animation_frames.get() == 0: self._animation_frames.set(2) if self._autostep: self._autostep = 0 else: self._autostep = 1 self._step() def cancel_autostep(self, *e): #self._autostep_button['text'] = 'Autostep' self._autostep = 0 # Make sure to stop auto-stepping if we get any user input. def step(self, *e): self._autostep = 0; self._step() def match(self, *e): self._autostep = 0; self._match() def expand(self, *e): self._autostep = 0; self._expand() def backtrack(self, *e): self._autostep = 0; self._backtrack() def _step(self): if self._animating_lock: return # Try expanding, matching, and backtracking (in that order) if self._expand(): pass elif self._parser.untried_match() and self._match(): pass elif self._backtrack(): pass else: self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' self._autostep = 0 # Check if we just completed a parse. if self._parser.currently_complete(): self._autostep = 0 self._lastoper2['text'] += ' [COMPLETE PARSE]' def _expand(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.expand() if rv is not None: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = rv self._prodlist.selection_clear(0, 'end') index = self._productions.index(rv) self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = '(all expansions tried)' return 0 def _match(self, *e): if self._animating_lock: return old_frontier = self._parser.frontier() rv = self._parser.match() if rv is not None: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = rv self._animate_match(old_frontier[0]) return 1 else: self._lastoper1['text'] = 'Match:' self._lastoper2['text'] = '(failed)' return 0 def _backtrack(self, *e): if self._animating_lock: return if self._parser.backtrack(): elt = self._parser.tree() for i in self._parser.frontier()[0]: elt = elt[i] self._lastoper1['text'] = 'Backtrack' self._lastoper2['text'] = '' if isinstance(elt, Tree): self._animate_backtrack(self._parser.frontier()[0]) else: self._animate_match_backtrack(self._parser.frontier()[0]) return 1 else: self._autostep = 0 self._lastoper1['text'] = 'Finished' self._lastoper2['text'] = '' return 0 def about(self, *e): ABOUT = ("NLTK Recursive Descent Parser Application\n"+ "Written by Edward Loper") TITLE = 'About: Recursive Descent Parser Application' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def help(self, *e): self._autostep = 0 # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75, font='fixed') except: ShowText(self._top, 'Help: Recursive Descent Parser Application', (__doc__ or '').strip(), width=75) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size+2))) self._redraw() ######################################### ## Expand Production Selection ######################################### def _toggle_grammar(self, *e): if self._show_grammar.get(): self._prodframe.pack(fill='both', side='left', padx=2, after=self._feedbackframe) self._lastoper1['text'] = 'Show Grammar' else: self._prodframe.pack_forget() self._lastoper1['text'] = 'Hide Grammar' self._lastoper2['text'] = '' # def toggle_grammar(self, *e): # self._show_grammar = not self._show_grammar # if self._show_grammar: # self._prodframe.pack(fill='both', expand='y', side='left', # after=self._feedbackframe) # self._lastoper1['text'] = 'Show Grammar' # else: # self._prodframe.pack_forget() # self._lastoper1['text'] = 'Hide Grammar' # self._lastoper2['text'] = '' def _prodlist_select(self, event): selection = self._prodlist.curselection() if len(selection) != 1: return index = int(selection[0]) old_frontier = self._parser.frontier() production = self._parser.expand(self._productions[index]) if production: self._lastoper1['text'] = 'Expand:' self._lastoper2['text'] = production self._prodlist.selection_clear(0, 'end') self._prodlist.selection_set(index) self._animate_expand(old_frontier[0]) else: # Reset the production selections. self._prodlist.selection_clear(0, 'end') for prod in self._parser.expandable_productions(): index = self._productions.index(prod) self._prodlist.selection_set(index) ######################################### ## Animation ######################################### def _animate_expand(self, treeloc): oldwidget = self._get(self._tree, treeloc) oldtree = oldwidget.parent() top = not isinstance(oldtree.parent(), TreeSegmentWidget) tree = self._parser.tree() for i in treeloc: tree = tree[i] widget = tree_to_treesegment(self._canvas, tree, node_font=self._boldfont, leaf_color='white', tree_width=2, tree_color='white', node_color='white', leaf_font=self._font) widget.node()['color'] = '#20a050' (oldx, oldy) = oldtree.node().bbox()[:2] (newx, newy) = widget.node().bbox()[:2] widget.move(oldx-newx, oldy-newy) if top: self._cframe.add_widget(widget, 0, 5) widget.move(30-widget.node().bbox()[0], 0) self._tree = widget else: oldtree.parent().replace_child(oldtree, widget) # Move the children over so they don't overlap. # Line the children up in a strange way. if widget.subtrees(): dx = (oldx + widget.node().width()/2 - widget.subtrees()[0].bbox()[0]/2 - widget.subtrees()[0].bbox()[2]/2) for subtree in widget.subtrees(): subtree.move(dx, 0) self._makeroom(widget) if top: self._cframe.destroy_widget(oldtree) else: oldtree.destroy() colors = ['gray%d' % (10*int(10*x/self._animation_frames.get())) for x in range(self._animation_frames.get(),0,-1)] # Move the text string down, if necessary. dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1] if dy > 0: for twidget in self._textwidgets: twidget.move(0, dy) self._canvas.move(self._textline, 0, dy) self._animate_expand_frame(widget, colors) def _makeroom(self, treeseg): """ Make sure that no sibling tree bbox's overlap. """ parent = treeseg.parent() if not isinstance(parent, TreeSegmentWidget): return index = parent.subtrees().index(treeseg) # Handle siblings to the right rsiblings = parent.subtrees()[index+1:] if rsiblings: dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10 for sibling in rsiblings: sibling.move(dx, 0) # Handle siblings to the left if index > 0: lsibling = parent.subtrees()[index-1] dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10) treeseg.move(dx, 0) # Keep working up the tree. self._makeroom(parent) def _animate_expand_frame(self, widget, colors): if len(colors) > 0: self._animating_lock = 1 widget['color'] = colors[0] for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = colors[0] else: subtree['color'] = colors[0] self._top.after(50, self._animate_expand_frame, widget, colors[1:]) else: widget['color'] = 'black' for subtree in widget.subtrees(): if isinstance(subtree, TreeSegmentWidget): subtree.node()['color'] = 'black' else: subtree['color'] = 'black' self._redraw_quick() widget.node()['color'] = 'black' self._animating_lock = 0 if self._autostep: self._step() def _animate_backtrack(self, treeloc): # Flash red first, if we're animating. if self._animation_frames.get() == 0: colors = [] else: colors = ['#a00000', '#000000', '#a00000'] colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get()))) for x in range(1, self._animation_frames.get()+1)] widgets = [self._get(self._tree, treeloc).parent()] for subtree in widgets[0].subtrees(): if isinstance(subtree, TreeSegmentWidget): widgets.append(subtree.node()) else: widgets.append(subtree) self._animate_backtrack_frame(widgets, colors) def _animate_backtrack_frame(self, widgets, colors): if len(colors) > 0: self._animating_lock = 1 for widget in widgets: widget['color'] = colors[0] self._top.after(50, self._animate_backtrack_frame, widgets, colors[1:]) else: for widget in widgets[0].subtrees(): widgets[0].remove_child(widget) widget.destroy() self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack(self, treeloc): widget = self._get(self._tree, treeloc) node = widget.parent().node() dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) / max(1, self._animation_frames.get())) self._animate_match_backtrack_frame(self._animation_frames.get(), widget, dy) def _animate_match(self, treeloc): widget = self._get(self._tree, treeloc) dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) / max(1, self._animation_frames.get())) self._animate_match_frame(self._animation_frames.get(), widget, dy) def _animate_match_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_frame, frame-1, widget, dy) else: widget['color'] = '#006040' self._redraw_quick() self._animating_lock = 0 if self._autostep: self._step() def _animate_match_backtrack_frame(self, frame, widget, dy): if frame > 0: self._animating_lock = 1 widget.move(0, dy) self._top.after(10, self._animate_match_backtrack_frame, frame-1, widget, dy) else: widget.parent().remove_child(widget) widget.destroy() self._animating_lock = 0 if self._autostep: self._step() def edit_grammar(self, *e): CFGEditor(self._top, self._parser.grammar(), self.set_grammar) def set_grammar(self, grammar): self._parser.set_grammar(grammar) self._productions = list(grammar.productions()) self._prodlist.delete(0, 'end') for production in self._productions: self._prodlist.insert('end', (' %s' % production)) def edit_sentence(self, *e): sentence = " ".join(self._sent) title = 'Edit Text' instr = 'Enter a new sentence to parse.' EntryDialog(self._top, sentence, instr, self.set_sentence, title) def set_sentence(self, sentence): self._sent = sentence.split() #[XX] use tagged? self.reset()
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])
class ResultList(Frame): """ Result List widget """ def __init__(self, master=None): Frame.__init__(self, master, padx=3, pady=3) self.columnconfigure(0, weight=1, minsize=50) self.columnconfigure(1, weight=1000) self.columnconfigure(2, weight=1, minsize=10) self.__createWidgets() self.show() def __createWidgets(self): self.lbl = Label(text="") self.lbl.grid(row=1, column=0, columnspan=2, in_=self) self.__hide_button = Button(text="Hide", command=self.hide) self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self) self.__yScroll = Scrollbar(orient=VERTICAL) self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE) self.__yScroll.config(command=self.list.yview) def show(self): self.__hide_button.config(text="Hide", command=self.hide) self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self) self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self) def hide(self): self.__hide_button.config(text="Show", command=self.show) self.list.grid_forget() self.__yScroll.grid_forget() def clear(self): self.list.delete(0, END) def fill(self, valList): self.clear() for v in valList: self.list.insert(END, v) self.list.see(0) self.select(0) def append(self, val): self.list.insert(END, val) self.list.see(END) def select(self, index=0): self.list.selection_set(index) def selected(self): return int(self.list.curselection()[0]) def width(self, width): self.list.config(width=width)