class filterswindow: ''' Interface graphique recapitulant les caracteristique du sismogramme presentant les options de filtrage et de calculs du noyau de sensibilite ''' def __init__(self,racine): self.canvas = Canvas(racine, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(racine, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global filterVar filterVar = 1 global text6a text6a = "1" global text6c1 text6c1 = StringVar() global text6c2 text6c2 = StringVar() global text6c3 text6c3 = StringVar() Label(self.frame, text="Option Filter").grid(row=0) Label(self.frame, text="\n").grid(row=1) Label(self.frame, text="lowest frequency ?").grid(row=4) e1 = Entry(self.frame, textvariable=text6c1) e1.grid(row=5) Label(self.frame, text="highest frequency ?").grid(row=20) e2 = Entry(self.frame, textvariable=text6c2) e2.grid(row=21) Label(self.frame, text="number of poles ?").grid(row=22) e3 = Entry(self.frame, textvariable=text6c3) e3.grid(row=23) Button(self.frame, text="continue", command=self.quitter).grid(row=24) def quitter(self): global racine racine.destroy() afficheSismoFiltre(textPath.get(), float(text6c1.get()), float(text6c2.get()), float(text6c3.get())) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def createCanvas( self ): "Create and return our scrolling canvas frame." f = Frame( self ) canvas = Canvas( f, width=self.cwidth, height=self.cheight, bg=self.bg ) # Scroll bars xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas
def initUI(self): #top frame using all the remaining space innerTopFrame = Frame(self, background="black") innerTopFrame.pack(fill=BOTH, expand=1) #CLOSE Label innerBottomLeftFrame = Frame(self, background="black") innerBottomLeftFrame.place(x=0, width=self.wRoot/2, y=self.hRoot-200, height=200) closeLabel = Label(innerBottomLeftFrame, bg="black", fg="black", text="CLOSE", font=("Comic Sans MS", 48, "bold")) innerBottomLeftFrame.bind("<Enter>", lambda f: closeLabel.config(fg="white")) innerBottomLeftFrame.bind("<Leave>", lambda f: closeLabel.config(fg="black")) innerBottomLeftFrame.bind("<Button-1>", lambda f: self.root.quit()) closeLabel.bind("<Button-1>", lambda f: self.root.quit()) closeLabel.pack(fill=BOTH) #SHUT DOWN Label innerBottomRightFrame = Frame(self, background="black") innerBottomRightFrame.place(x=self.wRoot/2, width=self.wRoot/2, y=self.hRoot-200, height=200) shutdownLabel = Label(innerBottomRightFrame, bg="black", fg="black", text="SHUT DOWN", font=("Comic Sans MS", 48, "bold")) innerBottomRightFrame.bind("<Enter>", lambda f: shutdownLabel.config(fg="white")) innerBottomRightFrame.bind("<Leave>", lambda f: shutdownLabel.config(fg="black")) innerBottomRightFrame.bind("<Button-1>", self.shutdown) shutdownLabel.bind("<Button-1>", self.shutdown) shutdownLabel.pack(fill=BOTH) #design the FullScreenApp self.pack(fill=BOTH, expand=1)
class RecapCalculs: ''' Interface graphique recapitulant les caracteristique du sismogramme presentant les options de filtrage et de calculs du noyau de sensibilite ''' def __init__(self,root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): self.message = Label(self.frame, text="Recapitulatif du sismogramme").grid(row=0) global X X=read(textPath.get()) self.recap = Listbox(self.frame, height = 15, width = 50) self.recap.insert(1, "network: {}\n".format(X[0].stats.network)) self.recap.insert(2, "station: {}\n".format(X[0].stats.station)) self.recap.insert(3, "location: {}\n".format(X[0].stats.location)) self.recap.insert(4, "channel: {}\n".format(X[0].stats.channel)) self.recap.insert(5, "start time: {}\n".format(X[0].stats.starttime)) self.recap.insert(6, "end time: {}\n".format(X[0].stats.endtime)) self.recap.insert(7, "sampling rate: {}\n".format(X[0].stats.sampling_rate)) self.recap.insert(8, "delta: {}\n".format(X[0].stats.delta)) self.recap.insert(9, "number points: {}\n".format(X[0].stats.npts)) self.recap.insert(10, "calibration: {}\n".format(X[0].stats.calib)) self.recap.insert(11, "event latitude: {}\n".format(X[0].stats.sac.evla)) self.recap.insert(12, "event longitude: {}\n".format(X[0].stats.sac.evlo)) self.recap.insert(13, "event depth: {}\n".format(X[0].stats.sac.evdp)) self.recap.insert(14, "station latitude: {}\n".format(X[0].stats.sac.stla)) self.recap.insert(15, "station longitude: {}\n".format(X[0].stats.sac.stlo)) self.recap.grid(row=0) #afficheGraphique() def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def run(self, robotip=DEFAULT_IP, imagename="image", port=9559): # Opens a tkinter window showing application ''' :param robotip: ip of bot :type: string :param port: port of bot on ip :type: int ''' #try: if __name__ == "__main__": try: tkinst = Tk() frame = Frame(tkinst, height=640, width=480) frame.bind("<Key>", move) frame.pack() subscriberID = self.vidproxy.subscribe( "subscriberID", 0, 11, 10) # 0,11,10 is correct numbers while True: image = self.vidproxy.getImageRemote(subscriberID) im = fromstring("RGB", (image[0], image[1]), str(bytearray(image[6]))) im.save(imagename + ".jpg") showimage = ImageTk.PhotoImage( Image.open(imagename + ".jpg").resize( (image[0] * 4, image[1] * 4), Image.ANTIALIAS)) w = Label(frame, image=showimage) w.image = showimage w.pack() tkinst.update() w.destroy() except Exception, e: print(str(e)) self.vidproxy.unsubscribe(subscriberID)
class EventManager: """Object used to manage callback functions for the events of a Widget Public Methods: ValideEvent(eventType) AddCallback(eventType, callback) SetCallback(func) RemoveCallback(eventType, func) ListBindings(event=None) """ # NOT USED, imstead I simply try to bind to a dummy widget to check if # the given event type is valid # # eventTypes = ('Key', 'KeyPress', 'KeyPress', # 'Button', 'ButtonPress', 'ButtonRelease', # 'Enter', 'Leave', 'Motion') # # eventModifiers = ('Control' 'Shift', 'Lock', # 'Button1', 'B1', 'Button2', 'B2','Button3', 'B3', # 'Button4', 'B4', 'Button5', 'B5', # 'Any', 'Double', 'Triple', # 'Mod1', 'M1', 'Meta', 'M', # 'Mod2', 'M2', 'Alt', # 'Mod3', 'M3', 'Mod4', 'M4', 'Mod5', 'M5' ) # buttonDetails = ( '1', '2', '3' ) # keyDetails = any keysym def __init__(self, widget): # keys are Tk events, values are lists of callback functions self.eventHandlers = {} self.widget = widget # create a dummy frame to try to bind event to check for event validity self.dummyFrame = Frame(widget,width=1, height=1) def DummyCallback(self, event): """dummy function used to check event validity""" pass def ValideEvent(self, eventType): """Check if an event is valide""" try: self.dummyFrame.bind(eventType, self.DummyCallback) except: return 0 return 1 def AddCallback(self, eventType, callback): """Add a callback fuction""" assert type(eventType) == type('string') assert callable(callback) # Here we should also check that callback has exactly 1 argument if not self.ValideEvent(eventType): raise ValueError('%s is not a valide event type' % eventType) if eventType in self.eventHandlers.keys(): self.eventHandlers[eventType].append(callback) else: self.eventHandlers[eventType] = [callback,] self.widget.bind(eventType, callback, '+') def BindFuncList(self,eventType, funcList): """Bind a list of functions to an event""" self.widget.bind(eventType, funcList[0]) for f in funcList[1:]: self.widget.bind(eventType, f, '+') def HasCallback(self, eventType, callback): """Check whether a function is registered as a callback for an event """ assert callable(callback) if self.eventHandlers.has_key(eventType): for f in self.eventHandlers[eventType]: if f==callback: return 1 return 0 def SetCallback(self, eventType, callback): """Set func as the callback or list of callback functions""" assert type(eventType) == type('string') if self.eventHandlers.has_key(eventType): funcList = self.eventHandlers[eventType] else: funcList = None if callable(callback): self.eventHandlers[eventType] = [callback,] self.widget.bind(eventType, callback) elif len(callback)>0: self.eventHandlers[eventType] = callback self.BindFuncList(eventType, callback) else: raise ValueError('First argument has to be a function or a list of\ functions') return funcList def FindFunctionByName(self, funcName, funcList): """find a function with a given name in a list of functions""" for f in funcList: if f.__name__==funcName: return f return None def RemoveCallback(self, eventType, func): """Delete function func from the list of callbacks for eventType""" if not self.eventHandlers.has_key(eventType): return None # raise ValueError('Widget %s has no event %s registered' % \ # self.widget, eventType) if type(func)==type('string'): func = self.FindFunctionByName(func, self.eventHandlers[eventType]) if not func: return try: self.eventHandlers[eventType].remove(func) except: pass if len(self.eventHandlers[eventType])==0: del self.eventHandlers[eventType] self.widget.bind(eventType, self.DummyCallback) else: self.BindFuncList(eventType, self.eventHandlers[eventType]) return func def ListOneBinding(self, key): """List all bindings for one events""" print 'Event', key if self.eventHandlers.has_key(key): for f in self.eventHandlers[key]: print '\t %s' % f.__name__ else: print '\tNone' def ListBindings(self, event=None): """List all bindings for one or all events""" if event is None: for k in self.eventHandlers.keys(): self.ListOneBinding(k) else: self.ListOneBinding(event)
class TreeNode: def __init__(self, canvas, parent, item, colortheme, vspace=20): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.edited = False self.children = [] self.colortheme =colortheme self.x = self.y = None self.vspace=vspace self.halfvspace=int(round(self.vspace/2)) self.evenodd=0 if not self.parent: self.canvas.bind('<Configure>',self.reconfig) def reconfig(self,*args): if len(self.canvas['scrollregion']) >0: w,n,e,s = self.canvas._getints(self.canvas['scrollregion']) if e < self.canvas.winfo_width(): e=self.canvas.winfo_width() for item in self.canvas.windows: win,x=item rightside=x+self.canvas._getints(self.canvas.itemcget(win,'width'))[0] if rightside<e: self.canvas.itemconfigure(win,width=e-x) def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): return name def select(self, event=None): if self.selected: return self.deselectall() self.selected = True # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnClick() def deselect(self, event=None): if not self.selected: return self.selected = False # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): self.deselecttree() if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y bottom = self.lastvisiblechild().y + self.vspace height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: self.canvas.evenodd=1 self.canvas.windows=[] oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) self.draw(5, 3) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor self.reconfig() def draw(self, x, y): if self.canvas.evenodd: self.evenodd=0 self.canvas.evenodd=0 else: self.evenodd=1 self.canvas.evenodd=1 self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y+self.vspace # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y+self.vspace for item in sublist: child = self.__class__(self.canvas, self, item, self.colortheme, self.vspace) self.children.append(child) cx = x+self.vspace cy = y+self.vspace cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x+self.halfvspace, cy+self.halfvspace, cx, cy+self.halfvspace, fill=self.colortheme.treelinescolor, stipple="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "tree_minus" callback = child.collapse else: iconname = "tree_plus" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x+self.halfvspace, cylast+self.halfvspace, image=image) self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x+self.halfvspace, y+self.halfvspace, x+self.halfvspace, cylast+self.halfvspace, stipple="gray50", fill=self.colortheme.treelinescolor) self.canvas.tag_lower(id) return cy def drawicon(self): return def drawtext(self): textx = self.x texty = self.y labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + self.halfvspace text = self.item.GetText() or "<no text>" if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "tree_node") else: imagename = self.item.GetIconName() or "tree_node" image = self.geticonimage(imagename) try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: self.frame = Frame(self.canvas, border=1, relief='flat') self.iconlabel = Label(self.frame, image=image, bd=0, padx=1, pady=1, anchor=W) self.label = Label(self.frame, text=text, bd=0, padx=3, pady=1, anchor=W) self.iconlabel.pack(side='left') self.label.pack(side='left', fill='y') widgets=[self.label,self.iconlabel, self.frame] if self.evenodd: bgcolor=self.colortheme.evencolor else: bgcolor=self.colortheme.editfieldbackground for widget in widgets: if self.selected: widget['bg']=self.colortheme.selectbackground else: widget['bg']=bgcolor if self.selected: self.label['fg']=self.colortheme.selectforeground else: self.label['fg']=self.colortheme.foreground width=self.frame.winfo_reqwidth() if width < self.canvas.winfo_width()-textx: width = self.canvas.winfo_width()-textx id = self.canvas.create_window(textx, texty, anchor=NW, window=self.frame, width=width) self.canvas.windows.append((id,textx)) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.iconlabel.bind("<1>", self.select_or_edit) self.iconlabel.bind("<Double-1>", self.flip) self.frame.bind("<1>", self.select_or_edit) self.frame.bind("<Double-1>", self.flip) self.label.bind("<Button-4>", self.unit_up) self.label.bind("<Button-5>", self.unit_down) self.iconlabel.bind("<Button-4>", self.unit_up) self.iconlabel.bind("<Button-5>", self.unit_down) self.frame.bind("<Button-4>", self.unit_up) self.frame.bind("<Button-5>", self.unit_down) self.text_id = id def unit_up(self, event): first,last=self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): first,last=self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(1, "unit") return "break" def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): if self.edited: return self.edited = True self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
class Path: def __init__(self, root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a text6a = "0" global filterVar filterVar = IntVar() global text6b text6b = StringVar() global t1x t1x = "" global t2x t2x = "" global t3x t3x = "" global t4x t4x = "" global text8_0 text8_0 = StringVar() global text8_1 text8_1 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) Label(self.frame, text="Filter name ?").grid(row=12) Entry(self.frame, textvariable=text6b).grid(row=13) Label(self.frame, text="time window t1 ?").grid(row=14) Labelt1 = Label(self.frame, text="-->").grid(row=15) Button(self.frame, text="time 1", command=self.time1).grid(row=15, column=1) Label(self.frame, text="time window t2 ?").grid(row=16) Labelt1 = Label(self.frame, text="-->").grid(row=17) Button(self.frame, text="time 2", command=self.time2).grid(row=17, column=1) ''' Label(self.frame, text="time window t3 ?").grid(row=18) Labelt1 = Label(self.frame, text="-->").grid(row=19) Button(self.frame, text="time 3", command=self.time3).grid(row=19, column=1) Label(self.frame, text="time window t4 ?").grid(row=20) Labelt1 = Label(self.frame, text="-->").grid(row=21) Button(self.frame, text="time 4", command=self.time4).grid(row=21, column=1) ''' def affiche0(): convertPara["text"]="No conversion" text8_1.set(0) def affiche1(): convertPara["text"]="Conversion" text8_0.set(0) convertPara = Menubutton(self.frame, text="Geodetic latitude to geocentric latitude conversion", relief=RAISED) convertPara.grid(row=0) convertPara.menu = Menu(convertPara, tearoff = 0) convertPara["menu"] = convertPara.menu convertPara.menu.add_checkbutton(label="No conversion", variable = text8_0, command = affiche0) convertPara.menu.add_checkbutton(label="Conversion", variable = text8_1, command = affiche1) convertPara.grid(row=22) b = Checkbutton(self.frame, text = "apply filter", variable = filterVar) b.grid(row=23, column = 0) Button(self.frame, text="continue", command=self.quitter).grid(row=23, column=1) def time1(self): global t1x global t1y t1x, t1y = Pointage() print type(t1x) print t1y def time2(self): global t2x global t2y t2x, t2y = Pointage() print t2x print t2y def time3(self): t3x, t3y = Pointage() print t3x print t3y def time4(self): t4x, t4y = Pointage() print t4x print t4y def quitter(self): root.destroy() def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
class OfxConverter(Frame): def __init__(self, parent): Frame.__init__(self, parent, background=u"white") self.parent = parent self.guiMap = [] self.debitValue = StringVar() self.creditValue = StringVar() self.row = 0 self.frame = Frame() self.UNUSED = u"Unused" self.initUI() def writeLog(self,*msgs): self.log[u'state'] = u'normal' if self.log.index(u'end-1c')!=u'1.0': self.log.insert(u'end', u'\n') for msg in msgs: self.log.insert(u'end', msg) ## self.log['state'] = 'disabled' def help(self): t = Toplevel() t.wm_title(u"About") t.transient() photo = ImageTk.PhotoImage(file=u"chameleon.png") ## photo = PhotoImage(file="chameleon.gif") w = Label(t, image=photo) w.photo = photo w.pack(fill=constants.BOTH,side=constants.LEFT,expand=True) l = Label(t, text=u"OFX Converter\n\n"+ u"Convert files in csv format to the\nofx format " + u"which is used by a lot\nof accounting programs " + u"like gnucash\n\n Written in Python 3\nby Floris Groenendijk" ) l.pack(side=constants.TOP, fill=u"both", expand=False, padx=20, pady=20) def onComboboxChanged(self, event): if event.widget.get() == u'credit/debit': # check which checkbox in which column was changed for i in xrange(len(self.comboBoxes)-1): if self.comboBoxes[i] == event.widget: break values = [] # retrieve the values of the labels in that column for j in xrange(len(self.labels)): if self.labels[j][i][u'text'] not in values: values.append(self.labels[j][i][u'text']) self.creditCombo[u'values'] = values self.creditCombo.current( 0 ) if len( values ) > 1: self.debitCombo[u'values'] = values self.debitCombo.current( 1 ) def onFrameConfigure(self, event): # Reset the scroll region to encompass the inner frame self.canvas.configure(scrollregion=self.canvas.bbox(u"all")) def initUI(self): self.parent.title(u"OFX Converter") menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label=u"Open", command=self.openFile, accelerator=u"Ctrl-o") fileMenu.add_command(label=u"Exit", command=self.onExit, accelerator=u"Ctrl-e", underline=1 ) menubar.add_cascade(label=u"File", menu=fileMenu) helpMenu = Menu(menubar) helpMenu.add_command(label=u"About", command=self.help, accelerator=u"Ctrl-i") menubar.add_cascade(label=u"Info", menu=helpMenu) notebook = ttk.Notebook( self.parent ) tabFilesMain = Frame( notebook ) self.tabFiles = Frame( tabFilesMain ) self.tabFiles.pack(fill=constants.BOTH) button = ttk.Button( tabFilesMain, command=self.parseFile, text=u"Process" ) button.pack(side=u"bottom", fill=constants.X, padx=5, pady=5) tabLogging = Canvas( notebook ) tabLogging.grid_rowconfigure(0, weight=1) tabLogging.grid_columnconfigure(0, weight=1) # begin of custom csv frame tabCustomCsv = Frame( notebook ) verticalScrollFrame = Frame( tabCustomCsv ) verticalScrollFrame.grid( row=0, column=0, rowspan=3, sticky=u"WNS" ) tabCustomCsv.grid_columnconfigure(0, weight=0) tabCustomCsv.grid_columnconfigure(1, weight=1) tabCustomCsv.grid_rowconfigure(2,weight=1) self.comboFrame = Frame( tabCustomCsv ) self.comboFrame.grid( row=1, column=1, sticky=u"WE" ) canvasFrame = Frame( tabCustomCsv) canvasFrame.grid( row=2, column=1, sticky=u"NEWS" ) horizontalScrollFrame = Frame( tabCustomCsv ) horizontalScrollFrame.grid( row=3, column=1, columnspan=1, sticky=u"WE" ) self.canvas = Canvas( canvasFrame, highlightthickness=0 ) scrollbar=Scrollbar( horizontalScrollFrame,orient=u"horizontal",command=self.canvas.xview) self.canvas.configure(xscrollcommand=scrollbar.set) self.canvas.pack(fill=constants.BOTH,expand=True) scrollbar.pack(side=u"bottom", fill=constants.X) scrollbar=Scrollbar( verticalScrollFrame,orient=u"vertical",command=self.canvas.yview) self.canvas.configure(yscrollcommand=scrollbar.set) scrollbar.pack(side=u"left", fill=constants.Y) self.canvas.pack(fill=constants.BOTH,expand=1,anchor=u"nw") # end of custom csv frame # begin of config frame configurationFrame = Frame( tabCustomCsv ) Label( configurationFrame, text=u"Values to determine whether the debit field concerns a debit or credit transaction and set the currency" ).pack(anchor=constants.W) currencyLine = Frame( configurationFrame ) currencyLine.pack(fill=constants.X) Label( currencyLine, text=u"currency", width=7, anchor=constants.W ).pack(side=constants.LEFT) self.currencyCombo = ttk.Combobox( currencyLine,width=30,text=u"currency" ) self.currencyCombo.pack(side=constants.LEFT) config = Config() self.currencies = config.getCurrencies() self.currencyCombo[u'values'] = list(sorted(self.currencies.keys())) Label( configurationFrame, text=u"credit", width=7, anchor=constants.W ).pack(side=constants.LEFT) self.creditCombo = ttk.Combobox(configurationFrame,width=10,text=u"credit") self.creditCombo.pack(side=constants.LEFT) Label( configurationFrame, text=u"debit", width=6, anchor=constants.W ).pack(side=constants.LEFT) self.debitCombo = ttk.Combobox( configurationFrame,width=10,text=u"debit" ) self.debitCombo.pack(side=constants.LEFT) Button( configurationFrame, text=u"save configuration", command=self.saveConfig ).pack(side=constants.RIGHT ) configurationFrame.grid( row=4, column=0, columnspan=2, sticky=u"WES") # end of config frame self.log = Text(tabLogging, wrap=u'word') self.log.grid(row=0,column=0,sticky=u'news') hScroll = Scrollbar(tabLogging, orient=constants.HORIZONTAL, command=self.log.xview) hScroll.grid(row=1, column=0, sticky=u'we') vScroll = Scrollbar(tabLogging, orient=constants.VERTICAL, command=self.log.yview) vScroll.grid(row=0, column=1, sticky=u'ns') self.log.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll.set) notebook.add( tabFilesMain, text=u"Files to process" ) notebook.add( tabCustomCsv, text=u"Custom csv" ) notebook.add( tabLogging, text=u"Logging" ) notebook.pack(fill=constants.BOTH,expand=1,anchor=constants.N) self.tabFiles.grid_columnconfigure( 0, weight=1 ) def addFile(self,filename,ibans): if filename != u"" and len(ibans) > 0: Label(self.tabFiles, text=filename, borderwidth=3).grid(row=self.row,column=0,sticky=constants.W,padx=1) ibanList = [] for iban in ibans: ibanList.append( iban[:8] ) combo = ttk.Combobox(self.tabFiles,values=ibanList) combo.current(0) if len(ibanList) == 1: combo.configure(state=constants.DISABLED) combo.grid(row=self.row,column=1,sticky=constants.E,padx=1) state = IntVar() c = Checkbutton(self.tabFiles,variable=state) c.grid(row=self.row,column=2) self.row += 1 ttk.Separator(self.tabFiles).grid(row=self.row, sticky=u"ew", columnspan=3 ) self.row += 1 self.guiMap.append( [ filename, ibans, combo, c, state ] ) def addFileToCustomTab(self,filename): if filename != u"": if self.frame: self.frame.pack_forget() self.frame.destroy() self.frame = Frame( self.canvas ) self.canvas.create_window((0,0),window=self.frame,anchor=u'nw') self.frame.bind(u"<Configure>", self.onFrameConfigure) file = csv.reader( open(filename) ) lines = 1 transaction = Transaction() fields = transaction.fields fields.insert(0,u"main account") fields.insert(0,self.UNUSED) self.comboBoxes = [] self.labels = collections.defaultdict(list) for row in file: column = 0 for field in row: if lines == 1: combo = ttk.Combobox(self.frame,values=transaction.fields,state=u"readonly") combo.current(0) combo.grid(row=0,column=column,sticky=constants.W) self.comboBoxes.append( combo ) combo.bind(u'<<ComboboxSelected>>', self.onComboboxChanged) nextColumn = column + 1 ttk.Separator(self.frame,orient=constants.VERTICAL).grid(row=0, column=nextColumn, sticky=u"ns") label = Label(self.frame,text=field,borderwidth=3) label.grid(row=lines,column=column,sticky=constants.W,padx=1) self.labels[lines-1].append( label ) column = column + 1 ttk.Separator(self.frame,orient=constants.VERTICAL).grid(row=lines, column=column, sticky=u"ns") column = column + 1 lines = lines + 1 if lines > 11: break def saveConfig(self): fields = {} memos = [] for i in xrange( len(self.comboBoxes) - 1 ): key = self.comboBoxes[i].get() if key == self.UNUSED: continue elif key == u'credit/debit': fields[ key ] = u' '.join( [ unicode(i), self.creditCombo.get(), self.debitCombo.get() ] ) elif key == u'memo': memos.append( unicode(i) ) elif key == u'main account': fields[ key ] = self.labels[0][i][u'text'] else: fields[ key ] = i if len(memos) > 0: fields[u'memo'] = u' '.join( memos ) config = Config() (bankKey, bankValue) = config.addToConfig( fields ) self.writeLog( u'key', bankKey, u"with value", bankValue, u"added to config file" ) def openFile(self): if sys.version_info >= (3,0): filename = filedialog.askopenfilename(parent=self.parent, filetypes=[(u'Csv files',u'.csv'), (u'All Files',u'.*')], title=u'Select the csv') else: filename = tkFileDialog.askopenfilename(parent=self.parent, filetypes=[(u'Csv files',u'.csv'), (u'All Files',u'.*')], title=u'Select the csv') if filename != u"": self.writeLog( u'File added: ', filename ) bank = Bank() ibans = bank.searchMainIban( filename ) # If mainIban contains more than one iban, # let the user select which one is the main iban # Otherwise we know the bank this csv belongs to if len( ibans ) > 1: self.writeLog( u'there\'s too many ibans, please select one from the list' ) elif len( ibans ) == 0: self.writeLog( u'No ibans found, is the file correct?' ) ## adding file to custom csv tab else: self.writeLog( u'Found iban: ', ibans[0][:8] ) ibanType = ibans[0][:8] self.addFile(filename,ibans) self.addFileToCustomTab( filename ) def parseFile(self): for guiLine in self.guiMap: ( filename, ibans, combo, checkButton, state ) = guiLine if state.get(): ibanType = combo.get() config = Config() fields = config.getCurrentBank( ibanType ) bankStatement = BankStatement() bankStatement.account = ibans[0] csvReader = CsvReader(fields) csvReader.readFile( filename, bankStatement ) ofx = Ofx() ofx.createXmlFile( filename, bankStatement ) checkButton.configure(state=constants.DISABLED) def onExit(self): quit()
class FullScreenWindow: def __init__(self, label_timeout, max_elements): self.count = 0 self.colors_count = 0 self.tk = Tk() self.max_elements = max_elements self.frame = Frame(self.tk) self.frame.bind("<Key>", self.key_press) self.frame.focus_set() self.state = False self.tk.attributes("-fullscreen", True) self.label_timeout = label_timeout self.screen_width = self.tk.winfo_screenwidth() self.screen_height = self.tk.winfo_screenheight() screen_resolution = str(self.screen_width) + 'x' + str(self.screen_height) self.tk.geometry(screen_resolution) self.canvas = Canvas(self.frame, height=self.screen_height, width=self.screen_width) self.canvas.pack(fill=BOTH) self.frame.pack() self.objects = deque() def key_press(self, key): self.draw_triangle() def draw_triangle(self): x1 = random.uniform(0, 1) * self.screen_width y1 = random.uniform(0, 1) * self.screen_height x2 = random.uniform(0, 1) * self.screen_width y2 = random.uniform(0, 1) * self.screen_height x3 = random.uniform(0, 1) * self.screen_width y3 = random.uniform(0, 1) * self.screen_height x4 = random.uniform(0, 1) * self.screen_width y4 = random.uniform(0, 1) * self.screen_height x5 = random.uniform(0, 1) * self.screen_width y5 = random.uniform(0, 1) * self.screen_height colors = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta'] if self.colors_count % 7 == 0: self.colors_count = 0 if self.count == 0: o = self.canvas.create_line(x1, y1, x2, y2, x3, y3, x1, y1) self.count = 1 elif self.count == 1: o = self.canvas.create_rectangle(x1, y1, x2, y2, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 2 elif self.count == 2: o = self.canvas.create_oval(x1, y1, x2, y2, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 3 elif self.count == 3: o = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 0 if len(self.objects) >= self.max_elements: obj_to_remove = self.objects.pop() self.canvas.delete(obj_to_remove) self.objects.appendleft(o) self.canvas.after(self.label_timeout,self.canvas.delete, o) self.frame.pack(fill=BOTH, expand=1)
class Chord(Frame): RIGHT_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDYwLDB4MDAsMHgwMCwweGUwLDB4MDAsMHgwMCwweGUwLDB4MDMsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MDMsMHgwMCwKMHhlMCwweDAxLDB4MDAsMHg2MCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07' DOWN_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDAwLDB4MDAsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MGYsMHgwMCwweGMwLDB4MDcsMHgwMCwweGMwLDB4MDMsMHgwMCwKMHg4MCwweDAzLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07' def __init__(self, master, title, width, body_background="white", background="#f0f0f0", foreground="#333333", selected_background="#1ba1e2", selected_foreground="white", active_foreground="#0067cb", cursor="hand1"): Frame.__init__(self, master, background="white") self._title = title self._background = background self._foreground = foreground self._active_foreground = active_foreground self._selected_foreground = selected_foreground self._selected_background = selected_background self._cursor = cursor self._right_arrow_icon = BitmapImage(data=base64.b64decode(Chord.RIGHT_ARROW_ICON)) self._down_arrow_icon = BitmapImage(data=base64.b64decode(Chord.DOWN_ARROW_ICON)) self._caption = Frame(self, width =width, background=background, padx=2) self._caption.pack(fill=X, pady=(0,2)) self._caption.pack_propagate(False) self._icon_label = Label(self._caption, image=self._right_arrow_icon, background=background) self._icon_label.pack(side=LEFT) self._title_label = Label(self._caption, text=title, bg = background, fg=foreground) self._title_label.pack(side=LEFT, padx=4, fill=X) self._caption.configure(height= self._title_label.winfo_reqheight()) self.body = Frame(self, background=body_background) self._body_height = None self._is_opened = False self._is_animating = False self._caption.bind('<Button-1>', self._on_click) self._title_label.bind('<Button-1>', self._on_click) self._icon_label.bind('<Button-1>', self._on_click) self._caption.bind('<Enter>', self._on_enter) self._caption.bind('<Leave>', self._on_leave) @property def title(self): return self._title @title.setter def title(self, text): self._title = text self._title_label.configure(text=text) def _on_enter(self, event): if not self._is_opened: self._down_arrow_icon.configure(foreground=self._active_foreground) self._right_arrow_icon.configure(foreground=self._active_foreground) self.config(cursor=self._cursor) def _on_leave(self, event): if not self._is_opened: self._down_arrow_icon.configure(foreground=self._foreground) self._right_arrow_icon.configure(foreground=self._foreground) self.config(cursor="arrow") def _on_click(self, event): if self._is_animating: return self.toggle() def open(self): if self._is_animating: return if not self._is_opened: self._open() def _open(self): self.body.pack() self.body.pack_propagate(False) self._icon_label.configure(image=self._down_arrow_icon, background = self._selected_background) self._title_label.configure(foreground= self._selected_foreground, background = self._selected_background) self._caption.configure(background = self._selected_background) self._down_arrow_icon.configure(foreground=self._selected_foreground) if self._body_height is None: self._body_height= self.body.winfo_reqheight() end_value = self._body_height self.body.configure(width=self.winfo_width()) self._is_opened = True self._is_animating = True animation = Animation( self, ticks=16, interval_time=0.01, start_value=0, end_value=end_value, config_function=lambda height: self.body.configure(height=int(height)), callback=self._on_finnish_animation) animation.start_animation() def _on_finnish_animation(self): self._is_animating = False if not self._is_opened: self.body.pack_forget() def close(self): if self._is_animating: return if self._is_opened: self._close() def _close(self): self._icon_label.configure(image=self._right_arrow_icon, background = self._background) self._title_label.configure(foreground= self._foreground, background = self._background) self._caption.configure(background = self._background) self._right_arrow_icon.configure(foreground=self._foreground) start_value = self.body.winfo_height() self._is_opened = False self._is_animating = True animation = Animation( self, ticks=16, interval_time=0.01, start_value=start_value, end_value=0, config_function=lambda height: self.body.configure(height=int(height)), callback=self._on_finnish_animation) animation.start_animation() def toggle(self): if self._is_opened: self._close() else: self._open()
class Scrolling_Area(Frame, object): def __init__(self, master, width=None, height=None, mousewheel_speed = 2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, outer_background=None, inner_frame=Frame, **kw): super(Scrolling_Area, self).__init__(master, **kw) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._clipper = Frame(self, background=outer_background, width=width, height=height) self._clipper.grid(row=0, column=0, sticky=N+E+W+S) self._width = width self._height = height self.innerframe = inner_frame(self._clipper, padx=0, pady=0, highlightthickness=0) self.innerframe.place(in_=self._clipper, x=0, y=0) if scroll_vertically: if yscrollbar is not None: self.yscrollbar = yscrollbar else: self.yscrollbar = Scrollbar(self, orient=VERTICAL) self.yscrollbar.grid(row=0, column=1,sticky=N+S) self.yscrollbar.set(0.0, 1.0) self.yscrollbar.config(command=self.yview) else: self.yscrollbar = None self._scroll_vertically = scroll_vertically if scroll_horizontally: if xscrollbar is not None: self.xscrollbar = xscrollbar else: self.xscrollbar = Scrollbar(self, orient=HORIZONTAL) self.xscrollbar.grid(row=1, column=0, sticky=E+W) self.xscrollbar.set(0.0, 1.0) self.xscrollbar.config(command=self.xview) else: self.xscrollbar = None self._scroll_horizontally = scroll_horizontally self._jfraction=0.05 self._startX = 0 self._startY = 0 # Whenever the clipping window or scrolled frame change size, # update the scrollbars. self.innerframe.bind('<Configure>', self._on_configure) self._clipper.bind('<Configure>', self._on_configure) self.innerframe.xview = self.xview self.innerframe.yview = self.yview Mousewheel_Support(self).add_support_to(self.innerframe, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar) def update_viewport(self): # compute new height and width self.update() frameHeight = float(self.innerframe.winfo_reqheight()) frameWidth = float(self.innerframe.winfo_reqwidth()) if self._width is not None: width = min(self._width, frameWidth) else: width = self._frameWidth if self._height is not None: height = min(self._height, frameHeight) else: height = self._frameHeight self._clipper.configure(width=width, height=height) def _on_configure(self, event): self._frameHeight = float(self.innerframe.winfo_reqheight()) self._frameWidth = float(self.innerframe.winfo_reqwidth()) # resize the visible part if self._scroll_horizontally: self.xview("scroll", 0, "unit") if self._scroll_vertically: self.yview("scroll", 0, "unit") def xview(self, mode = None, value = None, units = None): value = float(value) clipperWidth = self._clipper.winfo_width() frameWidth = self._frameWidth _startX = self._startX if mode is None: return self.xscrollbar.get() elif mode == 'moveto': # absolute movement self._startX = int(value * frameWidth) else: # mode == 'scroll' # relative movement if units == 'units': jump = int(clipperWidth * self._jfraction) else: jump = clipperWidth self._startX = self._startX + value * jump if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self._startX = 0 hi = 1.0 #use expand by default relwidth = 1 else: # The scrolled frame is larger than the clipping window. #use expand by default if self._startX + clipperWidth > frameWidth: self._startX = frameWidth - clipperWidth hi = 1.0 else: if self._startX < 0: self._startX = 0 hi = (self._startX + clipperWidth) / frameWidth relwidth = '' if self._startX != _startX: # Position frame relative to clipper. self.innerframe.place(x = -self._startX, relwidth = relwidth) lo = self._startX / frameWidth self.xscrollbar.set(lo, hi) def yview(self, mode = None, value = None, units = None): value = float(value) clipperHeight = self._clipper.winfo_height() frameHeight = self._frameHeight _startY = self._startY if mode is None: return self.yscrollbar.get() elif mode == 'moveto': self._startY = value * frameHeight else: # mode == 'scroll' if units == 'units': jump = int(clipperHeight * self._jfraction) else: jump = clipperHeight self._startY = self._startY + value * jump if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self._startY = 0 hi = 1.0 # use expand by default relheight = 1 else: # The scrolled frame is larger than the clipping window. # use expand by default if self._startY + clipperHeight > frameHeight: self._startY = frameHeight - clipperHeight hi = 1.0 else: if self._startY < 0: self._startY = 0 hi = (self._startY + clipperHeight) / frameHeight relheight = '' if self._startY != _startY: # Position frame relative to clipper. self.innerframe.place(y = -self._startY, relheight = relheight) lo = self._startY / frameHeight self.yscrollbar.set(lo, hi)
class TreeNode: def __init__(self, canvas, parent, item, colortheme, vspace=20): self.canvas = canvas self.parent = parent self.item = item self.state = 'collapsed' self.selected = False self.edited = False self.children = [] self.colortheme = colortheme self.x = self.y = None self.vspace = vspace self.halfvspace = int(round(self.vspace / 2)) self.evenodd = 0 if not self.parent: self.canvas.bind('<Configure>', self.reconfig) def reconfig(self, *args): if len(self.canvas['scrollregion']) > 0: w, n, e, s = self.canvas._getints(self.canvas['scrollregion']) if e < self.canvas.winfo_width(): e = self.canvas.winfo_width() for item in self.canvas.windows: win, x = item rightside = x + self.canvas._getints( self.canvas.itemcget(win, 'width'))[0] if rightside < e: self.canvas.itemconfigure(win, width=e - x) def destroy(self): for c in self.children[:]: self.children.remove(c) c.destroy() self.parent = None def geticonimage(self, name): return name def select(self, event=None): if self.selected: return self.deselectall() self.selected = True # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() self.item.OnClick() def deselect(self, event=None): if not self.selected: return self.selected = False # self.canvas.delete(self.image_id) self.drawicon() self.drawtext() def deselectall(self): if self.parent: self.parent.deselectall() else: self.deselecttree() def deselecttree(self): if self.selected: self.deselect() for child in self.children: child.deselecttree() def flip(self, event=None): if self.state == 'expanded': self.collapse() else: self.expand() self.item.OnDoubleClick() return "break" def expand(self, event=None): if not self.item._IsExpandable(): return if self.state != 'expanded': self.state = 'expanded' self.update() self.view() def collapse(self, event=None): self.deselecttree() if self.state != 'collapsed': self.state = 'collapsed' self.update() def view(self): top = self.y bottom = self.lastvisiblechild().y + self.vspace height = bottom - top visible_top = self.canvas.canvasy(0) visible_height = self.canvas.winfo_height() visible_bottom = self.canvas.canvasy(visible_height) if visible_top <= top and bottom <= visible_bottom: return x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) if top >= visible_top and height <= visible_height: fraction = top + height - visible_height else: fraction = top fraction = float(fraction) / y1 self.canvas.yview_moveto(fraction) def lastvisiblechild(self): if self.children and self.state == 'expanded': return self.children[-1].lastvisiblechild() else: return self def update(self): if self.parent: self.parent.update() else: self.canvas.evenodd = 1 self.canvas.windows = [] oldcursor = self.canvas['cursor'] self.canvas['cursor'] = "watch" self.canvas.update() self.canvas.delete(ALL) self.draw(5, 3) x0, y0, x1, y1 = self.canvas.bbox(ALL) self.canvas.configure(scrollregion=(0, 0, x1, y1)) self.canvas['cursor'] = oldcursor self.reconfig() def draw(self, x, y): if self.canvas.evenodd: self.evenodd = 0 self.canvas.evenodd = 0 else: self.evenodd = 1 self.canvas.evenodd = 1 self.x, self.y = x, y self.drawicon() self.drawtext() if self.state != 'expanded': return y + self.vspace # draw children if not self.children: sublist = self.item._GetSubList() if not sublist: # _IsExpandable() was mistaken; that's allowed return y + self.vspace for item in sublist: child = self.__class__(self.canvas, self, item, self.colortheme, self.vspace) self.children.append(child) cx = x + self.vspace cy = y + self.vspace cylast = 0 for child in self.children: cylast = cy self.canvas.create_line(x + self.halfvspace, cy + self.halfvspace, cx, cy + self.halfvspace, fill=self.colortheme.treelinescolor, stipple="gray50") cy = child.draw(cx, cy) if child.item._IsExpandable(): if child.state == 'expanded': iconname = "tree_minus" callback = child.collapse else: iconname = "tree_plus" callback = child.expand image = self.geticonimage(iconname) id = self.canvas.create_image(x + self.halfvspace, cylast + self.halfvspace, image=image) self.canvas.tag_bind(id, "<1>", callback) self.canvas.tag_bind(id, "<Double-1>", lambda x: None) id = self.canvas.create_line(x + self.halfvspace, y + self.halfvspace, x + self.halfvspace, cylast + self.halfvspace, stipple="gray50", fill=self.colortheme.treelinescolor) self.canvas.tag_lower(id) return cy def drawicon(self): return def drawtext(self): textx = self.x texty = self.y labeltext = self.item.GetLabelText() if labeltext: id = self.canvas.create_text(textx, texty, anchor="nw", text=labeltext) self.canvas.tag_bind(id, "<1>", self.select) self.canvas.tag_bind(id, "<Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + self.halfvspace text = self.item.GetText() or "<no text>" if self.selected: imagename = (self.item.GetSelectedIconName() or self.item.GetIconName() or "tree_node") else: imagename = self.item.GetIconName() or "tree_node" image = self.geticonimage(imagename) try: self.entry except AttributeError: pass else: self.edit_finish() try: label = self.label except AttributeError: self.frame = Frame(self.canvas, border=1, relief='flat') self.iconlabel = Label(self.frame, image=image, bd=0, padx=1, pady=1, anchor=W) self.label = Label(self.frame, text=text, bd=0, padx=3, pady=1, anchor=W) self.iconlabel.pack(side='left') self.label.pack(side='left', fill='y') widgets = [self.label, self.iconlabel, self.frame] if self.evenodd: bgcolor = self.colortheme.evencolor else: bgcolor = self.colortheme.editfieldbackground for widget in widgets: if self.selected: widget['bg'] = self.colortheme.selectbackground else: widget['bg'] = bgcolor if self.selected: self.label['fg'] = self.colortheme.selectforeground else: self.label['fg'] = self.colortheme.foreground width = self.frame.winfo_reqwidth() if width < self.canvas.winfo_width() - textx: width = self.canvas.winfo_width() - textx id = self.canvas.create_window(textx, texty, anchor=NW, window=self.frame, width=width) self.canvas.windows.append((id, textx)) self.label.bind("<1>", self.select_or_edit) self.label.bind("<Double-1>", self.flip) self.iconlabel.bind("<1>", self.select_or_edit) self.iconlabel.bind("<Double-1>", self.flip) self.frame.bind("<1>", self.select_or_edit) self.frame.bind("<Double-1>", self.flip) self.label.bind("<Button-4>", self.unit_up) self.label.bind("<Button-5>", self.unit_down) self.iconlabel.bind("<Button-4>", self.unit_up) self.iconlabel.bind("<Button-5>", self.unit_down) self.frame.bind("<Button-4>", self.unit_up) self.frame.bind("<Button-5>", self.unit_down) self.text_id = id def unit_up(self, event): first, last = self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): first, last = self.canvas.yview() if first <= 0 and last >= 1: return "break" self.canvas.yview_scroll(1, "unit") return "break" def select_or_edit(self, event=None): if self.selected and self.item.IsEditable(): self.edit(event) else: self.select(event) def edit(self, event=None): if self.edited: return self.edited = True self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) self.entry.insert(0, self.label['text']) self.entry.selection_range(0, END) self.entry.pack(ipadx=5) self.entry.focus_set() self.entry.bind("<Return>", self.edit_finish) self.entry.bind("<Escape>", self.edit_cancel) def edit_finish(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return text = entry.get() entry.destroy() if text and text != self.item.GetText(): self.item.SetText(text) text = self.item.GetText() self.label['text'] = text self.drawtext() self.canvas.focus_set() def edit_cancel(self, event=None): try: entry = self.entry del self.entry self.edited = False except AttributeError: return entry.destroy() self.drawtext() self.canvas.focus_set()
class console: def __init__(self, master, font): self.app = master self.root = master.root self.Yscroll = Scrollbar(self.root) self.Yscroll.grid(row=1, column=2, sticky='nsew', rowspan=2) # Create a bar for changing console size self.drag = Frame(self.root, bg="white", height=2, cursor="sb_v_double_arrow") # Create text bar self.height = 10 self.root_h = self.height + self.app.text.height self.text = Text(self.root, padx=5, pady=5, height=self.height, width=10, bg="Black", fg="White", font=(font, 12), yscrollcommand=self.Yscroll.set) self.Yscroll.config(command=self.text.yview) # Disable all key bindings EXCEPT those with function that return none ctrl = "Command" if SYSTEM == MAC_OS else "Control" self.text.bind("<Key>", lambda e: "break") self.text.bind("<{}-c>".format(ctrl), lambda e: None) # Allow for resizing self.mouse_down = False self.drag.bind("<Button-1>", self.mouseclick) self.drag.bind("<ButtonRelease-1>", self.mouserelease) self.drag.bind("<B1-Motion>", self.mousedrag) self.drag.grid(row=1, column=0, sticky="nsew", columnspan=2) self.text.grid(row=2, column=0, sticky="nsew", columnspan=2) self.queue = Queue.Queue() self.update() def __str__(self): """ str(s) -> string """ return self.text.get(1.0, "end") def write(self, string): """ Adds string to the bottom of the console """ self.queue.put(string) return def mouseclick(self, event): """ Allows the user to resize the console height """ self.mouse_down = True self.root.grid_propagate(False) return def mouserelease(self, event): self.mouse_down = False self.app.text.focus_set() return def mousedrag(self, event): if self.mouse_down: self.text.update_idletasks() textbox_line_h = self.app.text.dlineinfo("@0,0") if textbox_line_h is not None: self.app.text.height = int(self.app.text.winfo_height() / textbox_line_h[3]) console_line_h = self.text.dlineinfo("@0,0") self.root_h = self.height + self.app.text.height if console_line_h is not None: widget_y = self.text.winfo_rooty() new_height = (self.text.winfo_height() + (widget_y - event.y_root)) self.height = max(2, int(new_height / console_line_h[3])) self.text.config(height=self.height) self.app.text.config(height=self.root_h - self.height) return "break" return def update(self): try: while True: string = self.queue.get_nowait() try: self.text.insert(END, string) self.text.see(END) except: pass except Queue.Empty: pass self.root.after(50, self.update) def read(self): """ Returns contents of the console widget """ return self.text.get(1.0, "end") def hide(self): """ Removes console from interface """ self.text.grid_remove() self.Yscroll.grid_remove() return def show(self): self.text.grid() self.Yscroll.grid() return
class Chord(Frame): RIGHT_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDYwLDB4MDAsMHgwMCwweGUwLDB4MDAsMHgwMCwweGUwLDB4MDMsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MDMsMHgwMCwKMHhlMCwweDAxLDB4MDAsMHg2MCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07' DOWN_ARROW_ICON = 'I2RlZmluZSBpbWFnZV93aWR0aCAxNwojZGVmaW5lIGltYWdlX2hlaWdodCAxNwpzdGF0aWMgY2hhciBpbWFnZV9iaXRzW10gPSB7CjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLAoweDAwLDB4MDAsMHgwMCwweGUwLDB4MGYsMHgwMCwweGUwLDB4MGYsMHgwMCwweGMwLDB4MDcsMHgwMCwweGMwLDB4MDMsMHgwMCwKMHg4MCwweDAzLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAxLDB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwLDB4MDAsCjB4MDAsMHgwMCwweDAwLDB4MDAsMHgwMCwweDAwCn07' def __init__(self, master, title, width, body_background="white", background="#f0f0f0", foreground="#333333", selected_background="#1ba1e2", selected_foreground="white", active_foreground="#0067cb", cursor="hand1"): Frame.__init__(self, master, background="white") self._title = title self._background = background self._foreground = foreground self._active_foreground = active_foreground self._selected_foreground = selected_foreground self._selected_background = selected_background self._cursor = cursor self._right_arrow_icon = BitmapImage( data=base64.b64decode(Chord.RIGHT_ARROW_ICON)) self._down_arrow_icon = BitmapImage( data=base64.b64decode(Chord.DOWN_ARROW_ICON)) self._caption = Frame(self, width=width, background=background, padx=2) self._caption.pack(fill=X, pady=(0, 2)) self._caption.pack_propagate(False) self._icon_label = Label(self._caption, image=self._right_arrow_icon, background=background) self._icon_label.pack(side=LEFT) self._title_label = Label(self._caption, text=title, bg=background, fg=foreground) self._title_label.pack(side=LEFT, padx=4, fill=X) self._caption.configure(height=self._title_label.winfo_reqheight()) self.body = Frame(self, background=body_background) self._body_height = None self._is_opened = False self._is_animating = False self._caption.bind('<Button-1>', self._on_click) self._title_label.bind('<Button-1>', self._on_click) self._icon_label.bind('<Button-1>', self._on_click) self._caption.bind('<Enter>', self._on_enter) self._caption.bind('<Leave>', self._on_leave) @property def title(self): return self._title @title.setter def title(self, text): self._title = text self._title_label.configure(text=text) def _on_enter(self, event): if not self._is_opened: self._down_arrow_icon.configure(foreground=self._active_foreground) self._right_arrow_icon.configure( foreground=self._active_foreground) self.config(cursor=self._cursor) def _on_leave(self, event): if not self._is_opened: self._down_arrow_icon.configure(foreground=self._foreground) self._right_arrow_icon.configure(foreground=self._foreground) self.config(cursor="arrow") def _on_click(self, event): if self._is_animating: return self.toggle() def open(self): if self._is_animating: return if not self._is_opened: self._open() def _open(self): self.body.pack() self.body.pack_propagate(False) self._icon_label.configure(image=self._down_arrow_icon, background=self._selected_background) self._title_label.configure(foreground=self._selected_foreground, background=self._selected_background) self._caption.configure(background=self._selected_background) self._down_arrow_icon.configure(foreground=self._selected_foreground) if self._body_height is None: self._body_height = self.body.winfo_reqheight() end_value = self._body_height self.body.configure(width=self.winfo_width()) self._is_opened = True self._is_animating = True animation = Animation(self, ticks=16, interval_time=0.01, start_value=0, end_value=end_value, config_function=lambda height: self.body. configure(height=int(height)), callback=self._on_finnish_animation) animation.start_animation() def _on_finnish_animation(self): self._is_animating = False if not self._is_opened: self.body.pack_forget() def close(self): if self._is_animating: return if self._is_opened: self._close() def _close(self): self._icon_label.configure(image=self._right_arrow_icon, background=self._background) self._title_label.configure(foreground=self._foreground, background=self._background) self._caption.configure(background=self._background) self._right_arrow_icon.configure(foreground=self._foreground) start_value = self.body.winfo_height() self._is_opened = False self._is_animating = True animation = Animation(self, ticks=16, interval_time=0.01, start_value=start_value, end_value=0, config_function=lambda height: self.body. configure(height=int(height)), callback=self._on_finnish_animation) animation.start_animation() def toggle(self): if self._is_opened: self._close() else: self._open()
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Thu Jul 20 19:00:00 2017 @author: josef """ from Tkinter import Tk, Frame def keyup(event): key = event.keysym print "Key Released: %s" % key def keydown(event): key = event.keysym print "Key Pressed: %s" % key root = Tk() frame = Frame(master=root, width=100, height=100) frame.bind("<KeyPress>", keydown) frame.bind("<KeyRelease>", keyup) frame.pack() root.mainloop()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0) self.hex_color = '#0000ff' self.color_list = ["red","blue","green","orange","purple"] self.parent = parent print "Loading model..." self.lux = Lux() fp = open(curdir+"/gauss_model.pkl"); self.gm = pickle.load(fp); fp.close() fp = open(curdir+"/memoized_binomial_data.pkl"); self.curve_data = pickle.load(fp); fp.close() fp = open(curdir+"/sampling_normalizer.pkl"); self.normalizer = pickle.load(fp); fp.close() print "Creating UI" self.initUI() self.update_output() self.replot() def update_output(self): (h, s, v) = self.hsv_color self.hsv_var.set("Hue: \t %2.1f \nSat:\t %2.1f \nValue:\t %2.1f" % (h*360,s*100,v*100)) items = self.lux.full_posterior((h * 360, s * 100, v * 100)) self.current_post = items desc = [ '{:<25} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ] self.display.config(state=NORMAL) self.display.delete(0, END) for i in range(25): self.display.insert(END, '{:<20} ({:.3f})'.format(items[i][0], items[i][1])) self.display.select_set(0, 0) def plot_lux_model(self, params,ax1,label,support,dim): cur_color='black' mu1,sh1,sc1,mu2,sh2,sc2 = params left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99) right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99) lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360) s=3; ax1.plot(rx, [right_stach.sf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color); ax1.plot([1.01*mu1,0.99*mu2], [1.,1.], linewidth=s,c=cur_color) return ax1.plot(lx,[left_stach.sf(abs(y-mu1)) for y in lx],c=cur_color, linewidth=s); def plot_gm_model(self, params, ax, label, support): s=3 x = np.linspace(support[0],support[1],360) return ax.plot(x,norm.pdf(x,params[0],params[1]),c='red', linewidth=s), norm.pdf([params[0]],params[0],[params[1]])[0] def initUI(self): self.parent.title("Interactive LUX visualization") self.pack(fill=BOTH, expand=1) self.color_frame = Frame(self, border=1) self.color_frame.pack(side=LEFT) probe_title_var = StringVar(); probe_title_label = Label(self.color_frame, textvariable=probe_title_var, justify=CENTER, font = "Helvetica 16 bold italic") probe_title_var.set("Color Probe X"); probe_title_label.pack(side=TOP) self.hsv_var = StringVar() self.hsv_label = Label(self.color_frame, textvariable=self.hsv_var,justify=LEFT) h,s,v = self.hsv_color self.hsv_var.set("Hue: %2.1f \nSaturation: %2.1f \nValue: %2.1f" % (h*360,s*100,v*100)) self.hsv_label.pack(side=TOP) self.frame = Frame(self.color_frame, border=1, relief=SUNKEN, width=200, height=200) self.frame.pack(side=TOP) self.frame.config(bg=self.hex_color) self.frame.bind("<Button-1>",self.onChoose) self.btn = Button(self.color_frame, text="Select Color", command=self.onChoose) self.btn.pack(side=TOP) posterior_title_var = StringVar(); posterior_title_label = Label(self.color_frame, textvariable=posterior_title_var, justify=CENTER, font = "Helvetica 16 bold italic") posterior_title_var.set("\n\nLUX's Posterior"); posterior_title_label.pack(side=TOP) Label(self.color_frame, text="Double click to show details \n(Wait time dependent on computer)").pack(side=TOP) my_font = tkFont.Font(family="Courier", size=10) self.display = Listbox(self.color_frame, border=1, relief=SUNKEN, width=30, height=25, font=my_font) self.display.pack(side=TOP,fill=Y,expand=1) self.display.bind("<Double-Button-1>",self.onSelect) self.display_btn = Button(self.color_frame, text="Show details", command=self.onSelect) self.display_btn.pack(side=TOP) self.update_output() self.fig = Figure(figsize=(10,4), dpi=100) self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.show() self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) def replot(self): def gb(x,i,t): #t is max value, i in number of bins, x is the thing to be binned if x==t: return i-1 elif x==0.0: return 0 return int(floor(float(x)*i/t)) hsv_title = [] j=self.display.curselection()[0] name = self.current_post[j][0] mult = lambda x: reduce(operator.mul, x) g_labels = []; lux_labels=[]; all_g_params=[] for i in range(3): def align_yaxis(ax1, v1, ax2, v2): """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1""" _, y1 = ax1.transData.transform((0, v1)) _, y2 = ax2.transData.transform((0, v2)) inv = ax2.transData.inverted() _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2)) miny, maxy = ax2.get_ylim() ax2.set_ylim(miny, maxy+dy) subplot = self.fig.add_subplot(4,1,i+1) dim_label = ["H", "S","V"][i] subplot.set_ylabel(r"$P(k^{true}_{%s}|x)$" % ["H", "S","V"][i] ) curve_data = self.curve_data[name][i] scale = lambda x,a=0.3,b=0.9: (b-a)*(x)+a p_x = lambda x: self.normalizer[i][gb(x,len(self.normalizer[i]),[360,100,100][i])] max_p_x = max(self.normalizer[i]) #1 is white, 0 is black. so we want highly probable thigns to be black.. if self.lux.get_adj(self.current_post[j][0]): support = [[-180,180], [0,100],[0,100]][i] pp = lambda x,i: x-360 if i==0 and x>180 else x hacky_solution = [360,100,100][i] w = 1.5 if i==0 else 1 conv = lambda x: x*support[1]/len(curve_data) bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))] bar1 = subplot.bar([pp(atan2(sin((x*hacky_solution/len(curve_data))*pi/180),cos((x*hacky_solution/len(curve_data))*pi/180))*180/pi,i) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % j,ec="black",width=w,linewidth=0,color=bar_colors) else: support = [[0,360], [0,100],[0,100]][i] w = 1.5 if i==0 else 1 conv = lambda x: x*support[1]/len(curve_data) bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))] bar1 = subplot.bar([x*support[1]/len(curve_data) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % name[0],ec="black",width=w,linewidth=0,color=bar_colors) pp = lambda x,*args: x point = pp(self.hsv_color[i]*[360,100,100][i],i) hsv_title.append(point) probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='blue',label="Probe") #for j in range(5): lux_plot = self.plot_lux_model(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],support, i) subplot2 = subplot.twinx() gm_plot,gm_height = self.plot_gm_model([pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]], subplot2, self.current_post[j][0], support) extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) subplot.legend([extra], [["Hue", "Saturation", "Value"][i]],loc=2,frameon=False) if i==0: legend_set=lux_plot+[extra,extra,extra]+gm_plot+[extra,extra,extra] lux_params = self.lux.get_params(self.current_post[j][0])[i] g_params = [pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]] all_g_params.append(g_params) g_labels.append(r"$\mu^{%s}=$%2.2f, $\sigma^{%s}$=%2.2f" % (dim_label, g_params[0],dim_label,g_params[1])) #lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, (lux_params[0]-lux_params[1]*lux_params[2]),dim_label,lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,(lux_params[3]+lux_params[4]*lux_params[5]),dim_label, lux_params[4],dim_label,lux_params[5])) lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,lux_params[4],dim_label,lux_params[5])) subplot.set_xlim(support[0],support[1]) subplot.set_ylim(0,1.05) subplot2.set_xlim(support[0],support[1]) subplot2.set_ylabel(r"$P(x|Gaussian_{%s})$" % ["H", "S","V"][i]) align_yaxis(subplot, 1., subplot2, gm_height) leg_loc =(0.9,0.2) datum = [x*[360,100,100][i] for i,x in enumerate(self.hsv_color)]; phi_value = self.lux.get_phi(datum,self.current_post[j][0]) #gauss_value = mult([norm.pdf(datum[i],all_g_params[i][0],all_g_params[i][1]) for i in range(3)]) leg=self.fig.legend(probeplot+legend_set, ["Probe X"]+ [r"$\mathbf{\phi}_{%s}(X)=\mathbf{%2.5f}$; $\mathbf{\alpha}=\mathbf{%2.4f}$" % (self.current_post[j][0],phi_value,self.lux.get_avail(self.current_post[j][0]))]+lux_labels+ [r"$Normal^{Hue}_{%s}$; $prior(%s)=%2.4f$" % (self.current_post[j][0],self.current_post[j][0], self.gm[self.current_post[j][0]][2])]+[g_labels[0]+"; "+g_labels[1]+"; "+g_labels[2]] , loc=8, handletextpad=4,labelspacing=0.1) self.fig.suptitle("%s" % name, size=30) print "done replotting" def onChoose(self, *args): try: ((red,green,blue), hx) = tkColorChooser.askcolor() except: print "I think you hit cancel" return self.hex_color = hx self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frame.config(bg=hx) self.update_output() self.fig.clear() self.replot() self.canvas.draw() def onSelect(self, *args): self.fig.clear() self.replot() self.canvas.draw()
class Application(Frame, object): """The application main class.""" WIDTH, HEIGHT = 1280, 720 BG = 'white' FONT = 'Verdana' FILE_OPEN_OPTIONS = { 'mode': 'rb', 'title': 'Choose *.json file', 'defaultextension': '.json', 'filetypes': [('JSON file', '*.json')] } DEFAULTS = 'default_settings.yaml' def __init__(self, master=None): """Creates application main window with sizes self.WIDTH and self.HEIGHT. :param master: instance - Tkinter.Tk instance """ super(Application, self).__init__(master) self.master.title('Engine Game') self.master.geometry('{}x{}'.format(self.WIDTH, self.HEIGHT)) self.master.protocol('WM_DELETE_WINDOW', self.exit) self.source = None self._map = None self.points = None self.lines = None self.captured_point = None self.x0 = None self.y0 = None self.scale_x = None self.scale_y = None self.font_size = None self.coordinates = {} self.captured_lines = {} self.canvas_obj = AttrDict() self.icons = { 0: PhotoImage(file=join('icons', 'player_city.png')), 1: PhotoImage(file=join('icons', 'city.png')), 2: PhotoImage(file=join('icons', 'market.png')), 3: PhotoImage(file=join('icons', 'store.png')), 4: PhotoImage(file=join('icons', 'point.png')), 5: PhotoImage(file=join('icons', 'player_train.png')), 6: PhotoImage(file=join('icons', 'train.png')), 7: PhotoImage(file=join('icons', 'crashed_train.png')), 8: PhotoImage(file=join('icons', 'collision.png')), 9: PhotoImage(file=join('icons', 'play.png')), 10: PhotoImage(file=join('icons', 'play_pressed.png')), 11: PhotoImage(file=join('icons', 'stop.png')), 12: PhotoImage(file=join('icons', 'stop_pressed.png')) } self.queue_requests = { 0: self.set_status_bar, 1: self.set_player_idx, 2: self.build_map, 3: self.refresh_map, 4: self.set_available_games, 99: self.bot_control } self.settings_window = None if exists(expanduser(self.DEFAULTS)): with open(expanduser(self.DEFAULTS), 'r') as cfg: defaults = DefaultsDict.from_yaml(cfg) self.host = None if not defaults.host else str(defaults.host) self.port = None if not defaults.port else int(defaults.port) self.timeout = None if not defaults.timeout else int(defaults.timeout) self.username = None if not defaults.username else str(defaults.username) self.password = None if not defaults.password else str(defaults.password) else: self.host, self.port, self.timeout, self.username, self.password = None, None, None, None, None self.player_idx = None self.posts = {} self.trains = {} self.select_game_window = False self.available_games = None self.game = None self.num_players = None self.num_turns = None self.bot = Bot() self.bot_thread = None self.menu = Menu(self) filemenu = Menu(self.menu) filemenu.add_command(label='Open file', command=self.file_open) filemenu.add_command(label='Server settings', command=self.open_server_settings) filemenu.add_command(label='Select game', command=self.select_game) filemenu.add_command(label='Exit', command=self.exit) self.menu.add_cascade(label='Menu', menu=filemenu) master.config(menu=self.menu) self._status_bar = StringVar() self.label = Label(master, textvariable=self._status_bar) self.label.pack() self.frame = Frame(self) self.frame.bind('<Configure>', self._resize_frame) self.canvas = Canvas(self.frame, bg=self.BG, scrollregion=(0, 0, self.winfo_width(), self.winfo_height())) self.canvas.bind('<Button-1>', self._capture_point) self.canvas.bind('<Motion>', self._move_point) self.canvas.bind('<B1-ButtonRelease>', self._release_point) self.canvas.bind('<Configure>', self._resize_canvas) hbar = Scrollbar(self.frame, orient=HORIZONTAL) hbar.pack(side=BOTTOM, fill=X) hbar.config(command=self.canvas.xview) vbar = Scrollbar(self.frame, orient=VERTICAL) vbar.pack(side=RIGHT, fill=Y) vbar.config(command=self.canvas.yview) self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set) self.canvas.pack(fill=BOTH, expand=True) self.play = Label(self.canvas, bg='white') self.play.configure(image=self.icons[9]) self.play.bind('<Button-1>', self._play_press) self.play.bind('<B1-ButtonRelease>', self._play_release) self.stop = Label(self.canvas, bg='white') self.stop.configure(image=self.icons[11]) self.stop.bind('<Button-1>', self._stop_press) self.stop.bind('<B1-ButtonRelease>', self._stop_release) self.frame.pack(fill=BOTH, expand=True) self.weighted = IntVar(value=1) self.weighted_check = Checkbutton(self, text='Proportionally to length', variable=self.weighted, command=self._proportionally) self.weighted_check.pack(side=LEFT) self.show_weight = IntVar() self.show_weight_check = Checkbutton(self, text='Show length', variable=self.show_weight, command=self.show_weights) self.show_weight_check.pack(side=LEFT) self.pack(fill=BOTH, expand=True) self.requests_executor() self.get_available_games() self.set_status_bar('Click Play to start the game') self.play.place(rely=0.5, relx=0.5, anchor=CENTER) @property def map(self): """Returns the actual map.""" return self._map @map.setter def map(self, value): """Clears previously drawn map and assigns a new map to self._map.""" self.clear_map() self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self.canvas.winfo_height())) self.x0, self.y0 = self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2 self._map = value @staticmethod def midpoint(x_start, y_start, x_end, y_end): """Calculates a midpoint coordinates between two points. :param x_start: int - x coordinate of the start point :param y_start: int - y coordinate of the start point :param x_end: int - x coordinate of the end point :param y_end: int - y coordinate of the end point :return: 2-tuple of a midpoint coordinates """ return (x_start + x_end) / 2, (y_start + y_end) / 2 def _resize_frame(self, event): """Calculates new font size each time frame size changes. :param event: Tkinter.Event - Tkinter.Event instance for Configure event :return: None """ self.font_size = int(0.0125 * min(event.width, event.height)) def _resize_canvas(self, event): """Redraws map each time Canvas size changes. Scales map each time visible part of Canvas is enlarged. :param event: Tkinter.Event - Tkinter.Event instance for Configure event :return: None """ if self.map: k = min(float(event.width) / float(self.x0 * 2), float(event.height) / float(self.y0 * 2)) self.scale_x, self.scale_y = self.scale_x * k, self.scale_y * k self.x0, self.y0 = self.x0 * k, self.y0 * k self.redraw_map() self.redraw_trains() x_start, y_start, x_end, y_end = self.canvas.bbox('all') x_start = 0 if x_start > 0 else x_start y_start = 0 if y_start > 0 else y_start self.canvas.configure(scrollregion=(x_start, y_start, x_end, y_end)) def _proportionally(self): """Rebuilds map and redraws trains.""" self.build_map() self.redraw_trains() def _capture_point(self, event): """Stores captured point and it's lines. :param event: Tkinter.Event - Tkinter.Event instance for ButtonPress event :return: None """ x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) obj_ids = self.canvas.find_overlapping(x - 5, y - 5, x + 5, y + 5) if not obj_ids: return for obj_id in obj_ids: if obj_id in self.canvas_obj.point.keys(): self.captured_point = obj_id point_idx = self.canvas_obj.point[obj_id]['idx'] self.captured_lines = {} for line_id, attr in self.canvas_obj.line.items(): if attr['start_point'] == point_idx: self.captured_lines[line_id] = 'start_point' if attr['end_point'] == point_idx: self.captured_lines[line_id] = 'end_point' if self.weighted.get(): self.weighted.set(0) def _release_point(self, event): """Writes new coordinates for a moved point and resets self.captured_point and self.captured_lines. :param event: Tkinter.Event - Tkinter.Event instance for ButtonRelease event :return: None """ if self.captured_point: idx = self.canvas_obj.point[self.captured_point]['idx'] x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) self.coordinates[idx] = (x, y) self.points[idx]['x'], self.points[idx]['y'] = (x - self.x0) / self.scale_x, (y - self.y0) / self.scale_y self.captured_point = None self.captured_lines = {} def _move_point(self, event): """Moves point and its lines. Moves weights if self.show_weight is set to 1. In case some point is moved beyond Canvas border Canvas scrollregion is resized correspondingly. :param event: Tkinter.Event - Tkinter.Event instance for Motion event :return: None """ if self.captured_point: new_x, new_y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) self.canvas.coords(self.captured_point, new_x, new_y) indent_y = self.icons[self.canvas_obj.point[self.captured_point]['icon']].height() / 2 + self.font_size if self.canvas_obj.point[self.captured_point]['text_obj']: self.canvas.coords(self.canvas_obj.point[self.captured_point]['text_obj'], new_x, new_y - indent_y) self.coordinates[self.canvas_obj.point[self.captured_point]['idx']] = (new_x, new_y) self.canvas.configure(scrollregion=self.canvas.bbox('all')) for line_id, attr in self.captured_lines.items(): line_attrs = self.canvas_obj.line[line_id] if attr == 'start_point': x, y = self.coordinates[line_attrs['end_point']] self.canvas.coords(line_id, new_x, new_y, x, y) else: x, y = self.coordinates[line_attrs['start_point']] self.canvas.coords(line_id, x, y, new_x, new_y) if self.show_weight.get(): mid_x, mid_y = self.midpoint(new_x, new_y, x, y) self.canvas.coords(line_attrs['weight_obj'][1], mid_x, mid_y) r = self.font_size * len(str(line_attrs['weight'])) self.canvas.coords(line_attrs['weight_obj'][0], mid_x - r, mid_y - r, mid_x + r, mid_y + r) self.redraw_trains() def _play_press(self, _): """Draws play button pressed icon.""" self.play.configure(image=self.icons[10]) def _play_release(self, _): """Draws play button icon and calls bot_control method.""" self.play.configure(image=self.icons[9]) self.bot_control() def _stop_press(self, _): """Draws stop button pressed icon.""" self.stop.configure(image=self.icons[12]) def _stop_release(self, _): """Draws stop buton icon and calls bot_control method.""" self.stop.configure(image=self.icons[11]) self.bot_control() def set_player_idx(self, value): """Sets a player idx value.""" self.player_idx = value def file_open(self): """Opens file dialog and builds and draws a map once a file is chosen. Stops bot if its started.""" path = tkFileDialog.askopenfile(parent=self.master, **self.FILE_OPEN_OPTIONS) if path: if self.bot_thread: self.bot_control() self.posts, self.trains = {}, {} self.source = path.name self.weighted_check.configure(state=NORMAL) self.build_map() def open_server_settings(self): """Opens server settings window.""" ServerSettings(self, title='Server settings') def select_game(self): """Opens select game window.""" self.select_game_window = True SelectGame(self, title='Select game') self.select_game_window = False self.set_status_bar('Click Play to start the game') def exit(self): """Closes application and stops bot if its started.""" if self.bot_thread: self.bot_control() self.master.destroy() def bot_control(self): """Starts bot for playing the game or stops it if it is started.""" if not self.bot_thread: self.bot_thread = Thread(target=self.bot.start, kwargs={ 'host': self.host, 'port': self.port, 'time_out': self.timeout, 'username': self.username, 'password': self.password, 'game': self.game, 'num_players': self.num_players, 'num_turns': self.num_turns}) self.bot_thread.start() else: self.bot.stop() self.bot_thread.join() self.bot_thread = None def get_available_games(self): """Requests a list of available games.""" if self.select_game_window: self.bot.get_available_games(host=self.host, port=self.port, time_out=self.timeout) self.after(1000, self.get_available_games) def set_available_games(self, games): """Sets new value for available games list.""" self.available_games = games def set_status_bar(self, value): """Assigns new status bar value and updates it. :param value: string - status bar string value :return: None """ self._status_bar.set(value) self.label.update() def build_map(self, source=None): """Builds and draws new map. :param source: string - source string; could be JSON string or path to *.json file. :return: None """ if source: self.source = source if self.source: self.map = Graph(self.source, weighted=self.weighted.get()) self.set_status_bar('Map title: {}'.format(self.map.name)) self.points, self.lines = self.map.get_coordinates() self.draw_map() def draw_map(self): """Draws map by prepared coordinates.""" self.draw_lines() self.draw_points() def clear_map(self): """Clears previously drawn map and resets coordinates and scales.""" self.canvas.delete('all') self.scale_x, self.scale_y = None, None self.coordinates = {} def redraw_map(self): """Redraws existing map by existing coordinates.""" if self.map: self.coordinates = {} for obj_id in self.canvas_obj.line: self.canvas.delete(obj_id) self.draw_lines() self.redraw_points() def redraw_points(self): """Redraws map points by existing coordinates.""" if self.map: for obj_id, attrs in self.canvas_obj.point.items(): if attrs['text_obj']: self.canvas.delete(attrs['text_obj']) self.canvas.delete(obj_id) self.draw_points() def redraw_trains(self): """Redraws existing trains.""" if self.trains and hasattr(self.canvas_obj, 'train'): for obj_id, attrs in self.canvas_obj.train.items(): self.canvas.delete(attrs['text_obj']) self.canvas.delete(obj_id) self.draw_trains() @prepare_coordinates def draw_points(self): """Draws map points by prepared coordinates.""" point_objs = {} captured_point_idx = self.canvas_obj.point[self.captured_point]['idx'] if self.captured_point else None for idx in self.points.keys(): x, y = self.coordinates[idx] if self.posts and idx in self.posts.keys(): post_type = self.posts[idx]['type'] if post_type == 1: status = '{}/{} {}/{} {}/{}'.format(self.posts[idx]['population'], self.posts[idx]['population_capacity'], self.posts[idx]['product'], self.posts[idx]['product_capacity'], self.posts[idx]['armor'], self.posts[idx]['armor_capacity']) elif post_type == 2: status = '{}/{}'.format(self.posts[idx]['product'], self.posts[idx]['product_capacity']) else: status = '{}/{}'.format(self.posts[idx]['armor'], self.posts[idx]['armor_capacity']) image_id = 0 if post_type == 1 and self.posts[idx]['player_idx'] == self.player_idx else post_type point_id = self.canvas.create_image(x, y, image=self.icons[image_id]) y -= (self.icons[post_type].height() / 2) + self.font_size text_id = self.canvas.create_text(x, y, text=status, font="{} {}".format(self.FONT, self.font_size)) else: post_type = 4 point_id = self.canvas.create_image(x, y, image=self.icons[post_type]) text_id = None point_objs[point_id] = {'idx': idx, 'text_obj': text_id, 'icon': post_type} self.captured_point = point_id if idx == captured_point_idx else self.captured_point self.canvas_obj['point'] = point_objs @prepare_coordinates def draw_lines(self): """Draws map lines by prepared coordinates and shows their weights if self.show_weight is set to 1.""" line_objs, captured_lines_idx = {}, {} if self.captured_lines: for line_id in self.captured_lines.keys(): captured_lines_idx[self.canvas_obj.line[line_id]['idx']] = line_id for idx, attrs in self.lines.items(): x_start, y_start = self.coordinates[attrs['start_point']] x_stop, y_stop = self.coordinates[attrs['end_point']] line_id = self.canvas.create_line(x_start, y_start, x_stop, y_stop) line_objs[line_id] = {'idx': idx, 'weight': attrs['weight'], 'start_point': attrs['start_point'], 'end_point': attrs['end_point'], 'weight_obj': ()} if idx in captured_lines_idx.keys(): self.captured_lines[line_id] = self.captured_lines.pop(captured_lines_idx[idx]) self.canvas_obj['line'] = line_objs self.show_weights() @prepare_coordinates def draw_trains(self): """Draws trains by prepared coordinates.""" trains = {} for train in self.trains.values(): start_point = self.lines[train['line_idx']]['start_point'] end_point = self.lines[train['line_idx']]['end_point'] weight = self.lines[train['line_idx']]['weight'] position = train['position'] x_start, y_start = self.coordinates[start_point] x_end, y_end = self.coordinates[end_point] delta_x, delta_y = int((x_start - x_end) / weight) * position, int((y_start - y_end) / weight) * position x, y = x_start - delta_x, y_start - delta_y if train['cooldown'] > 0: icon = 7 status = None else: icon = 5 if train['player_idx'] == self.player_idx else 6 status = '{}/{}'.format(train['goods'], train['goods_capacity']) indent_y = self.icons[icon].height() / 2 train_id = self.canvas.create_image(x, y - indent_y, image=self.icons[icon]) text_id = self.canvas.create_text(x, y - (2 * indent_y + self.font_size), text=status, font="{} {}".format(self.FONT, self.font_size)) if status else None trains[train_id] = {'icon': icon, 'text_obj': text_id} self.canvas_obj['train'] = trains def show_weights(self): """Shows line weights when self.show_weight is set to 1 and hides them when it is set to 0.""" if not self.canvas_obj: return if self.show_weight.get(): for line in self.canvas_obj.line.values(): if line['weight_obj']: for obj in line['weight_obj']: self.canvas.itemconfigure(obj, state='normal') else: x_start, y_start = self.coordinates[line['start_point']] x_end, y_end = self.coordinates[line['end_point']] x, y = self.midpoint(x_start, y_start, x_end, y_end) value = line['weight'] size = self.font_size r = int(size) * len(str(value)) oval_id = self.canvas.create_oval(x - r, y - r, x + r, y + r, fill=self.BG, width=0) text_id = self.canvas.create_text(x, y, text=value, font="{} {}".format(self.FONT, str(size))) line['weight_obj'] = (oval_id, text_id) else: for line in self.canvas_obj.line.values(): if line['weight_obj']: for obj in line['weight_obj']: self.canvas.itemconfigure(obj, state='hidden') def requests_executor(self): """Dequeues and executes requests. Assigns corresponding label to bot control button.""" if not self.bot.queue.empty(): request_type, request_body = self.bot.queue.get_nowait() if request_type == 99 and request_body: self.open_server_settings() request_body = None if request_body is not None: self.queue_requests[request_type](request_body) else: self.queue_requests[request_type]() if self.bot_thread and self.bot_thread.is_alive(): if self.play.place_info(): self.play.place_forget() self.stop.place(rely=0.99, relx=0.995, anchor=SE) else: if self.stop.place_info(): self.stop.place_forget() self.play.place(rely=0.5, relx=0.5, anchor=CENTER) self.after(50, self.requests_executor) def refresh_map(self, dynamic_objects): """Refreshes map with passed dynamic objects. :param dynamic_objects: dict - dict of dynamic objects :return: None """ for post in dynamic_objects['posts']: self.posts[post['point_idx']] = post for train in dynamic_objects['trains']: self.trains[train['idx']] = train self.redraw_points() self.redraw_trains()
def __init__(self): def onresize(event): data_canvas.configure(scrollregion=data_canvas.bbox("all")) self.root.update_idletasks() def on_mousewheel(event): data_canvas.yview_scroll(-1 * (event.delta / 120), "units") self.root.update_idletasks() self.root = Tk() self.root.wm_title("Micro-Tensile Testing Machine") self.root.state("zoomed") ######################################################################################################################## # Title header = Frame(self.root) Label(header, text="Micro-Tensile Testing Machine", font=("Helvetica", 40, "bold"), bg="green", relief=RAISED).grid(row=0) header.columnconfigure(0, weight=1) header.grid(row=0, sticky=E + W) ######################################################################################################################## # Parameters par_frame = Frame(self.root) choice_frame = Frame(par_frame, bd=2, relief=RAISED) self.choice = IntVar() self.choice.set(1) Radiobutton(choice_frame, text="ELONGATION", font=("Courier", 15), variable=self.choice, value=1).grid(row=0, column=0, padx=50) Radiobutton(choice_frame, text="BENDING", font=("Courier", 15), variable=self.choice, value=2).grid(row=1, column=0, padx=50) choice_frame.grid(row=0, column=0, sticky=W) spec_frame = Frame(par_frame, bd=2, relief=RAISED) Label(spec_frame, text="Specimen\nDimensions", font=("arial", 15)).grid(row=0, column=0, rowspan=2) Label(spec_frame, text="LENGTH(mm)", font=("Courier", 15), relief=SUNKEN, bg="yellow", fg="brown").grid(row=0, column=1, ipadx=5, ipady=1) self.L = Entry(spec_frame, fg="blue", font=("Courier", 15), width=7) self.L.insert(0, 25.4) self.L.grid(row=0, column=2) Label(spec_frame, text="Area(mm^2)", font=("Courier", 15), relief=SUNKEN, bg="yellow", fg="brown").grid(row=1, column=1, ipadx=5, ipady=1) self.area_box = Entry(spec_frame, fg="blue", font=("Courier", 15), width=7) self.area_box.insert(0, 40.3765) self.area_box.grid(row=1, column=2) spec_frame.grid(row=0, column=1, rowspan=2, sticky=E) par_frame.grid_columnconfigure(1, weight=1) par_frame.grid(row=1, sticky=E + W) ######################################################################################################################## # Main Frame containing Curve and data display curve = Frame(self.root) self.no_reading = 0 # Stress, Strain value arrays self.stress = np.array([0.0]) self.strain = np.array([0.0]) # Figure main_curve = plot.figure(figsize=(18.5, 10)) gs = gridspec.GridSpec(1, 2, width_ratios=[3, 2]) ################################################################### # # Live diagram live_plot = main_curve.add_subplot(gs[0, 0]) live_plot.set_title("Live Diagram") live_plot.grid(True) live_plot.set_xlabel("in mm") live_plot.set_xlim([0, float(self.L.get())]) live_plot.set_ylim([0, 50.0]) # Set y axis limits for live diagram self.lines = live_plot.plot([0.0], [0.0], 'b-', [0.0], [0.0], 'r--') self.live_plot = live_plot ################################################################### # # Stress-Strain Curve curve_plot = main_curve.add_subplot(gs[0, 1]) curve_plot.set_title("Curve") curve_plot.grid(True) curve_plot.set_xlim([0.0, 0.01]) curve_plot.set_ylim([0.0, 100.0]) curve_plot.set_xlabel("") curve_plot.set_ylabel("") self.points = curve_plot.plot(self.strain, self.stress, 'k-') self.curve_plot = curve_plot ################################################################### # # Save and show Figure main_curve.tight_layout() self.main_curve = main_curve self.canvas_main = FigureCanvasTkAgg(self.main_curve, master=curve) self.canvas_main.show() self.canvas_main.get_tk_widget().grid(row=0, column=0, sticky=N + S + E + W) # Displaying data disp_data = Frame(curve, relief=RAISED, bd=2) yscrollbar = AutoScrollbar(disp_data) yscrollbar.grid(row=0, column=1, rowspan=4, sticky=N + S) xscrollbar = AutoScrollbar(disp_data, orient=HORIZONTAL) xscrollbar.grid(row=2, column=0, sticky=E + W) data_canvas = Canvas(disp_data, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set) data_canvas.grid(row=0, column=0, rowspan=4, sticky=N + S + W + E) yscrollbar.config(command=data_canvas.yview) xscrollbar.config(command=data_canvas.xview) label_frame = Frame(disp_data) Label(label_frame, text="DATA\nS.No Load(N) Elongation(mm)\n", font=("COMIC SANS MS", 17, "bold")).grid(row=0, column=0, sticky=N + S + W + E) self.data = StringVar() self.data_str = "" self.data.set(self.data_str) Label(label_frame, textvariable=self.data, font=("Helvetica", 16, "italic")).grid(row=1, column=0, sticky=N + S + W + E) data_canvas.create_window(0, 0, window=label_frame) label_frame.bind("<Configure>", onresize) label_frame.bind_all("<MouseWheel>", on_mousewheel) disp_data.rowconfigure(1, weight=1) disp_data.columnconfigure(0, weight=1) disp_data.columnconfigure(1, weight=1) disp_data.grid(row=0, column=1, sticky=N + S + W + E) curve.columnconfigure(0, weight=1) curve.grid(row=2, sticky=N + S + E + W) ######################################################################################################################## footer = Frame(self.root) Button(footer, text="Run", font=('Comic Sans MS', 25, "bold italic"), command=self.run_program).grid(row=0, column=0) footer.columnconfigure(0, weight=1) footer.grid(row=3, sticky=N + S + E + W) self.root.mainloop()
class PmaConvert: def __init__(self, config): root = Tk() # Root Definition root.geometry('1100x700') root.title('PMA Convert') # Configuration and Variables self.file_selection = '' self.is_converting = False self.options = config['option_definitions'] gui_config = config['gui_config'] # UI ## Frames self.main_frame = Frame(root) self.position_main_frame(gui_config['screen_orientation']) ## Components self.log = Text(self.main_frame, bd=1, relief=SUNKEN, width=140, height=23, state=DISABLED, spacing3=1, wrap=WORD) choose_text = ('1. Choose XLSForm (.xls or .xlsx) file(s) for ' 'conversion.') self.choose_files_label = Label(self.main_frame, text=choose_text) # TODO: Get spacing to work. # self.choose_files_label.grid(row=3, column=3, padx=(50, 50)) # self.choose_files_label.grid(row=3, column=3, pady=(50, 50)) self.choose_files_label.pack() self.choose_files_button = Button(self.main_frame, text='Choose file...', fg='black', command=self.on_open) self.choose_files_button.pack() out_text = 'Choose location for output file(s).' self.output_location_label = Label(self.main_frame, text=out_text) self.output_location_button = Button(self.main_frame, text='Choose location...', fg='black') if gui_config['output_location_on'] is True: self.output_location_label.pack() self.output_location_button.pack() self.choose_options_label = Label(self.main_frame, text='2. Choose conversion options.') self.choose_options_label.pack() ### Create Options Checkboxes # Task: Dynamically generate: http://stackoverflow.com/questions/... # ...553784/can-you-use-a-string-to-instantiate-a-class-in-python self.preexisting = BooleanVar() pre_text = self.options['preexisting']['label'] self.preexisting_opt = Checkbutton(self.main_frame, text=pre_text, variable=self.preexisting) self.preexisting_opt.pack() self.regular = BooleanVar() reg_text = self.options['regular']['label'] self.regular_opt = Checkbutton(self.main_frame, text=reg_text, variable=self.regular) self.regular_opt.pack() self.novalidate = BooleanVar() noval_text = self.options['novalidate']['label'] self.novalidate_opt = Checkbutton(self.main_frame, text=noval_text, variable=self.novalidate) self.novalidate_opt.pack() self.ignore_version = BooleanVar() ig_text = self.options['ignore_version']['label'] self.ignore_version_opt = Checkbutton(self.main_frame, text=ig_text, variable=self.ignore_version) self.ignore_version_opt.pack() self.linking_warn = BooleanVar() link_text = self.options['linking_warn']['label'] self.linking_warn_option = Checkbutton(self.main_frame, text=link_text, variable=self.linking_warn) self.linking_warn_option.pack() self.debug = BooleanVar() debug_text = self.options['debug']['label'] self.debug_option = Checkbutton(self.main_frame, text=debug_text, variable=self.debug) self.debug_option.pack() self.extras = BooleanVar() extras_text = self.options['extras']['label'] self.extras_option = Checkbutton(self.main_frame, text=extras_text, variable=self.extras) self.extras_option.pack() self.convert_label = Label(self.main_frame, text='3. Run conversion.') self.convert_label.pack() # Task: Add xscrollcommand and yscrollcommand. self.convert_button = Button(self.main_frame, text='Convert', fg='black', command=self.convert) self.convert_button.pack() self.log.pack(fill=X, expand=1) self.log_text('PMA Convert allows you to convert .xls or .xlsx form ' 'definition files to files which are compatible with ODK ' 'Collect.\n\nIf you need to copy and paste from this ' 'log, highlight the text and press CTRL+C to copy. Then ' 'press CTRL+V to paste.\n\n' '====================================================\n\n' 'Awaiting file selection.') # Task: Fix menus. They're not working. self.context_menu = Menu(self.main_frame, tearoff=0) self.context_menu.add_command(label="Convert", command=self.convert) self.main_frame.bind("<Button-3>", self.popup) # - Note: Strangely this stopped anchoring to bottom suddenly, for some # reason. So it is temporarily disabled. self.status_bar = Label(self.main_frame, text='Awaiting file selection.', bd=1, relief=SUNKEN, anchor=W) if gui_config['status_bar_on'] is True: self.status_bar.pack(side=BOTTOM, fill=X) # Run root.mainloop() # Functions def popup(self, event): # Note: Currently doesn't work. self.context_menu.post(event.x_root, event.y_root) # display the popup menu try: self.context_menu.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.context_menu.grab_release() def position_main_frame(self, orientation): if orientation == 'center': x, y, a = .5, .5, 'c' return self.main_frame.place(relx=x, rely=y, anchor=a) elif orientation == 'top': return self.main_frame.pack() else: return self.main_frame.pack() def on_open(self): file_types = [ ('XLS Files', '*.xls'), ('XLSX Files', '*.xlsx'), ('All files', '*') ] try: self.file_selection = tkFileDialog.askopenfilename( filetypes=file_types, title='Open one or more files.', message='Open one or more files', multiple=1 ) except: self.file_selection = tkFileDialog.askopenfilename( filetypes=file_types, title='Open one or more files.', multiple=1 ) if self.file_selection != '': self.set_status('Click on Convert to convert files.') log_output = 'Ready for conversion: \n' for file in self.file_selection: log_output += '* ' + str(file) + '\n' log_output = log_output[:-1] # Removes the last '\n'. self.log.configure(self.log_text(log_output)) def set_status(self, new_status): self.status_bar.configure(text=new_status) def log_text(self, new_text): self.log.configure(state=NORMAL) self.log.insert(END, str(new_text) + '\n\n') self.log.configure(state=DISABLED) self.log.bind("<1>", lambda event: self.log.focus_set()) def convert(self): if self.file_selection != '': f = self.file_selection kwargs = { SUFFIX: u'', PREEXISTING: self.preexisting.get(), PMA: not self.regular.get(), CHECK_VERSIONING: not self.ignore_version.get(), STRICT_LINKING: not self.linking_warn.get(), VALIDATE: not self.novalidate.get(), EXTRAS: self.extras.get(), DEBUG: self.debug.get() } buffer = StringIO.StringIO() if not kwargs[DEBUG]: sys.stdout = buffer sys.stderr = buffer else: self.log_text('--> DEBUG MODE: check console output') try: xlsform_convert(f, **kwargs) except ConvertError as e: print unicode(e) except OSError as e: # Should catch WindowsError, impossible to test on Mac traceback.print_exc() print e if not kwargs[DEBUG]: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ self.log_text(buffer.getvalue())
class Path: def __init__(self, root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a0 text6a0 = IntVar() global text6a1 text6a1 = IntVar() global text6b text6b = StringVar() global text6c1 text6c1 = StringVar() global text6c2 text6c2 = StringVar() global text6c3 text6c3 = StringVar() global text7_1 text7_1 = StringVar() global text7_2 text7_2 = StringVar() global text7_3 text7_3 = StringVar() global text7_4 text7_4 = StringVar() global text8 text8 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) def affiche0(): filterPara["text"]="Filter Off" text6a1.set(0) def affiche1(): filterPara["text"]="Filter On" text6a0.set(0) filterPara = Menubutton(self.frame, text="Butterworth filter ", relief=RAISED) filterPara.grid(row=0) filterPara.menu = Menu(filterPara, tearoff = 0) filterPara["menu"] = filterPara.menu filterPara.menu.add_checkbutton(label="Filter Off", variable = text6a0, command = affiche0) filterPara.menu.add_checkbutton(label="Filter On", variable = text6a1, command = affiche1) filterPara.grid(row=12) Label(self.frame, text="Filter name ?").grid(row=15) Entry(self.frame, textvariable=text6b).grid(row=16) Label(self.frame, text="\nIf butterworth = 0; \n just comment out those 3 parameters").grid(row=17) Label(self.frame, text="lowest frequency ?").grid(row=18,column=1) Entry(self.frame, textvariable=text6c1).grid(row=19, column=1) Label(self.frame, text="highest frequency ?").grid(row=20, column=1) Entry(self.frame, textvariable=text6c2).grid(row=21, column=1) Label(self.frame, text="number of poles ?").grid(row=22, column=1) Entry(self.frame, textvariable=text6c3).grid(row=23, column =1) Label(self.frame, text="time window t1 ?").grid(row=24) Entry(self.frame, textvariable=text7_1).grid(row=25) Label(self.frame, text="time window t2 ?").grid(row=26) Entry(self.frame, textvariable=text7_2).grid(row=27) Label(self.frame, text="time window t3 ?").grid(row=28) Entry(self.frame, textvariable=text7_3).grid(row=29) Label(self.frame, text="time window t4 ?").grid(row=30) Entry(self.frame, textvariable=text7_4).grid(row=31) Label(self.frame, text="itranslat (1 if you convert geodetic latitude to geocentric latitude) ?").grid(row=32) Entry(self.frame, textvariable=text8).grid(row=33) Button(self.frame, text="continue", command=writingFile).grid(row=34) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
class MtgProxyView(Frame): """The View, which takes care of the visual representation of the model. Attributes: root: the root panel for the visual represantion cardModel: the cardModel class which deals with all the internal card data home: the path of where images are located safeHome: the path where PDfs are supposed to be saved cnfData: the path to the config file defaultImage: the path to the default image listFrame: the frame in which the mode is portraied canvas: tha canvas which allows scrolling and a grid myscrollbar: the scrollbar which gives the user the abilty to scroll through the list of cards buttonframe: the frame in which the action buttons are being placed wipeWorkspace: the button which corresponds with the clear worksapce function bSelectDir: the button which corresponds with the selectDir function selectSaveDir: the button which corresponds with the selectSaveDir function bMake: the button which corresponds with the makePdf function addButton: the button which corresponds with the addNewCard function """ def __init__(self): """ This is the the constructor of the MtgProxyView It takes care of all the setup and doesnt require anything from the main """ #basic setup sizex = 765 sizey = 525 posx = 0 posy = 0 self.root = Tk() self.root.title("PyProxies") self.root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) self.root.resizable(width=False, height=False) #backend data setup self.cardmodel = Cardmodel() #constants self.home = "" self.safeHome = "" self.cnfData = "upm.cnf" self.defaultImage = "noCard.jpg" self.loadConfig() #list setup self.listframe = Frame(self.root, relief=GROOVE, width=500, height=500, bd=1) self.listframe.place(x=10, y=10) self.canvas = Canvas(self.listframe) self.frame = Frame(self.canvas) self.myscrollbar = Scrollbar(self.listframe, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.myscrollbar.set) #and it scrollbar self.myscrollbar.pack(side="right", fill="y") self.canvas.pack(side="left") self.canvas.create_window((0, 0), window=self.frame, anchor='nw') #button setup self.buttonframe = Frame(self.root, relief=GROOVE, width=100, height=500, bd=1, padx=15, pady=10) self.buttonframe.place(x=535, y=10) self.wipeWorkspace = Button(self.buttonframe, text="clear Workspace", command=self.completeWipe, width=20) self.wipeWorkspace.pack(anchor="sw", pady=5) self.bSelectDir = Button(self.buttonframe, text="select a fitting Directory", command=self.selectDir, width=20) self.bSelectDir.pack(anchor="sw", pady=5) self.selectSaveDir = Button(self.buttonframe, text="Select a save directory", command=self.selectSafeDir, width=20) self.selectSaveDir.pack(anchor="sw", pady=5) self.bMake = Button(self.buttonframe, text="make PDF", command=self.makePdf, width=20) self.bMake.pack(anchor="sw", pady=5) self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.frame.bind("<Configure>", self.myfunction) self.data() self.root.mainloop() def loadConfig(self): """ This is the functions which loads the configuration. Only the place where Images can be added as sources and where PDFs can be saved, are able to be set and saved. """ configFile = open(self.cnfData, "r+") temp = configFile.read().split("\n") try: self.home = expanduser("~") if os.path.exists(temp[0]): self.home = temp[0] self.safeHome = expanduser("~") if os.path.exists(temp[1]): self.safeHome = temp[1] except IndexError: print "Error" self.home = expanduser("~") self.safeHome = expanduser("~") print "new homes" print self.home print self.safeHome configFile.close() def saveConfig(self): """ This Function takes care of writing the values of the home and the saveHome to the configuration file """ configFile = open(self.cnfData, "w") configFile.write(self.home + "\n" + self.safeHome) print "config saved" configFile.close() self.loadConfig() def completeWipe(self): """ This function clears the workspace of all of its components and resets the Model. """ for i in range(self.cardmodel.getCardCount()): #self.cardHowOften[i]=0 self.cardmodel.setCardHowOften(i, 0) self.cardmodel.setImg(self.defaultImage, i) #self.imgPaths[i] = self.defaultImage self.cardmodel.resetCardCount() for w in self.frame.winfo_children(): w.destroy() self.data() def selectSafeDir(self): """ This function sets the directory where exported PDFs are being stored. Its does this by invoking the tkFileDialog which asks for user input and returns a valid path. """ path = tkFileDialog.askdirectory( initialdir=self.safeHome, title="Select a better save directory.") if isinstance(path, basestring): self.safeHome = path self.saveConfig() def selectDir(self): """ This function provides the user with the functionality to set their starting directory for adding source images. They can do this in order to save time and optimize their workflow. Its does this by invoking the tkFileDialog which asks for user input and returns a valid path. """ path = tkFileDialog.askdirectory( initialdir=self.home, title="Select a better working directory.") if isinstance(path, basestring): self.home = path self.saveConfig() def data(self): """ The data function takes care of going over the entiry model and representing it on the canvas object. It is only supposed to be invoked when the workspace has been cleard beforehand. """ for i in range(self.cardmodel.getCardCount()): #image label pilFile = Image.open(self.cardmodel.getImg(i)) image1 = pilFile.resize((60, 80), Image.ANTIALIAS) image2 = ImageTk.PhotoImage(image1) imageLabel = Label(self.frame, image=image2) imageLabel.image = image2 imageLabel.grid(row=i, column=0, padx=2, pady=2) #other labels Label(self.frame, text="Card is being printed " + str(self.cardmodel.getCardHowOftenAt(i)) + " times.").grid( row=i, column=1) Button(self.frame, text="-", command=lambda i=i: self.decrHowOften(i)).grid(row=i, column=2) Button(self.frame, text="+", command=lambda i=i: self.incrHowOften(i)).grid(row=i, column=3) Button(self.frame, text="add Source", command=lambda i=i: self.getImgPath(i)).grid(row=i, column=4) Button(self.frame, text="X", command=lambda i=i: self.delete(i)).grid(row=i, column=5) self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.addButton.grid(row=self.cardmodel.getCardCount(), column=0, columnspan=2, padx=10, pady=20, sticky="W") def updateOne(self, i): """ This Function is supposed to only update one row of the Canvas in, which the model is displayed. Args: i: the index of the row which is supposed to be updated """ pilFile = Image.open(self.cardmodel.getImg(i)) image1 = pilFile.resize((60, 80), Image.ANTIALIAS) image2 = ImageTk.PhotoImage(image1) imageLabel = Label(self.frame, image=image2) imageLabel.image = image2 imageLabel.grid(row=i, column=0, padx=2, pady=2) # other labels Label(self.frame, text="Card is being printed " + str(self.cardmodel.getCardHowOftenAt(i)) + " times.").grid( row=i, column=1) Button(self.frame, text="-", command=lambda i=i: self.decrHowOften(i)).grid(row=i, column=2) Button(self.frame, text="+", command=lambda i=i: self.incrHowOften(i)).grid(row=i, column=3) Button(self.frame, text="add Source", command=lambda i=i: self.getImgPath(i)).grid(row=i, column=4) Button(self.frame, text="X", command=lambda i=i: self.delete(i)).grid(row=i, column=5) def delete(self, i): """ This function is supposed to delete one Card and update the model accordingly. Args: i: the indexing of the row, which is supposed to be updated """ self.cardmodel.deleteCard(i) #complete reset for w in self.frame.winfo_children(): w.destroy() self.data() def incrHowOften(self, i): """ This function takes care of increasing the counter of how often a card is supposed to be printed. Args: i: the row in which the the card is located """ self.cardmodel.incrCardHowOften(i) self.updateOne(i) def decrHowOften(self, i): """ This function takes care of decreasing the counter of how often a card is supposed to be printed. Args: i: the row in which the the card is located """ self.cardmodel.decrCardHowOften(i) self.updateOne(i) def addNewCard(self): """ This function adds a new card to the model and updates it with default values. It then invokes the updateOne-function in order to update the view. """ self.cardmodel.addCard() self.addButton.destroy() self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.addButton.grid(row=self.cardmodel.getCardCount(), column=0, columnspan=2, padx=10, pady=20, sticky="W") self.updateOne(self.cardmodel.getCardCount() - 1) def myfunction(self, event): """ A function which is called in the event of a configuration concerning the frame. It sets the scrollregion of the scrollbar to be the canvas """ self.canvas.configure(scrollregion=self.canvas.bbox("all"), width=500, height=500) def getImgPath(self, i): """ This function allows the user to change the image source of a card. It does this by invoking the tkFileDialog in order to ask for a filename, limited to JPGs and PNGs. If the user input something it updates the model. Args: i: index of the row in which the card is located """ imgPath = tkFileDialog.askopenfilenames(initialdir=self.home, title="Select Image", filetypes=[ ("JPG files", "*.jpg"), ("PNG files", "*.png"), ("JPEG files", "*.jpeg") ]) print imgPath print str(imgPath) == "()" if str(imgPath) != "()" and str(imgPath) != "": print(imgPath[0]) self.cardmodel.setImg(imgPath[0], i) self.updateOne(i) else: print "user didnt select anything" def makePdf(self): """ This function gives the user the functionality to select a filename for the PDF they want to print. Afterwards if a name has been entered the function gives the model to the proxymaker module, which creates a PDF in the desired location. """ name = tkSimpleDialog.askstring( 'Input', 'Enter the desired name for the PDF, without suffix') if name is not None: proxymaker.writeData(self.cardmodel, self.safeHome + "/" + name + ".pdf")
class Scrolling_Area(Frame, object): def __init__(self, master, width=None, height=None, mousewheel_speed=2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, outer_background=None, inner_frame=Frame, **kw): super(Scrolling_Area, self).__init__(master, **kw) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._clipper = Frame(self, background=outer_background, width=width, height=height) self._clipper.grid(row=0, column=0, sticky=N + E + W + S) self._width = width self._height = height self.innerframe = inner_frame(self._clipper, padx=0, pady=0, highlightthickness=0) self.innerframe.place(in_=self._clipper, x=0, y=0) if scroll_vertically: if yscrollbar is not None: self.yscrollbar = yscrollbar else: self.yscrollbar = Scrollbar(self, orient=VERTICAL) self.yscrollbar.grid(row=0, column=1, sticky=N + S) self.yscrollbar.set(0.0, 1.0) self.yscrollbar.config(command=self.yview) else: self.yscrollbar = None self._scroll_vertically = scroll_vertically if scroll_horizontally: if xscrollbar is not None: self.xscrollbar = xscrollbar else: self.xscrollbar = Scrollbar(self, orient=HORIZONTAL) self.xscrollbar.grid(row=1, column=0, sticky=E + W) self.xscrollbar.set(0.0, 1.0) self.xscrollbar.config(command=self.xview) else: self.xscrollbar = None self._scroll_horizontally = scroll_horizontally self._jfraction = 0.05 self._startX = 0 self._startY = 0 # Whenever the clipping window or scrolled frame change size, # update the scrollbars. self.innerframe.bind('<Configure>', self._on_configure) self._clipper.bind('<Configure>', self._on_configure) self.innerframe.xview = self.xview self.innerframe.yview = self.yview Mousewheel_Support(self).add_support_to(self.innerframe, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar) def update_viewport(self): # compute new height and width self.update() frameHeight = float(self.innerframe.winfo_reqheight()) frameWidth = float(self.innerframe.winfo_reqwidth()) if self._width is not None: width = min(self._width, frameWidth) else: width = self._frameWidth if self._height is not None: height = min(self._height, frameHeight) else: height = self._frameHeight self._clipper.configure(width=width, height=height) def _on_configure(self, event): self._frameHeight = float(self.innerframe.winfo_reqheight()) self._frameWidth = float(self.innerframe.winfo_reqwidth()) # resize the visible part if self._scroll_horizontally: self.xview("scroll", 0, "unit") if self._scroll_vertically: self.yview("scroll", 0, "unit") def xview(self, mode=None, value=None, units=None): value = float(value) clipperWidth = self._clipper.winfo_width() frameWidth = self._frameWidth _startX = self._startX if mode is None: return self.xscrollbar.get() elif mode == 'moveto': # absolute movement self._startX = int(value * frameWidth) else: # mode == 'scroll' # relative movement if units == 'units': jump = int(clipperWidth * self._jfraction) else: jump = clipperWidth self._startX = self._startX + value * jump if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self._startX = 0 hi = 1.0 #use expand by default relwidth = 1 else: # The scrolled frame is larger than the clipping window. #use expand by default if self._startX + clipperWidth > frameWidth: self._startX = frameWidth - clipperWidth hi = 1.0 else: if self._startX < 0: self._startX = 0 hi = (self._startX + clipperWidth) / frameWidth relwidth = '' if self._startX != _startX: # Position frame relative to clipper. self.innerframe.place(x=-self._startX, relwidth=relwidth) lo = self._startX / frameWidth self.xscrollbar.set(lo, hi) def yview(self, mode=None, value=None, units=None): value = float(value) clipperHeight = self._clipper.winfo_height() frameHeight = self._frameHeight _startY = self._startY if mode is None: return self.yscrollbar.get() elif mode == 'moveto': self._startY = value * frameHeight else: # mode == 'scroll' if units == 'units': jump = int(clipperHeight * self._jfraction) else: jump = clipperHeight self._startY = self._startY + value * jump if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self._startY = 0 hi = 1.0 # use expand by default relheight = 1 else: # The scrolled frame is larger than the clipping window. # use expand by default if self._startY + clipperHeight > frameHeight: self._startY = frameHeight - clipperHeight hi = 1.0 else: if self._startY < 0: self._startY = 0 hi = (self._startY + clipperHeight) / frameHeight relheight = '' if self._startY != _startY: # Position frame relative to clipper. self.innerframe.place(y=-self._startY, relheight=relheight) lo = self._startY / frameHeight self.yscrollbar.set(lo, hi)
class Example(Frame): output_lines = 10 # make debug false when you are actually going to demo this to an audience debug = 1 def __init__(self, parent): Frame.__init__(self, parent) self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0) self.hex_color = '#0000ff' # Added second copy of the above two fields for second color # For debugging, want an initial if self.debug : self.hsv_colorTwo = colorsys.rgb_to_hsv(0.0, 0.50, 0.625) self.hex_colorTwo = '#0088aa' else: self.hsv_colorTwo = colorsys.rgb_to_hsv(1.0, 0.0, 0.0) self.hex_colorTwo = '#ff0000' self.parent = parent print "Loading model..." self.lux = Lux() self.initUI() def update_output(self): (h, s, v) = self.hsv_color self.cv.set('Color {:.2f} {:.2f} {:.2f} (hsv)'.format(h, s, v)) #tjm Added second update_output method for when second color is chosen def update_outputTwo(self): (h, s, v) = self.hsv_colorTwo self.cvTwo.set('Color {:.2f} {:.2f} {:.2f} (hsv)'.format(h, s, v)) def initUI(self): row_height = 220 start_height = 30 left_column = 30 sq_size = 180 color_column = left_column assoc_column = color_column + sq_size + 30 dist_column = assoc_column + 220 y_label = 5 self.parent.title("Interactive LUX visualization") self.pack(fill=BOTH, expand=1) self.frame = Frame(self, border=1, relief=SUNKEN, width=sq_size, height=sq_size) self.frame.place(x=color_column, y=start_height) self.frame.config(bg=self.hex_color) self.frame.bind("<Button-1>", self.onChooseClick) #tjm Added second color display window self.frameTwo = Frame(self, border=1, relief=SUNKEN, width=sq_size, height=sq_size) self.frameTwo.place(x=color_column, y=start_height+row_height) self.frameTwo.config(bg=self.hex_colorTwo) self.frameTwo.bind("<Button-1>", self.onChooseTwoClick) #tjm First string field to display the H, S, and V values self.cv = StringVar() self.info = Label(self, textvariable=self.cv) self.info.place(x=color_column, y=y_label) #tjm second string field to display H, S, and V values self.cvTwo = StringVar() self.infoTwo = Label(self, textvariable=self.cvTwo) self.infoTwo.place(x=color_column, y=y_label+row_height) #tjm label for associated color terms field self.cvThree = StringVar() self.infoThree = Label(self, textvariable=self.cvThree) self.infoThree.place(x=assoc_column, y=y_label) #tjm label for distinguishing color terms field self.cvFour = StringVar() self.infoFour = Label(self, textvariable=self.cvFour) self.infoFour.place(x=dist_column, y=y_label) #tjm instruction text for color term assignment prediction function self.cvFive = StringVar() self.infoFive = Label(self, textvariable=self.cvFive) self.infoFive.place(x=left_column, y=y_label+2*row_height) self.display = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.display.place(x=assoc_column, y=start_height) self.display.tag_configure('undistinguished', foreground='dark salmon') #tjm Added second text window to display color labels self.displayTwo = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.displayTwo.place(x=assoc_column, y=start_height+row_height) self.displayTwo.tag_configure('undistinguished', foreground='dark salmon') #tjm Text field that displays distinction color term for top color self.distLabel = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.distLabel.place(x=dist_column, y=start_height) #tjm Text field that shows distinction color term for bottom color self.distLabelTwo = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.distLabelTwo.place(x=dist_column, y=start_height+row_height) #tjm added Entry widget for user to supply a color term self.e = Entry(self, bd = 5) self.e.bind("<Return>", lambda(event):self.onChooseAssign(self.e.get())) self.e.place(x = assoc_column, y=y_label+2*row_height) #tjm added text window to display result self.assignmentResult = Text(self, border = 1, relief=SUNKEN, width = 25, height = 2) self.assignmentResult.place(x = dist_column, y = y_label+2*row_height) self.cvThree.set('Associated Color Terms') self.cvFour.set('Differentiating Color Terms') self.cvFive.set('Test color term to interpret') self.update_output() self.update_outputTwo() self.distAndDisplay() def distAndDisplay(self): hueResultList = self.distinguish(1) hueResultListTwo = self.distinguish(2) #tjm displays top N choices and confidence ratings in the distLabel text field desc = [ '{:<17} {:.3f}\n'.format(hueResultList[i][0], hueResultList[i][1]) for i in range(self.output_lines) ] self.distLabel.config(state=NORMAL) self.distLabel.delete(1.0, END) self.distLabel.insert(END, ''.join(desc)) self.distLabel.config(state=DISABLED) descs = [hueResultList[i][0] for i in range(self.output_lines)] descTwo = [ '{:<17} {:.3f}\n'.format(hueResultListTwo[i][0], hueResultListTwo[i][1]) for i in range(self.output_lines) ] self.distLabelTwo.config(state=NORMAL) self.distLabelTwo.delete(1.0, END) self.distLabelTwo.insert(END, ''.join(descTwo)) self.distLabelTwo.config(state=DISABLED) descsTwo = [hueResultListTwo[i][0] for i in range(self.output_lines)] #tjm the "items" field holds the probability for each color term being used to describe hsv_color (h, s, v) = self.hsv_color items = self.lux.full_posterior((h * 360, s * 100, v * 100)) desc = [ '{:<17} {:.3f}\n'.format(items[i][0], items[i][1]) for i in range(self.output_lines) ] #tjm displays the HSV values self.display.config(state=NORMAL) self.display.delete(1.0, END) self.display.insert(END, ''.join(desc)) for i in range(self.output_lines) : if items[i][0] not in descs : self.display.tag_add('undistinguished', str(i+1) + ".0", str(i+1) + ".23") self.display.config(state=DISABLED) #tjm the "itemsTwo" field holds the probability for each color term being used to describe hsc_colorTwo (h, s, v) = self.hsv_colorTwo itemsTwo = self.lux.full_posterior((h * 360, s * 100, v * 100)) descTwo = [ '{:<17} {:.3f}\n'.format(itemsTwo[i][0], itemsTwo[i][1]) for i in range(self.output_lines) ] self.displayTwo.config(state=NORMAL) self.displayTwo.delete(1.0, END) self.displayTwo.insert(END, ''.join(descTwo)) for i in range(self.output_lines) : if itemsTwo[i][0] not in descsTwo : self.displayTwo.tag_add('undistinguished', str(i+1) + ".0", str(i+1) + ".23") self.displayTwo.config(state=DISABLED) self.onChooseAssign(self.e.get()) def onChoose(self): news = tkColorChooser.askcolor() if news and news[0]: ((red,green,blue), hx) = news self.hex_color = hx self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frame.config(bg=hx) self.update_output() self.distAndDisplay() #tjm Added second onChoose function for when the second button is clicked def onChooseTwo(self): news = tkColorChooser.askcolor() if news and news[0]: ((red,green,blue), hx) = news self.hex_colorTwo = hx self.hsv_colorTwo = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frameTwo.config(bg=hx) self.update_outputTwo() self.distAndDisplay() def onChooseClick(self, event) : self.onChoose() def onChooseTwoClick(self, event) : self.onChooseTwo() def onChooseAssign(self, colorTerm): node = self.lux.all.get(colorTerm) if node: scoreTop = self.score(node, self.hsv_color, self.hsv_colorTwo) scoreNumberTop = scoreTop[1] scoreBottom= self.score(node, self.hsv_colorTwo, self.hsv_color) scoreNumberBottom = scoreBottom[1] totalScoreTop = (scoreNumberTop/(scoreNumberTop+scoreNumberBottom)) if totalScoreTop > 0.5: winner = '{:<17} {:.3f}\n{:<14} {:.6f}'.format('top color!', totalScoreTop, colorTerm, scoreNumberTop) else: if totalScoreTop < 0.5: winner = '{:<17} {:.3f}\n{:<14} {:.6f}'.format('bottom color!', (1.0 - totalScoreTop), colorTerm, scoreNumberBottom) else: winner = 'Could describe either.\n{:<14f} {:.6f}'.format(colorTerm, scoreNumberTop) elif colorTerm : winner = 'Unknown term: ' + colorTerm else : winner = '' self.assignmentResult.config(state=NORMAL) self.assignmentResult.delete(1.0, END) self.assignmentResult.insert(END, winner) self.assignmentResult.config(state=DISABLED) def score(self, currentNode, hsvY, hsvZ): (hY, sY, vY) = hsvY (hZ, sZ, vZ) = hsvZ hY *= 360 sY *= 100 vY *= 100 hZ *= 360 sZ *= 100 vZ *= 100 muHLow = currentNode.dim_models[0].params[0] muHHigh = currentNode.dim_models[0].params[3] muSLow = currentNode.dim_models[1].params[0] muSHigh = currentNode.dim_models[1].params[3] muVLow = currentNode.dim_models[2].params[0] muVHigh = currentNode.dim_models[2].params[3] # mds changed to hY and hZ - never use the unscaled values phiHY = currentNode.dim_models[0].phi(hY) phiHZ = currentNode.dim_models[0].phi(hZ) phiSY = currentNode.dim_models[1].phi(sY) phiSZ = currentNode.dim_models[1].phi(sZ) phiVY = currentNode.dim_models[2].phi(vY) phiVZ = currentNode.dim_models[2].phi(vZ) # mds added: need to handle hue adjust if currentNode.dim_models[0].adjust : adjust = True; nhY = atan2(sin(hY*pi/180),cos(hY*pi/180))*180/pi nhZ = atan2(sin(hZ*pi/180),cos(hZ*pi/180))*180/pi else : adjust = False; nhY = hY; nhZ = hZ; """ ([product over opposite dimensions d] phi_d(y) ) * <== termA ([product over other dimensions d] phi_d(y) - <== termB [product over all dimensions d] phi_d(z)) <== termC """ termA = 1.0 termB = 1.0 termC = phiHZ * phiSZ * phiVZ oppSideCase = 0 #tjm determine which case and calculate appropriate y-but-not-z value #tjm opposite sides case for hue if ((nhY < muHLow) & (muHHigh < nhZ)) | ((nhZ < muHLow) & (muHHigh < nhY)): termA *= phiHY oppSideCase += 1 else: termB *= phiHY #tjm opposite sides case for saturation if ((sY < muSLow) & (muSHigh < sZ)) | ((sZ < muSLow) & (muSHigh < sY)): termA *= phiSY oppSideCase += 1 else: termB *= phiSY #tjm opposite sides case for value if ((vY < muVLow) & (muVHigh < vZ)) | ((vZ < muVLow) & (muVHigh < vY)): termA *= phiVY oppSideCase +=1 else: termB *= phiVY score = termA * (termB - termC) if score < 0: score = 0 #mds weight words by availability score *= currentNode.availability return [currentNode.name, score, termA, termB, termC, oppSideCase, adjust, nhY, nhZ, muHLow, muHHigh] #tjm Method to select color term that describes one color but not the other def distinguish(self, choice): """tjm process: 1) go through all color terms 1a) see if it's an acceptable case 1b) calculate y-but-not-z-confidence 1c) store color term name and y-but-not-z-confidence in list 2) return sorted list 3) print out top 5 values for sanity check """ #tjm list of color terms and associated y-but-not-z confidence hueResults = [] #tjm determine if you're picking a term to describe top color or bottom color if choice == 1: #tjm loop over all color terms for currentNodeChoice in self.lux.all.values(): #mds enable comprehensive debugging reports hueResults.append(self.score(currentNodeChoice, self.hsv_color, self.hsv_colorTwo)) else: for currentNodeChoice in self.lux.all.values(): #mds enable comprehensive debugging reports hueResults.append(self.score(currentNodeChoice, self.hsv_colorTwo, self.hsv_color)) total = sum(r[1] for r in hueResults) for r in hueResults : r[1] /= total return sorted(hueResults, key = lambda hueResults:hueResults[1], reverse=True)
def main(): global state_pub global root global max_velocity global max_steering_angle max_velocity = rospy.get_param("~speed", 2.0) max_steering_angle = rospy.get_param("~max_steering_angle", 0.34) state_pub = rospy.Publisher( "/racecar/ackermann_cmd", AckermannDriveStamped, queue_size=1 ) rospy.Timer(rospy.Duration(0.1), publish_cb) atexit.register(exit_func) os.system("xset r off") root = Tk() frame = Frame(root, width=100, height=100) frame.bind("<KeyPress>", keydown) frame.bind("<KeyRelease>", keyup) frame.pack() frame.focus_set() lab = Label( frame, height=10, width=30, text="Focus on this window\nand use the WASD keys\nto drive the car.\n\nPress Q to quit", ) lab.pack() print("Press %c to quit" % QUIT) root.mainloop()