def addListBox(self, ax=600, ay=52, x=0, y=0, bg="#B4045F"): scrolly = Scrollbar(self, activebackground="#171212", bg="#171212", orient=VERTICAL, troughcolor="#171212") listbox = Listbox(self, height=ay, width=ax, background=bg, borderwidth=0, highlightcolor="#4d86a1", selectbackground="#4d86a1", activestyle=NONE, highlightbackground="#4a4a4a", yscrollcommand=scrolly.set) listbox.config(font=("", 10), fg="#FFFFFF") listbox.place(x=0, y=0) scrolly.place(x=651, y=0, height=387) self.__list_listbox.append(listbox) self.__list_scrollbar.append(scrolly) for x in self.__list_listbox: x.configure(yscrollcommand=scrolly.set) scrolly.configure(command=self.__yview)
def __init__(self, root=None): self.root = root or Tk() self.root.title('Pylint') top_frame = Frame(self.root) res_frame = Frame(self.root) btn_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) res_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) Label(top_frame, text='Module or package').pack(side=LEFT) self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT) scrl = Scrollbar(res_frame) self.results = Listbox(res_frame, background='white', font='fixedsys', selectmode='browse', yscrollcommand=scrl.set) scrl.configure(command=self.results.yview) self.results.pack(side=LEFT, expand=True, fill=BOTH) scrl.pack(side=RIGHT, fill=Y) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #self.root.bind('<ctrl-q>', self.quit) self.txtModule.focus_set()
def make_scrollbars(scrollable, master, x=True, y=True): result = [] if x: hscrollbar = Scrollbar(master, orient=HORIZONTAL) scrollable.configure(xscrollcommand=hscrollbar.set) hscrollbar.configure(command=scrollable.xview) result.append(hscrollbar) if y: vscrollbar = Scrollbar(master, orient=VERTICAL) scrollable.configure(yscrollcommand=vscrollbar.set) vscrollbar.configure(command=scrollable.yview) result.append(vscrollbar) return result
def __init__(self, parent, width=400, height=200): Frame.__init__(self, parent) self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF") self.canvas.configure(bd=2, relief=SUNKEN) self.canvas.pack(side=LEFT) self.centre_line = self.canvas.create_line(0, 0, 0, 0) scrollbar = Scrollbar(self) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.configure(command=self.canvas.yview) self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0, width, height)) self.width=width self.height_in_lines = height/18 self.item_count = 0 self.font = ("Helvetica", 12)
class LispTKScrollbarClass(LispAtom): def __init__(self,root): self.value=Scrollbar(root.value) def execute(self,env, *unEvalArgs): arg = LISP.Eval.evall(unEvalArgs[0], env) if(arg == new(LispSymbol,"pack")): self.value.pack(side=RIGHT, fill=Y) if(arg == new(LispSymbol,"setParent")): parent = LISP.Eval.evall(unEvalArgs[1], env) self.value.configure(command=parent.value.yview) def execute_ea(self,*evalArgs): arg=evalArgs[0] if(arg == new(LispSymbol,"pack")): self.value.pack(side=RIGHT, fill=Y) if(arg == new(LispSymbol,"setParent")): parent = evalArgs[1] self.value.configure(command=parent.value.yview)
class EMNN(): def __init__(self, conn): conn.gui = True queue = self.queue = Queue.Queue() conn.queue = queue self.conn = conn def startgui(self): self.root = root = Tk() root.title('SIMAPSE - Simulation Maps for Ecological Niche Modelling') root.geometry('695x445+375+115') root.tk.call('encoding', 'system', 'utf-8') root.configure(bg='#d9d9d9') root.resizable(width='false', height='false') self.gui() self.root.after(100, self.periodicUpdate) root.mainloop() def gui(self): from Tkinter import Button, Entry, Frame, Label, Checkbutton, \ Scrollbar, Text, IntVar, StringVar, OptionMenu self.dir_project = '' self.folds = 0 self.func = "" self.aucfilter = IntVar() self.lightgray = '#d9d9d9' self.darkgray = '#d3d3d3' self.normaltext = ("Helvetica", -10) self.boldtext = ("Helvetica", -10, "bold") self.bigtext = ("Helvetica", -12, "bold") self.smalltext = ("Helvetica", -9) self.butData = Button(self.root) self.butData.place(in_=self.root, x=5, y=5) self.butData.configure(height=1, width=10, text="Data File", font=self.normaltext, highlightbackground=self.lightgray, command=self.dataOpen) self.butRasterFolder = Button(self.root) self.butRasterFolder.place(in_=self.root, x=5, y=35) self.butRasterFolder.configure(height=1, width=10, text="Raster Folder", font=self.normaltext, highlightbackground=self.lightgray, command=self.rasterOpen) self.butOutFolder = Button(self.root) self.butOutFolder.place(in_=self.root, x=5, y=65) self.butOutFolder.configure(height=1, width=10, text="Out Folder", font=self.normaltext, highlightbackground=self.lightgray, command=self.outOpen) self.entData = Entry(self.root) self.entData.place(in_=self.root, x=100, y=9) self.entData.configure(textvariable="file_data", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entData.insert(0, '') self.entOutFolder = Entry(self.root) self.entOutFolder.place(in_=self.root, x=100, y=69) self.entOutFolder.configure(textvariable="out_dir", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entOutFolder.insert(0, '') self.entRasterFolder = Entry(self.root) self.entRasterFolder.place(in_=self.root, x=100, y=39) self.entRasterFolder.configure(textvariable="dir_rasters", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entRasterFolder.insert(0, '') self.activeMethod = StringVar(self.root) self.activeMethod.set("Random repetition") self.butMETHOD = OptionMenu( self.root, self.activeMethod, "Random repetition", "Cross validation", "Bootstrapping", command=lambda x: self.displayMethodFrame(x)) self.butMETHOD.place(in_=self.root, x=4, y=97, height="25", width="120") self.butMETHOD.configure(font=self.smalltext, background=self.lightgray) self.displayMethodFrame(self.activeMethod.get()) self.activeOption = StringVar(self.root) self.activeOption.set("Network structure") self.butOPTION = OptionMenu( self.root, self.activeOption, "Network structure", "Options", command=lambda x: self.displayOptionFrame(x)) self.butOPTION.place(in_=self.root, x=4, y=182, height="25", width="120") self.butOPTION.configure(font=self.smalltext, background=self.lightgray) self.displayOptionFrame(self.activeOption.get()) self.Progress_frame = Frame(self.root) self.Progress_frame.place(in_=self.root, x=5, y=423) self.Progress_frame.configure(borderwidth="2", relief='sunken', height="20", width="105", bg='white') self.Progress_bar = Label(self.Progress_frame) self.Progress_bar.place(x=0, y=0) self.Progress_bar.configure(font=self.smalltext) self.Progress_info = Label(self.root) self.Progress_info.place(x=110, y=425) self.Progress_info.configure(font=self.smalltext, bg=self.lightgray) self.frameButtons = Frame(self.root) self.frameButtons.place(in_=self.root, x=5, y=336) self.frameButtons.configure(borderwidth="2", bg=self.lightgray, relief="raise", height="84", width="260") self.butREAD = Button(self.root) self.butREAD.place(in_=self.frameButtons, x=5, y=5, width=70) self.butREAD.configure(font=self.bigtext, highlightbackground=self.lightgray, text="READ", command=self.read) self.butRUN = Button(self.root) self.butRUN.place(in_=self.frameButtons, x=80, y=5, width=70) self.butRUN.configure(font=self.bigtext, highlightbackground=self.lightgray, text="RUN", command=self.returnVar, state='disabled') self.butRESULTS = Button(self.root) self.butRESULTS.place(in_=self.frameButtons, x=155, y=5, width=80) self.butRESULTS.configure(font=self.bigtext, highlightbackground=self.lightgray, text="RESULTS", command=self.returnResults, state='disabled') self.butPROJECT = Button(self.root) self.butPROJECT.place(in_=self.frameButtons, x=5, y=45, width=70) self.butPROJECT.configure(font=self.boldtext, highlightbackground=self.lightgray, text="PROJECT", command=self.project, state='disabled') self.frameText = Frame(self.root) self.frameText.place(in_=self.root, x=270, y=100) self.frameText.configure(height=320, width=400) self.scrollbar = Scrollbar(self.root) self.textFrame = Text(self.frameText, wrap='word') self.textFrame.configure(font=self.normaltext, height="24", width="65") self.textFrame.place(x=0, y=0) self.textFrame.configure(yscrollcommand=self.scrollbar.set) self.scrollbar.configure(command=self.textFrame.yview, highlightbackground=self.lightgray) self.scrollbar.place(x=675, y=100, height=320) def displayMethodFrame(self, method): ''' Displays individual frames for the subsetting method''' from Tkinter import Button, Entry, Frame, Label if self.__dict__.has_key('frameMethodSelection'): self.frameMethodSelection.destroy() self.varupdate() c = self.conn.simargs self.frameMethodSelection = Frame(self.root) self.frameMethodSelection.place(in_=self.root, x=5, y=122) self.frameMethodSelection.configure(borderwidth="2", relief="raise", height="60", width="260", bg=self.lightgray) if method == "Random repetition": self.labRepetitions = Label(self.root) self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10) self.labRepetitions.configure(font=self.normaltext, borderwidth="1", justify='left', anchor='e', bg=self.lightgray, text="Number of repetitions:") self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=125, y=10) self.entRepetitions.configure(textvariable="repetitions", width="7", font=self.normaltext, highlightbackground=self.lightgray) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) elif method == "Cross validation": self.labRepetitions = Label(self.root) self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10) self.labRepetitions.configure(font=self.normaltext, bg=self.lightgray, text="Number of folds:") self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=100, y=10) self.entRepetitions.configure(textvariable="repetitions", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) elif method == "Bootstrapping": self.labRepetition = Label(self.root) self.labRepetition.place(in_=self.frameMethodSelection, x=2, y=5) self.labRepetition.configure(borderwidth="1", text="Number of Bootstraps:", bg=self.lightgray, font=self.normaltext) self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=125, y=5) self.entRepetitions.configure(textvariable="repetitions", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) self.labBsize = Label(self.root) self.labBsize.place(in_=self.frameMethodSelection, x=2, y=30) self.labBsize.configure(borderwidth="1", text="Bootstraps Sample Size:", bg=self.lightgray, font=self.normaltext) self.entBsize = Entry(self.root) self.entBsize.place(in_=self.frameMethodSelection, x=125, y=30) self.entBsize.configure(textvariable="Bsize", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entBsize.delete(0, 'end') self.entBsize.insert('end', c['bsize']) def displayOptionFrame(self, option): ''' Displays individual frames for the subsetting method''' from Tkinter import Button, Entry, Frame, Label, Checkbutton if self.__dict__.has_key('frameOptionSelection'): self.frameOptionSelection.destroy() self.varupdate() c = self.conn.simargs self.frameOptionSelection = Frame(self.root) self.frameOptionSelection.place(in_=self.root, x=5, y=207) self.frameOptionSelection.configure(borderwidth="2", relief="raise", height="125", width="260", bg=self.lightgray) if option == "Network structure": self.labMaxiter = Label(self.root) self.labMaxiter.place(in_=self.frameOptionSelection, x=190, y=5) self.labMaxiter.configure(borderwidth="1", font=self.normaltext, text="Internal", bg=self.lightgray) self.labNNN = Label(self.root) self.labNNN.place(in_=self.frameOptionSelection, x=95, y=5) self.labNNN.configure(borderwidth="1", font=self.normaltext, text="Reported", bg=self.lightgray) self.labTI = Label(self.root) self.labTI.place(in_=self.frameOptionSelection, x=5, y=25) self.labTI.configure(borderwidth="1", font=self.normaltext, text="Total iterations =", bg=self.lightgray) self.entITERReport = Entry(self.root) self.entITERReport.place(in_=self.frameOptionSelection, x=88, y=25) self.entITERReport.configure(textvariable="AUCReport", width="10", font=self.normaltext, highlightbackground=self.lightgray) self.entITERReport.delete(0, 'end') self.entITERReport.insert('end', c['iterreport']) self.times = Label(self.root) self.times.place(in_=self.frameOptionSelection, x=160, y=25) self.times.configure(text="x", font=self.normaltext, bg=self.lightgray) self.entITERInter = Entry(self.root) self.entITERInter.place(in_=self.frameOptionSelection, x=180, y=25) self.entITERInter.configure(textvariable="maxiter", width="10", font=self.normaltext, highlightbackground=self.lightgray) self.entITERInter.delete(0, 'end') self.entITERInter.insert('end', c['iterinter']) self.labEta = Label(self.root) self.labEta.place(in_=self.frameOptionSelection, x=5, y=55) self.labEta.configure(borderwidth="1", font=self.normaltext, text="Learning Rate", bg=self.lightgray) self.butHINT = Button(self.root) self.butHINT.place(in_=self.frameOptionSelection, x=65, y=75, height=23, width=20) self.butHINT.configure(font=self.smalltext, text="H", command=self.hint, state='disabled', highlightbackground=self.lightgray) self.labMomentum = Label(self.root) self.labMomentum.place(in_=self.frameOptionSelection, x=88, y=55) self.labMomentum.configure(borderwidth="1", font=self.normaltext, text="Momentum", bg=self.lightgray) self.entLRATE = Entry(self.root) self.entLRATE.place(in_=self.frameOptionSelection, x=5, y=75) self.entLRATE.configure(textvariable="eta", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entLRATE.delete(0, 'end') self.entLRATE.insert('end', c['lrate']) self.entMomentum = Entry(self.root) self.entMomentum.place(in_=self.frameOptionSelection, x=90, y=75) self.entMomentum.configure(textvariable="momentum", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entMomentum.delete(0, 'end') self.entMomentum.insert('end', c['momentum']) self.labNNS = Label(self.root) self.labNNS.place(in_=self.frameOptionSelection, x=165, y=55) self.labNNS.configure(borderwidth="1", font=self.normaltext, text="Hidden Layers", bg=self.lightgray) self.entNNShape = Entry(self.root) self.entNNShape.place(in_=self.frameOptionSelection, x=160, y=75) self.entNNShape.configure(textvariable="HiddenLyr", width="14", font=self.normaltext, highlightbackground=self.lightgray) self.entNNShape.delete(0, 'end') self.entNNShape.insert('end', c['hiddenlyrs']) elif option == "Options": self.labPercentage = Label(self.root) self.labPercentage.place(in_=self.frameOptionSelection, x=2, y=5) self.labPercentage.configure(borderwidth="1", text="Test %:", font=self.normaltext, bg=self.lightgray) self.entPercentage = Entry(self.root) self.entPercentage.place(in_=self.frameOptionSelection, x=45, y=5, width=30) self.entPercentage.configure(textvariable="Percentage", font=self.normaltext, highlightbackground=self.lightgray) self.entPercentage.delete(0, 'end') self.entPercentage.insert('end', c['percentage']) self.labAPRatio = Label(self.root) self.labAPRatio.place(in_=self.frameOptionSelection, x=80, y=5) self.labAPRatio.configure(borderwidth="1", text="Pseudoabsences/Presences:", font=self.normaltext, bg=self.lightgray) self.entAPRatio = Entry(self.root) self.entAPRatio.place(in_=self.frameOptionSelection, x=220, y=5) self.entAPRatio.configure(textvariable="apratio", width="4", font=self.normaltext, highlightbackground=self.lightgray) self.entAPRatio.delete(0, 'end') self.entAPRatio.insert('end', c['apratio']) self.labBurnin = Label(self.root) self.labBurnin.place(in_=self.frameOptionSelection, x=2, y=30) self.labBurnin.configure(borderwidth="1", text="Burn-in iterations:", font=self.normaltext, bg=self.lightgray) self.entBurnin = Entry(self.root) self.entBurnin.place(in_=self.frameOptionSelection, x=90, y=30) self.entBurnin.configure(textvariable="burnin", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entBurnin.delete(0, 'end') self.entBurnin.insert('end', c['burnin']) self.chkAucFilter = Checkbutton(self.root) self.chkAucFilter.place(in_=self.frameOptionSelection, x=2, y=60) self.chkAucFilter.configure(font=self.normaltext, text="Filter with AUC threshold", variable=self.aucfilter, bg=self.lightgray, command=self.aucstate) self.labAUCTrain = Label(self.root) self.labAUCTrain.place(in_=self.frameOptionSelection, x=5, y=85) self.labAUCTrain.configure(borderwidth="1", font=self.normaltext, text="training data", bg=self.lightgray) self.entAUCTrain = Entry(self.root) self.entAUCTrain.place(in_=self.frameOptionSelection, x=70, y=85) self.entAUCTrain.configure(textvariable="valueAuc", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entAUCTrain.delete(0, 'end') self.entAUCTrain.insert('end', c['auctrain']) self.labAUCTest = Label(self.root) self.labAUCTest.place(in_=self.frameOptionSelection, x=130, y=85) self.labAUCTest.configure(borderwidth="1", font=self.normaltext, text="testing data", bg=self.lightgray) self.entAUCTest = Entry(self.root) self.entAUCTest.place(in_=self.frameOptionSelection, x=195, y=85) self.entAUCTest.configure(textvariable="valueAucTest", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entAUCTest.delete(0, 'end') self.entAUCTest.insert('end', c['auctest']) self.aucstate() def varupdate(self): extract = self.extract c = self.conn.simargs c['file_data'] = extract('entData', c['file_data']) c['dir_rasters'] = extract('entRasterFolder', c['dir_rasters']) c['out_dir'] = extract('entOutFolder', c['out_dir']) c['method'] = extract('activeMethod', c['method']) c['iterreport'] = int(extract('entITERReport', c['iterreport'])) c['iterinter'] = int(extract('entITERInter', c['iterinter'])) c['lrate'] = float(extract('entLRATE', c['lrate'])) c['momentum'] = float(extract('entMomentum', c['momentum'])) c['hiddenlyrs'] = extract('entNNShape', c['hiddenlyrs']) c['apratio'] = float(extract('entAPRatio', c['apratio'])) c['percentage'] = int(extract('entPercentage', c['percentage'])) c['burnin'] = int(extract('entBurnin', c['burnin'])) c['auctrain'] = float(extract('entAUCTrain', c['auctrain'])) c['auctest'] = float(extract('entAUCTest', c['auctest'])) c['repetitions'] = int(extract('entRepetitions', c['repetitions'])) c['bsize'] = int(extract('entBsize', c['bsize'])) c['aucfilter'] = bool(extract('aucfilter', int(c['aucfilter']))) def extract(self, test, default): if test in self.__dict__.keys(): value = self.__dict__[test].get() else: value = default return value def read(self): import time self.varupdate() self.conn.processor(self.conn.manager.read_all, 'read') def returnVar(self): # Updates variables self.varupdate() self.conn.processor(self.conn.manager.model, 'run') def returnResults(self): self.varupdate() self.conn.processor(self.conn.manager.results, 'results') def project(self): self.varupdate() project_dir = askdirectory() self.conn.simargs['project_dir'] = project_dir self.conn.processor(self.conn.manager.project, 'project') def hint(self): self.varupdate() self.conn.processor(self.conn.manager.hint, 'hint') def dataOpen(self): self.entData.delete(0, 'end') file_data = askopenfilename(filetypes=[("text files", "*.txt"), ("allfiles", "*")]) self.entData.insert('end', file_data) def rasterOpen(self): self.entRasterFolder.delete(0, 'end') dir_rasters = askdirectory() self.entRasterFolder.insert('end', dir_rasters) def outOpen(self): self.entOutFolder.delete(0, 'end') out_dir = askdirectory() self.entOutFolder.insert('end', out_dir) def update_text(self, string_txt): txt = string_txt + " \n" self.textFrame.insert('end', txt) self.textFrame.yview('end') def processGraph(self, graph_object): '''Just a wraper to call the graphics creation object''' graph_object() def periodicUpdate(self): """Executes periodic checks to GUI: - if there are new messages and displays when true""" try: while 1: code, args, kwargs = self.queue.get_nowait() if code == Connector.CODE_TEXT: self.update_text(*args) elif code == Connector.CODE_PROGRESS: self.progress(*args, **kwargs) elif code == Connector.CODE_MODIFY_BUTTON: self.modify_but(*args) elif code == Connector.CODE_SHOWRESULTS: self.showResults(*args) elif code == Connector.CODE_GRAPHS: self.processGraph(args) else: self.update_text('Unknown message...') self.queue.task_done() self.root.update() except Queue.Empty: pass self.root.after(100, self.periodicUpdate) def modify_but(self, state, buttonlist): if buttonlist == 'all': buttonlist = [ 'READ', 'RUN', 'RESULTS', 'PROJECT', 'HINT', 'METHOD', 'OPTION' ] for button in buttonlist: but = "self.but%s.configure(state=\'%s\')" % (button, state) exec(but) def abundance(self): self.entAUCTrain.configure(state='disabled') self.entAUCTest.configure(state='disabled') def aucstate(self): if self.aucfilter.get(): state = 'normal' else: state = 'disabled' self.entAUCTrain.configure(state=state) self.entAUCTest.configure(state=state) def progress(self, value, maxvalue, **kwargs): '''Shows the progress bar in GUI args are: Value - Value of the current progress MaxValue - Value where progress terminates kwargs are color - Color for the progess bar msg - message to display''' color = 'blue' if 'color' in kwargs: color = kwargs['color'] percent = (value * 100) / maxvalue self.Progress_bar.configure(font=self.smalltext, foreground="white", background=color) #"#0000ff" if percent <> 100: width = int((percent / 100.000) * 20) text = '%s%%' % percent self.Progress_bar.configure(text=text, width=width) if 'msg' in kwargs: self.Progress_info.configure(text=kwargs['msg']) elif percent == 100: self.Progress_bar.configure(text="", width=0, relief="flat", background="#ece9d8") self.Progress_info.configure(text="") def showResults(self, figures): from Tkinter import Button figures = [self.entOutFolder.get() + "/" + x for x in figures] ResultsWindow = mytoplevel(self.root, figures, self) ResultsWindow.title('Results') butRW = Button(ResultsWindow, text='CLOSE', command=ResultsWindow.destroy) butRW.pack() def update_queue(self): try: while self.queue.qsize(): msg = '%s\n' % self.queue.get(0) self.textFrame.insert('end', msg) self.textFrame.yview('end') except Queue.Empty: pass
def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class Chatbox(object): def __init__(self, master, my_nick=None, command=None, topic=None, entry_controls=None, maximum_lines=None, timestamp_template=None, scrollbar_background=None, scrollbar_troughcolor=None, history_background=None, history_font=None, history_padx=None, history_pady=None, history_width=None, entry_font=None, entry_background=None, entry_foreground=None, label_template=u"{nick}", label_font=None, logging_file=None, tags=None): self.interior = Frame(master, class_="Chatbox") self._command = command self._is_empty = True self._maximum_lines = maximum_lines self._timestamp_template = timestamp_template self._command = command self._label_template = label_template self._logging_file = logging_file if logging_file is None: self._log = None else: try: self._log = open(logging_file, "r") except: self._log = None top_frame = Frame(self.interior, class_="Top") top_frame.pack(expand=True, fill=BOTH) self._textarea = Text(top_frame, state=DISABLED) self._vsb = Scrollbar(top_frame, takefocus=0, command=self._textarea.yview) self._vsb.pack(side=RIGHT, fill=Y) self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH) self._textarea["yscrollcommand"] = self._vsb.set entry_frame = Frame(self.interior, class_="Chatbox_Entry") entry_frame.pack(fill=X, anchor=N) if entry_controls is not None: controls_frame = Frame(entry_frame, class_="Controls") controls_frame.pack(fill=X) entry_controls(controls_frame, chatbox=self) bottom_of_entry_frame = Frame(entry_frame) self._entry_label = Label(bottom_of_entry_frame) self._entry = Entry(bottom_of_entry_frame) else: self._entry_label = Label(entry_frame) self._entry = Entry(entry_frame) self._entry.pack(side=LEFT, expand=YES, fill=X) self._entry.bind("<Return>", self._on_message_sent) self._entry.focus() if history_background: self._textarea.configure(background=history_background) if history_font: self._textarea.configure(font=history_font) if history_padx: self._textarea.configure(padx=history_padx) if history_width: self._textarea.configure(width=history_width) if history_pady: self._textarea.configure(pady=history_pady) if scrollbar_background: self._vsb.configure(background=scrollbar_background) if scrollbar_troughcolor: self._vsb.configure(troughcolor=scrollbar_troughcolor) if entry_font: self._entry.configure(font=entry_font) if entry_background: self._entry.configure(background=entry_background) if entry_foreground: self._entry.configure(foreground=entry_foreground) if label_font: self._entry_label.configure(font=label_font) if tags: for tag, tag_config in tags.items(): self._textarea.tag_config(tag, **tag_config) self.set_nick(my_nick) @property def topic(self): return @topic.setter def topic(self, topic): return def focus_entry(self): self._entry.focus() def bind_entry(self, event, handler): self._entry.bind(event, handler) def bind_textarea(self, event, handler): self._textarea.bind(event, handler) def bind_tag(self, tagName, sequence, func, add=None): self._textarea.tag_bind(tagName, sequence, func, add=add) def focus(self): self._entry.focus() def user_message(self, nick, content): if self._timestamp_template is None: self._write((u"%s:" % nick, "nick"), " ", (content, "user_message")) else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"), " ", (content, "user_message")) def notification_message(self, content, tag=None): if tag is None: tag = "notification" self._write((content, tag)) notification = notification_message def notification_of_private_message(self, content, from_, to): if self._timestamp_template is None: self.notification_message( u"{from_} -> {to}: {content}".format(from_=from_, to=to, content=content), "notification_of_private_message") else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self.notification_message( u"{timestamp} {from_} -> {to}: {content}".format( timestamp=timestamp, from_=from_, to=to, content=content), "notification_of_private_message") def new_message(self, message): if isinstance(message, User_Message): self.user_message(message.content, message.nick) elif isinstance(message, Notification_Message): self.notification(message.content, message.tag) elif isinstance(message, Notification_Of_Private_Message): self.notification_of_private_message(message.from_, message.to, message.content) else: raise Exception("Bad message") def tag(self, tag_name, **kwargs): self._textarea.tag_config(tag_name, **kwargs) def clear(self): self._is_empty = True self._textarea.delete('1.0', END) @property def logging_file(self): return self._logging_file def send(self, content): if self._my_nick is None: raise Exception("Nick not set") self.user_message(self._my_nick, content) def _filter_text(self, text): return "".join(ch for ch in text if ch <= u"\uFFFF") def _write(self, *args): if len(args) == 0: return relative_position_of_scrollbar = self._vsb.get()[1] self._textarea.config(state=NORMAL) if self._is_empty: self._is_empty = False else: self._textarea.insert(END, "\n") if self._log is not None: self._log.write("\n") for arg in args: if isinstance(arg, tuple): text, tag = arg # Parsing not allowed characters text = self._filter_text(text) self._textarea.insert(END, text, tag) else: text = arg text = self._filter_text(text) self._textarea.insert(END, text) if self._log is not None: self._log.write(text) if self._maximum_lines is not None: start_line = int(self._textarea.index('end-1c').split('.') [0]) - self._maximum_lines if lines_to_delete >= 1: self._textarea.delete('%s.0' % start_line, END) self._textarea.config(state=DISABLED) if relative_position_of_scrollbar == 1: self._textarea.yview_moveto(1) def _on_message_sent(self, event): message = self._entry.get() self._entry.delete(0, END) self.send(message) if self._command: self._command(message) def set_nick(self, my_nick): self._my_nick = my_nick if my_nick: text = self._label_template.format(nick=my_nick) self._entry_label["text"] = text self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry) else: self._entry_label.pack_forget()
class GUI(object): def __init__(self, gen, config, preset_dir): # These will be set later (might consider removing them?) self.deviceIP = "" self.devicePort = 0 self.applicationPort = 0 self.config = config self.preset_dir = preset_dir self.generator = gen try: self.__root = Tk() screen_w = self.__root.winfo_screenwidth() screen_h = self.__root.winfo_screenheight() window_w = self.config["window_width"] window_h = self.config["window_height"] off_w = (screen_w - window_w) / 2 off_h = (screen_h - window_h) / 4 # use 4 instead of 2 self.__root.geometry("%dx%d+%d+%d" % (window_w, window_h, off_w, off_h)) # Delete Window callback self.__root.protocol("WM_DELETE_WINDOW", self.exitCallback) self.__window = self.__root self.__root.wm_title("iPhoneComposer") self.__root.option_add("*tearOff", FALSE) # Create menu menubar = Menu(self.__root) preset_handlers = self.makeShowPresetHandlers() self.__root.config(menu=menubar) optionsMenu = Menu(menubar) menubar.add_cascade(label="Options", menu=optionsMenu) optionsMenu.add_command(label="Show internal state", command=self.showInternalState) presetMenu = Menu(menubar) menubar.add_cascade(label="Presets", menu=presetMenu) for i in xrange(12): presetMenu.add_command(label="Show preset %d state" % (i + 1), command=preset_handlers[i]) # Add an output list that may be accessed publicly mainframe = Frame(self.__window, bd=2, relief=SUNKEN, width=500, height=400) # Output frame outputframe = Frame(mainframe, relief=SUNKEN, width=500, height=200) self.outputscrollbar = Scrollbar(outputframe) self.outputscrollbar.pack(side=RIGHT, fill=Y) Label(outputframe, text="Output").pack(side=TOP) self.output = Text(outputframe, bd=0, yscrollcommand=self.outputscrollbar.set) self.output.pack(pady=(10, 10), padx=(10, 10)) self.output.configure(yscrollcommand=self.outputscrollbar.set) self.outputscrollbar.configure(command=self.output.yview) outputframe.pack_propagate(0) outputframe.pack(fill=None, expand=False) # OSC frame oscframe = Frame(mainframe, relief=SUNKEN, width=500, height=200) self.oscScrollbar = Scrollbar(oscframe) self.oscScrollbar.pack(side=RIGHT, fill=Y) Label(oscframe, text="OSC").pack(side=TOP) self.osc = Text(oscframe, bd=0, yscrollcommand=self.oscScrollbar.set) self.osc.pack(pady=(10, 10), padx=(10, 10)) self.osc.configure(yscrollcommand=self.oscScrollbar.set) self.oscScrollbar.configure(command=self.osc.yview) oscframe.pack_propagate(0) oscframe.pack(fill=None, expand=False) mainframe.pack_propagate(0) mainframe.grid(row=1, column=0) # Create the buttons buttonPane = PanedWindow(self.__window, orient=VERTICAL) buttonPane.grid(row=2, column=0) self.__createButtons(buttonPane) buttonPane.pack_propagate(0) # Create the connection fields connectPane = PanedWindow(self.__window, orient=VERTICAL) connectPane.grid(row=3, column=0) self.__createConnect(connectPane) except: t, v, tb = sys.exc_info() traceback.print_exception(t, v, tb) self.__root.quit() quit() def set_midi_output(self, midi_output): self.__midi_output = midi_output def set_touch_osc(self, touch_osc): self.__touch_osc = touch_osc def raise_above_all(self, window): window.attributes("-topmost", 1) window.attributes("-topmost", 0) def showInternalState(self): self.showState(self.generator.state, "Application Internal State") def makeShowPresetHandlers(self): preset_handlers = [] for i in xrange(1, 13): preset_handlers.append(PresetHandler(self, i)) return preset_handlers def showState(self, state, title): internal_state = "Instrument : %d\n" % state["instrument"] internal_state += "BPM : %d\n" % state["bpm"] internal_state += "Path Pattern : %s\n" % state["path"]["pattern"] internal_state += "Path Generator : %s\n" % state["path"]["order"] rhythm_pattern = self.generator.deserialize_rhythm(state["rhythm"]["pattern"]) internal_state += "Rhythm Pattern :\n" for pat in rhythm_pattern: internal_state += "%s\n" % pat internal_state += "Rhythm Generator : %s\n" % state["rhythm"]["order"] internal_state += "Pitch Pattern :\n" pitch_pattern = self.generator.deserialize_pitch(state["pitch"]["pattern"]) for pat in pitch_pattern: internal_state += "%s\n" % pat internal_state += "Pitch Generator : %s\n" % state["pitch"]["order"] internal_state += "Amplitude Pattern : %s\n" % state["amplitude"]["pattern"] internal_state += "Amplitude Generator : %s" % state["amplitude"]["order"] tkMessageBox.showinfo(title, internal_state) def addToOutput(self, msg): self.output.insert(END, msg) self.output.yview(END) def addToOSC(self, msg): self.osc.insert(END, msg) self.osc.yview(END) def __createButtons(self, pane): # Add the play button play = Button(pane, text="Play", command=self.playCallback) play.grid(row=0, column=0) # Add the pause button pause = Button(pane, text="Pause", command=self.pauseCallback) pause.grid(row=0, column=1) # Add the clear button, which clears the output box. clear = Button(pane, text="Clear", command=self.clearCallback) clear.grid(row=1, column=0) # Add the connect button Button(pane, text="Connect", command=self.connectCallback).grid(row=1, column=1) def __createConnect(self, pane): self.deviceIPaddressVar = StringVar() self.devicePortVar = StringVar() self.applicationPortVar = StringVar() self.deviceIPaddressVar.set("Unknown") self.devicePortVar.set(str(self.config["device_port"])) self.applicationPortVar.set(str(self.config["application_port"])) Label(pane, text="OSC settings").grid(row=0, column=0) Label(pane, text="Device IP Address : ").grid(row=1, column=0) Entry(pane, textvariable=self.deviceIPaddressVar).grid(row=1, column=1) Label(pane, text="Device Input Port : ").grid(row=2, column=0) Entry(pane, textvariable=self.devicePortVar).grid(row=2, column=1) Label(pane, text="Application Input Port : ").grid(row=3, column=0) Entry(pane, textvariable=self.applicationPortVar).grid(row=3, column=1) def __updateConnect(self, ip, port): pass def clearCallback(self): # Clears the output box self.output.delete(0.0, END) self.osc.delete(0.0, END) pass def exitCallback(self): self.__midi_output.exit_notes() self.generator.playing = False self.generator.active = False self.__root.quit() print "Exit was successful." sys.exit(0) def connectCallback(self): print "Connecting..." try: self.devicePort = int(self.devicePortVar.get()) self.applicationPort = int(self.applicationPortVar.get()) self.deviceIP = self.deviceIPaddressVar.get() self.__touch_osc.connect(self.deviceIP, self.devicePort, self.applicationPort) except ValueError: tkMessageBox.showinfo( "Incorrect IP/Port Combination", "Please check that the IP/Port combination you entered is correct" ) except OSCClientError: tkMessageBox.showinfo( "Unable to connect to the device", "Please check that the IP/Port combination you entered is correct" ) def playCallback(self): self.generator.playing = True def pauseCallback(self): self.generator.playing = False def run(self): self.__root.mainloop()
class Chatbox(object): def __init__(self, master, my_nick=None, command=None, topic=None, entry_controls=None, maximum_lines=None, timestamp_template=None, scrollbar_background=None, scrollbar_troughcolor=None, history_background=None, history_font=None, history_padx=None, history_pady=None, history_width=None, entry_font=None, entry_background=None, entry_foreground=None, label_template=u"{nick}", label_font=None, logging_file='log.txt', tags=None): self._master = master self.interior = Frame(master, class_="Chatbox") self._command = command self._is_empty = True self._maximum_lines = maximum_lines self._timestamp_template = timestamp_template self._command = command self._label_template = label_template self._logging_file = logging_file if logging_file is None: self._log = None else: try: self._log = open(logging_file, "a") except: self._log = None #### INSTRUCTION: self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold") self.content_font = tkfont.Font(family='Helvetica', size=13) self.instruction_font = tkfont.Font(family='Courier', size=13) instruction_label_frame = Frame(self.interior, class_="Instruction_label") instruction_label_frame.pack(fill=X) self._label_instruction = Label(instruction_label_frame, text="INSTRUCTIONS", font=self.title_font) self._label_instruction.pack(side=LEFT) instruction_frame = Frame(self.interior, class_="Instruction") instruction_frame.pack(fill=X) self._text_instruction = Text(instruction_frame, height=13, borderwidth=2, relief="groove", font=self.instruction_font) self._text_instruction.pack(fill=X, side=LEFT, expand=True) quote = """1. Read the question. 2. Fill your answer Please answer in a COMPLETE SENTENCE, not just keywords. Example: Good: Bad: Question: What kind of food do you like? Question: What kind of food do you like? Reply: I like spicy food. Reply: spicy food. If you are reluctant to answer the question, click "Next Dialogue" button to go to the next question. 3. press Enter to submit your answer. 4. Rate the reply question in the Evaluation section 5. Click "Next Dialogue" button at the bottom to continue. """ self._text_instruction.insert(END, quote) counter_frame = Frame(self.interior) counter_frame.pack(fill=X) global counter_question counter_question = StringVar() counter_question.set(str(1)) Label(counter_frame, text="").pack(side='top', anchor='w') self._label_counter_1 = Label(counter_frame, text="DIALOGUE", font=self.title_font).pack(side=LEFT) self._label_counter_2 = Label(counter_frame, textvariable=counter_question, font=self.title_font).pack(side=LEFT) self._label_counter_3 = Label(counter_frame, text="OF 10 ", font=self.title_font).pack(side=LEFT) #### MESSAGE DISPLAY AREA: top_frame = Frame(self.interior, class_="Top") top_frame.pack( expand=True, fill=BOTH ) # True: the widget is expanded to fill any extra space, BOTH: fill X&Y self._textarea = Text(top_frame, height=1, borderwidth=2, relief="groove", state=DISABLED, font=self.content_font) self._vsb = Scrollbar(top_frame, takefocus=0, command=self._textarea.yview) self._vsb.pack(side=RIGHT, fill=Y) #scroll bar di kanan, sepanjang sumbu Y self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH) self._textarea.insert(END, '\n') self._textarea[ "yscrollcommand"] = self._vsb.set # text area tempat display chat #### MESSAGE ENTRY: entry_frame = Frame(self.interior, class_="Chatbox_Entry") entry_frame.pack( fill=X, anchor=N ) # fill=X: make all widgets as wide as parent widget, anchor=N: place the text at the top #self.var_entry = StringVar() if entry_controls is not None: controls_frame = Frame(entry_frame, class_="Controls") controls_frame.pack(fill=X) entry_controls(controls_frame, chatbox=self) bottom_of_entry_frame = Frame(entry_frame) self._entry_label = Label(bottom_of_entry_frame) self._entry = Entry( bottom_of_entry_frame) #,textvariable=self.var_entry else: self._entry_label = Label(entry_frame) self._entry = Entry( entry_frame) #, width = 70, textvariable=self.var_entry self._entry.pack(side=LEFT, fill=X, expand=YES) self._entry.bind( "<Return>", self._on_message_sent ) # when user press enter in the chatbox, call on_message_sent self._entry.focus() #self._buttonmessage = Button(entry_frame, text="Submit", width = 20, command=self._on_message_sent) #self._buttonmessage.bind("<Button-1>", self._on_message_sent) # bind the action of the left button of your mouse to the button assuming your primary click button is the left one. #self._buttonmessage.pack(side=LEFT) #### label_evaluation = Frame(self.interior) label_evaluation.pack(fill=X, anchor=N) Label(label_evaluation, text="").pack(side='top', anchor='w') Label(label_evaluation, text="EVALUATION", font=self.title_font).pack(side='top', anchor='w') Label( label_evaluation, text= "Please indicate how strongly you agree or disagree with all the following statements." ).pack(side='top', anchor='w') #Label(label_evaluation, text="").pack(side='top', anchor='w') #### QUESTIONNAIRES: ''' Questionnaire frame''' question_frame = Frame(self.interior) #question_frame.grid(column=0, row=0, sticky=(N, W, E, S)) #question_frame.columnconfigure(0, weight=1) #question_frame.rowconfigure(0, weight=1) #self.configure(background="white") question_frame.pack() self.var_q1 = IntVar() self.var_q2 = IntVar() self.var_q3 = IntVar() self.var_q4 = IntVar() self.var_q1.set(0) # none selected self.var_q2.set(0) # none selected self.var_q3.set(0) # none selected self.var_q4.set(0) # none selected #Label(question_frame, text="").grid(column=0, row=0, sticky="W") #Label(question_frame, text="EVALUATION", font=self.title_font).grid(column=0, row=1, sticky="W") Label(question_frame, text="Strongly disagree").grid(column=1, row=3, padx=4) Label(question_frame, text="Disagree").grid(column=2, row=3, padx=4) Label(question_frame, text="Neither agree nor disagree").grid(column=3, row=3, padx=4) Label(question_frame, text="Agree").grid(column=4, row=3, padx=4) Label(question_frame, text="Strongly agree").grid(column=5, row=3, padx=4) Label(question_frame, text="The grammar of the reply question is correct").grid( column=0, row=4, sticky="W") Radiobutton(question_frame, variable=self.var_q1, value=1).grid(column=1, row=4) Radiobutton(question_frame, variable=self.var_q1, value=2).grid(column=2, row=4) Radiobutton(question_frame, variable=self.var_q1, value=3).grid(column=3, row=4) Radiobutton(question_frame, variable=self.var_q1, value=4).grid(column=4, row=4) Radiobutton(question_frame, variable=self.var_q1, value=5).grid(column=5, row=4) Label( question_frame, text= "The reply question is appropriate to be asked \nin a conversation", justify=LEFT).grid(column=0, row=5, sticky="W") Radiobutton(question_frame, variable=self.var_q2, value=1).grid(column=1, row=5) Radiobutton(question_frame, variable=self.var_q2, value=2).grid(column=2, row=5) Radiobutton(question_frame, variable=self.var_q2, value=3).grid(column=3, row=5) Radiobutton(question_frame, variable=self.var_q2, value=4).grid(column=4, row=5) Radiobutton(question_frame, variable=self.var_q2, value=5).grid(column=5, row=5) Label(question_frame, text="The reply question is related to my answer").grid( column=0, row=6, sticky="W") Radiobutton(question_frame, variable=self.var_q3, value=1).grid(column=1, row=6) Radiobutton(question_frame, variable=self.var_q3, value=2).grid(column=2, row=6) Radiobutton(question_frame, variable=self.var_q3, value=3).grid(column=3, row=6) Radiobutton(question_frame, variable=self.var_q3, value=4).grid(column=4, row=6) Radiobutton(question_frame, variable=self.var_q3, value=5).grid(column=5, row=6) Label(question_frame, text="The dialogue as a whole feels natural").grid(column=0, row=7, sticky="W") Radiobutton(question_frame, variable=self.var_q4, value=1).grid(column=1, row=7) Radiobutton(question_frame, variable=self.var_q4, value=2).grid(column=2, row=7) Radiobutton(question_frame, variable=self.var_q4, value=3).grid(column=3, row=7) Radiobutton(question_frame, variable=self.var_q4, value=4).grid(column=4, row=7) Radiobutton(question_frame, variable=self.var_q4, value=5).grid(column=5, row=7) #E1 = Entry(question_frame) #### NEXT QUESTIONS BUTTON: button_next = Frame(self.interior, class_="Evaluation_3") button_next.pack(fill=X, anchor=N) Label(button_next, text="").pack(side='top', anchor='w') Label( button_next, text= "Please give your comment here.\nFor example, give the reason why do you think the reply question is not appropriate, \nincorrect grammar, not related to your answer, or why it does not feel natural.", justify=LEFT).pack(side='top', anchor='w') self.var_comment = StringVar() self.E1 = Entry(button_next, textvariable=self.var_comment) self.E1.pack(side='top', anchor='w', expand=YES, fill=X) Label(button_next, text="").pack() #button self._button_next = Button(button_next, text="Next Dialogue >>", command=self._on_click_next, width=50) self._button_next.pack() #### if history_background: self._textarea.configure(background=history_background) if history_font: self._textarea.configure(font=history_font) if history_padx: self._textarea.configure(padx=history_padx) if history_width: self._textarea.configure(width=history_width) if history_pady: self._textarea.configure(pady=history_pady) if scrollbar_background: self._vsb.configure(background=scrollbar_background) if scrollbar_troughcolor: self._vsb.configure(troughcolor=scrollbar_troughcolor) if entry_font: self._entry.configure(font=entry_font) if entry_background: self._entry.configure(background=entry_background) if entry_foreground: self._entry.configure(foreground=entry_foreground) if label_font: self._entry_label.configure(font=label_font) if tags: for tag, tag_config in tags.items(): self._textarea.tag_config(tag, **tag_config) self.set_nick(my_nick) @property def topic(self): return @topic.setter def topic(self, topic): return def focus_entry(self): self._entry.focus() def bind_entry(self, event, handler): self._entry.bind(event, handler) def bind_textarea(self, event, handler): self._textarea.bind(event, handler) def bind_tag(self, tagName, sequence, func, add=None): self._textarea.tag_bind(tagName, sequence, func, add=add) def focus(self): self._entry.focus() def user_message(self, nick, content): if self._timestamp_template is None: self._write((u"%s:" % nick, "nick"), " ", (content, "user_message")) else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"), " ", (content, "user_message")) def notification_message(self, content, tag=None): if tag is None: tag = "notification" self._write((content, tag)) notification = notification_message def notification_of_private_message(self, content, from_, to): if self._timestamp_template is None: self.notification_message( u"{from_} -> {to}: {content}".format(from_=from_, to=to, content=content), "notification_of_private_message") else: timestamp = datetime.datetime.now().strftime( self._timestamp_template) self.notification_message( u"{timestamp} {from_} -> {to}: {content}".format( timestamp=timestamp, from_=from_, to=to, content=content), "notification_of_private_message") def new_message(self, message): if isinstance(message, User_Message): self.user_message(message.content, message.nick) elif isinstance(message, Notification_Message): self.notification(message.content, message.tag) elif isinstance(message, Notification_Of_Private_Message): self.notification_of_private_message(message.from_, message.to, message.content) else: raise Exception("Bad message") def tag(self, tag_name, **kwargs): self._textarea.tag_config(tag_name, **kwargs) def clear(self): self._is_empty = True self._textarea.delete('1.0', END) @property def logging_file(self): return self._logging_file def send(self, content): if self._my_nick is None: raise Exception("Nick not set") self.user_message(self._my_nick, content) def _filter_text(self, text): return "".join(ch for ch in text if ch <= u"\uFFFF") def _write(self, *args): if len(args) == 0: return relative_position_of_scrollbar = self._vsb.get()[1] self._textarea.config(state=NORMAL) if self._is_empty: self._is_empty = False else: self._textarea.insert(END, "\n") if self._log is not None: self._log.write("\n") for arg in args: if isinstance(arg, tuple): text, tag = arg # Parsing not allowed characters text = self._filter_text(text) self._textarea.insert(END, text, tag) else: text = arg text = self._filter_text(text) self._textarea.insert(END, text) if self._log is not None: self._log.write(text) if self._maximum_lines is not None: start_line = int(self._textarea.index('end-1c').split('.') [0]) - self._maximum_lines if lines_to_delete >= 1: self._textarea.delete('%s.0' % start_line, END) self._textarea.config(state=DISABLED) if relative_position_of_scrollbar == 1: self._textarea.yview_moveto(1) def _on_message_sent(self, event): if not self._entry.get(): # or not self.var_entry.get() showwarning('Empty answer', 'Please fill your anwer') else: # update flag press enter global flag_press_enter global counter_enter_global if flag_press_enter == False: flag_press_enter = True #counter_enter += 1 if flag_press_enter == True: if counter_enter_global < 2: counter_enter_global += 1 # get the input from user #print("var_entry:",self.var_entry.get()) message = self._entry.get() # clear entry self._entry.delete(0, END) self.send(message) if self._command: self._command( message) # display user input to the chat window if counter_enter_global > 1: self._textarea.config(state=NORMAL) self._textarea.insert( END, "\n[Thank you for your response. Continue to evaluate the Reply Question]" ) self._textarea.config(state=DISABLED) else: ''' running the follow-up question generation ''' with open(input_path, 'w') as f: f.write("%s\n" % message) pp.preprocess_senna_input(input_path, senna_input_path) rs.runSENNA(senna_input_file) # getting semantic representation sentenceList, dlines = fqg.create_SR(senna_input_path) # generate the questions listOfAllGeneratedQA = fqg.generate_questions( sentenceList, dlines) print(listOfAllGeneratedQA) #reply_list = random.choice(listOfAllGeneratedQA[0]) reply = rs.ranking(listOfAllGeneratedQA) if self._log is not None: self._log.write("\nTemplate: %s" % listOfAllGeneratedQA) #reply = reply_list[0] print(reply) self.user_message("Reply question", reply) else: showinfo( 'Thank you', 'Thank you for your response. Please continue to evaluate the Reply Question' ) self._entry.focus() def set_nick(self, my_nick): self._my_nick = my_nick if my_nick: text = self._label_template.format(nick=my_nick) self._entry_label["text"] = text self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry) else: self._entry_label.pack_forget() def _on_click_next(self): global flag_press_enter global counter_enter_global maximum_counter = 10 if flag_press_enter == True and self.var_q1.get( ) != 0 and self.var_q2.get() != 0 and self.var_q3.get( ) != 0 and self.var_q4.get() != 0: global counter_question_global if self._log is not None: self._log.write("\nDialogue number: %s" % str(counter_question_global)) # increase question counter counter_question_global += 1 # write questionnaire's answers to log file if self._log is not None: self._log.write("\nQ1: %s" % self.var_q1.get()) self._log.write("\nQ2: %s" % self.var_q2.get()) self._log.write("\nQ3: %s" % self.var_q3.get()) self._log.write("\nQ3: %s" % self.var_q4.get()) self._log.write("\nComment: %s" % self.var_comment.get()) #print ('debug: ',self.var_q1.get()) if counter_question_global > maximum_counter: showinfo( 'Finish', 'Thank you for your participation! \nWe will now save your responses. \nPress OK to close the application.' ) if OK: self._master.destroy() global flag_close flag_close = True elif self.var_q1.get() == 0 and flag_press_enter == True: showinfo('Rate the evaluation', 'Please rate all evaluations.') elif self.var_q2.get() == 0 and flag_press_enter == True: showinfo('Rate the evaluation', 'Please rate all evaluations.') elif self.var_q3.get() == 0 and flag_press_enter == True: showinfo('Rate the evaluation', 'Please rate all evaluations.') elif self.var_q4.get() == 0 and flag_press_enter == True: showinfo('Rate the evaluation', 'Please rate all evaluations.') else: # clear chat area self._textarea.config(state=NORMAL) self._textarea.delete('1.0', END) self._textarea.config(state=DISABLED) # fill with new starter's question with open(starter_questions) as f: dlines = f.read().splitlines( ) #reading a file without newlines starter = (random.choice(dlines)) self.user_message("Question", starter) # update question counter counter_question.set(str(counter_question_global)) # reset flag_press_enter = False counter_enter_global = 0 self.var_q1.set(0) # questionnaire 1 self.var_q2.set(0) # questionnaire 2 self.var_q3.set(0) # questionnaire 3 self.var_q4.set(0) # questionnaire 3 self.E1.delete(0, END) # clear comment self._entry.delete(0, END) # clear entry message