class ChatWindow(object): def __init__(self, parent, line_sender): self.parent = parent self.main = self.build_window() self.line_sender = line_sender def build_window(self): self.toplevel = tk.Toplevel(self.parent) f = tk.Frame(self.toplevel) f.pack() self.area = ScrolledText(f) self.area.pack(side=tk.TOP) self.area.config(state=tk.DISABLED) self.line = tk.Entry(f) self.line.pack(side=tk.BOTTOM, padx=10, pady=10) self.line.focus_force() self.toplevel.bind('<Return>', self.send_line) return f def send_line(self, _evt): line = self.line.get() self.line.delete(0, tk.END) self.line_sender(line) def add_message(self, msg): self.area.config(state=tk.NORMAL) self.area.insert(tk.END, '%s\n' % msg) self.area.config(state=tk.DISABLED) def set_dispose_callback(self, callback): self.toplevel.protocol('WM_DELETE_WINDOW', callback)
def __init__(self, master, text): Frame.__init__(self, master) text_field = ScrolledText(self) text_field.insert(At(0, 0), text) text_field.pack(side=TOP) text_field.config(state=DISABLED) ButtonBar(self, [], [('Close', self.master.destroy)]).pack(side=BOTTOM, fill=X)
def browser(self, filename): new = Toplevel() # make new window text = ScrolledText(new, height=30, width=90) # Text with scrollbar text.config(font=('courier', 10, 'normal')) # use fixed-width font text.pack() new.title("Text Viewer") # set window mgr attrs new.iconname("browser") text.insert('0.0', open(filename, 'r').read()) # insert file's text
def browser(self, file): new = Toplevel() text = ScrolledText(new, height=30, width=90) text.config(font=('Courier', 9, 'normal')) text.pack() new.title("Poor-man's Text Editor") new.iconname("PyBrowser") text.insert('0.0', open(file, 'r').read())
def browser(self, file): new = Toplevel() text = ScrolledText(new, height=30, width=90) text.config(font=('Courier', 9, 'normal')) text.pack() new.title("Poor-man's Text Editor") new.iconname("PyBrowser") text.insert('0.0', open(file, 'r').read() )
def browser(self, filename): new = Toplevel() # make new window text = ScrolledText(new, height=30, width=90) # Text with scrollbar text.config(font=('courier', 10, 'normal')) # use fixed-width font text.pack() new.title("Text Viewer") # set window mgr attrs new.iconname("browser") text.insert('0.0', open(filename, 'r').read() ) # insert file's text
class PopupScrolledText(PopupWindow): """ Scrolled text output window with 'Save As...' """ def __init__(self, title="", kind="", iconfile=None, var=None): PopupWindow.__init__(self, title=title, kind=kind, iconfile=iconfile) if var: self._var = var else: self._var = BooleanVar() self._var.trace_variable("w", self._visibility_control) self._text = ScrolledText(self) self._text.pack() self._text.config(font=FONT) self._make_menu() self._visibility_control() def on_close(self, *args): self._var.set(False) def _visibility_control(self, *args): if self._var.get(): self.deiconify() else: self.withdraw() def _make_menu(self): topmenu = Menu(self) self.config(menu=topmenu) file = Menu(topmenu, tearoff=0) file.add_command(label="Save as...", command=self.on_save_as) file.add_command(label="Hide", command=self.on_close) topmenu.add_cascade(label="File", menu=file) edit = Menu(topmenu, tearoff=0) edit.add_command(label="Clear text", command=self.on_clear) topmenu.add_cascade(label="Edit", menu=edit) def on_save_as(self): filename = asksaveasfilename() if filename: alltext = self.gettext() f = open(filename, "w") f.write(alltext) f.close() def on_clear(self): self._text.delete("0.0", END) self._text.update() def gettext(self): return self._text.get("1.0", END + "-1c") def hide(self): self._var.set(False) def show(self): self._var.set(True)
def setUpClipArea(self, frame): ''' @summary: クリップボートの表示エリアを作成します ''' xscrollbar = Tk.Scrollbar(frame, orient=Tk.HORIZONTAL) st = ScrolledText(frame, bg="GRAY", xscrollcommand=xscrollbar.set, height=10) st.config(state=Tk.DISABLED) return st
def __init__(self, parent, text, title="Phoshare Help"): Toplevel.__init__(self, parent) self.transient(parent) self.title(title) self.parent = parent t = ScrolledText(self) t.insert(END, text) t.config(state=DISABLED) t.pack()
def _getHelp(self): win = Tk.Toplevel(self.tks) win.title("Help") helptext = ScrolledText(win) helptext.config(state=Tk.NORMAL) helptext.insert('1.0', __help_text__) helptext.config(state=Tk.DISABLED) helptext.pack() Tk.Button(win, text='OK', command=win.destroy).pack()
class MemorablePwdsApp(pp2e_laj.gui.tools.guimixin.GuiMixin, pp2e_laj.gui.tools.guimaker.GuiMakerWindowMenu): """(Tkinter) User interface for memorable passwords application.""" def clear(self): """Clear all the candidate passwords.""" self._candidates = [] self.refreshCandidates() def generate(self): """Generates a set of candidate passwords.""" for i in range(0, 8): self._candidates.append(self._generator.next()) self.refreshCandidates() def help(self): pp2e_laj.gui.tools.guimaker.GuiMakerWindowMenu.help(self) def makeWidgets(self): middle = Frame(self) middle.pack(expand=YES, fill=BOTH) Label(middle, text='Candidate Passwords').grid(row=0, column=0, sticky=NSEW) self.candidatesView = ScrolledText(middle, height=15, width=45) self.candidatesView.config(font=('courier', 10, 'normal')) self.candidatesView.grid(row=1, column=0, sticky=NSEW) Label(middle, text='Try It!').grid(row=0, column=1, sticky=NSEW) self.scratchPadView = ScrolledText(middle, height=15, width=45) self.scratchPadView.config(font=('courier', 10, 'normal')) self.scratchPadView.grid(row=1, column=1, sticky=NSEW) def refreshCandidates(self): self.candidatesView.delete('1.0', END) for word in self._candidates: self.candidatesView.insert(END, word + '\n') def start(self): """Initialize the menu bar and tool bar of the application.""" self._candidates = [] self._generator = mem_pwds.MemorablePwds.MemorablePwds() self.menuBar = [ ('File', 0, [('New', 0, self.clear), ('Exit', 0, sys.exit)]), ('Edit', 0, [('Generate', 0, self.generate)]), ] self.toolBar = [ ('Generate', self.generate, {'side': LEFT}), ('Clear', self.clear, {'side': LEFT}), ]
class NoteCreate(Toplevel): """ Create Note page """ def __init__(self): Toplevel.__init__(self) self.bg_page = PhotoImage(file="Image/note_bg1.gif") self.favorite_logo = PhotoImage(file="Image/favorite2.gif") def note_page(self, text_title, text_note, favorite): """Display a Note when add new note or edit note""" def add_destroy(): """add new data and destroy current window""" message = tkMessageBox.showinfo('Status', 'Complete') add_data(text_title, text_note, date(), favorite) self.destroy() self.background = Label(self, image=self.bg_page) self.new_note = Label(self, text=text_title, bg='#efe9dc', fg='#f46b2f', font=('AngsanaUPC', 18, 'bold')) self.txt = ScrolledText(self, width=44, height=13, bg='#efe9dc',\ font=('AngsanaUPC', 14), relief=FLAT) self.txt.insert('1.0', text_note) self.txt.config(state='disable') self.ok = Button(self, text='Ok', bg='#02d602', relief=FLAT, width=10, fg='white', font=('Arial', 10, 'bold'), command=add_destroy, activebackground='#49B203', activeforeground='white') self.cancel = Button(self, text='Cancel', bg='#a0a0a0', relief=FLAT, width=10, fg='white', font=('Arial', 10, 'bold'), activebackground='#838483', activeforeground= 'white', command=self.destroy) self.background.place(x=0, y=0) self.new_note.place(x=30, y=50) self.txt.place(x=25, y=100) self.ok.place(x=80, y=455) self.cancel.place(x=190, y=455) if favorite == 1: self.favor = Label(self, image=self.favorite_logo, bg='#efe9dc') self.favor.place(x=266, y=40) self.bind("<Button-1>", self.flat) def flat(self, event): """Event widget flat""" event.widget.config(relief=FLAT)
def __init__(self, appname, helptext, iconfile=None, showsource=lambda: 0): PopupWindow.__init__(self, appname, 'Help', iconfile) from ScrolledText import ScrolledText # a non-modal dialog bar = Frame(self) # pack first=clip last bar.pack(side=BOTTOM, fill=X) code = Button(bar, bg='beige', text="Source", command=showsource) quit = Button(bar, bg='beige', text="Cancel", command=self.destroy) code.pack(pady=1, side=LEFT) quit.pack(pady=1, side=LEFT) text = ScrolledText(self) # add Text + scrollbar text.config(font=self.myfont, width=70) # too big for showinfo text.config(bg='steelblue', fg='white') # erase on btn or return text.insert('0.0', helptext) text.pack(expand=YES, fill=BOTH) self.bind("<Return>", (lambda event: self.destroy()))
def showhelp(helptext=helptext, appname='PyMail'): # show helptext in from ScrolledText import ScrolledText # a non-modal dialog new = Toplevel() # make new popup window bar = Frame(new) # pack first=clip last bar.pack(side=BOTTOM, fill=X) code = Button(bar, bg='beige', text="Source", command=showsource) quit = Button(bar, bg='beige', text="Cancel", command=new.destroy) code.pack(pady=1, side=LEFT) quit.pack(pady=1, side=LEFT) text = ScrolledText(new) # add Text + scrollbar text.config(font='system', width=70) # too big for showinfo text.config(bg='steelblue', fg='white') # erase on btn or return text.insert('0.0', helptext) text.pack(expand=YES, fill=BOTH) new.title(appname + " Help") new.bind("<Return>", (lambda event, new=new: new.destroy()))
class GuiOutput: def __init__(self, parent=None): self.text = None if parent: self.popupnow(parent) # popup now or on first write def popupnow(self, parent=None): # in parent now, Toplevel later if self.text: return self.text = ScrolledText(parent or Toplevel()) self.text.config(font=('courier', 9, 'normal')) self.text.pack() def write(self, text): self.popupnow() self.text.insert(END, str(text)) self.text.see(END) self.text.update() def writelines(self, lines): # lines already have '\n' for line in lines: self.write(line) # or map(self.write, lines)
def search_cmd(self): query = {} query['title'] = self.title_entry.get() query['genre'] = self.genre_entry.get() query['director'] = self.director_entry.get() query['date'] = self.date_entry.get() runtime = self.options.index(self.runtime_var.get()) * 60 - 1 query['runtime'] = MovieTime(runtime).quartile() is_empty = True for v in query.itervalues(): if v != "" and v != "None": is_empty = False if self.id_entry.get() != "": is_empty = False self.runtime_var.get() if is_empty: tkMessageBox.showerror("Error", "At least one field should be provided.") else: if self.id_entry.get() != "": docs = app.get_documents([int(self.id_entry.get())]) else: docs = app.search(query) # Create results window results_window = Toplevel(self) results_window.resizable(width=False, height=False) results_window.wm_title(str(len(docs)) + " Results") results_window.focus_set() text = ScrolledText(results_window, width=60, height=40) text.grid(padx=20, pady=20) docs_str = "" for doc in docs: docs_str += doc + '\n\n' docs_str = docs_str[:len(docs_str)-2] text.insert(END, docs_str) text.config(state=DISABLED)
def showhelp(helptext=helptext, appname="PyMail"): # show helptext in from ScrolledText import ScrolledText # a non-modal dialog new = Toplevel() # make new popup window bar = Frame(new) # pack first=clip last bar.pack(side=BOTTOM, fill=X) code = Button(bar, bg="beige", text="Source", command=showsource) quit = Button(bar, bg="beige", text="Cancel", command=new.destroy) code.pack(pady=1, side=LEFT) quit.pack(pady=1, side=LEFT) text = ScrolledText(new) # add Text + scrollbar text.config(font="system", width=70) # too big for showinfo text.config(bg="steelblue", fg="white") # erase on btn or return text.insert("0.0", helptext) text.pack(expand=YES, fill=BOTH) new.title(appname + " Help") new.bind("<Return>", (lambda event, new=new: new.destroy()))
class Terminal(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.CreateWidgets() self.prompt = '>>> ' configfile = open('adminclientconfig.txt', 'r') hostname = configfile.readline().strip() port = int(configfile.readline().strip()) username = configfile.readline().strip() password = configfile.readline().strip() self.conn = Connection(hostname, port, username, password ,self.ReceiveMessage ,lambda: self.ReceiveMessage("connection successful") ,lambda: self.ReceiveMessage("ERROR!!!!")) def destroy(self): self.conn.Shutdown() Frame.destroy(self) def CreateWidgets(self): self.text = ScrolledText(self, state=DISABLED, height=30) self.text["fg"] = "white" self.text["bg"] = "black" self.text.pack() self.entry = Entry(self) self.entry["fg"] = "white" self.entry["bg"] = "black" self.entry.pack(fill=X,pady=0) self.entry.bind("<Key-Return>", self.SendMessage) # self.entry.bind("<Key-Tab>", lambda _: self.entry.insert(INSERT, "\t")) def SendMessage(self, event): data = self.entry.get() self.entry.delete(0, END) self.conn.OnCommand(data, self.OnResult) self.ReceiveMessage(self.prompt + data) # echo def ReceiveMessage(self, data): self.text.config(state=NORMAL) self.text.insert(END, data+"\n") self.text.config(state=DISABLED) self.text.yview_pickplace('end') def OnResult(self, more): if more: self.prompt = '... ' else: self.prompt = '>>> '
class GuiOutput: def __init__(self, parent=None): self.text = None if parent: self.popupnow(parent) # popup now or on first write def popupnow(self, parent=None): # in parent now, Toplevel later if self.text: return self.text = ScrolledText(parent or Toplevel()) self.text.config(font=('courier', 9, 'normal')) self.text.pack() def write(self, text): self.popupnow() self.text.insert(END, str(text)) self.text.see(END) self.text.update() def writelines(self, lines): # lines already have '\n' for line in lines: self.write(line) # or map(self.write, lines)
def __init__(self): Toplevel.__init__(self) self.geometry('500x400') Label(self, text = 'Read Me').pack() text= ScrolledText(self, bg="lightgray") text['font'] = ('console','10') text.insert(END," welcome to monitor tool\n\n \ Here is some notes which will help you use monitor tool\n\n\ 1. About SMTP setting, please input your smtp user/passwd information, till now only QQ email smtp is varified\ for other smtp emails can not garantee. also you should open POP3/SMTP setting, the passwd is grant access passwd\ you can click verity email button to check the input smtp server is okay or not\n\n\ 2. About server information, please input the target server ip/user/passwd and command keyword which will be used\ to search its pid, ps -ef | grep <command keyword>. also input the command log path, which will be used to fetch command\ result, the frequency(mins), default value is 5 mins, means monitor will ssh to server every 5 mins to fetch pid status\n\n\ 3. About the email to address, you can add more then one email address into this enty, like ***@qq.com;***@ericsson.com\n\n\ 4. About Enable report progress, if want to know the script progress every certain period(30 mins, 1 hour...), you can select this checkbutton\ the monitor will fetch script log and send out by email") text.see("end") text.pack() text.config(state=DISABLED)
class ChatWindow(object): def __init__(self, parent, line_sender): self.parent = parent self.main = self.build_window() self.line_sender = line_sender def build_window(self): self.toplevel = tk.Toplevel(self.parent) f = tk.Frame(self.toplevel) f.pack() self.area = ScrolledText(f) self.area.pack(side=tk.TOP) self.area.config(state=tk.DISABLED) self.line = tk.Entry(f) self.line.pack(side=tk.BOTTOM, padx=10, pady=10) self.line.focus_force() self.toplevel.bind('<Return>', self.send_line) return f def send_line(self, _evt): line = self.line.get() self.line.delete(0, tk.END) self.line_sender(line) def add_message(self, msg): self.area.config(state=tk.NORMAL) self.area.insert(tk.END, '%s\n' % msg) self.area.config(state=tk.DISABLED) def set_dispose_callback(self, callback): self.toplevel.protocol('WM_DELETE_WINDOW', callback)
class GuiOutput: def __init__(self, name,parent=None): self.text = None self.titleName = name if parent: self.popupnow(name,parent) # popup now or on first write def popupnow(self,name,parent=None): # in parent now, Toplevel later if self.text: return newTopLevel = Toplevel() self.text = ScrolledText(parent or newTopLevel) newTopLevel.title(name) self.text.config(font=('courier', 9, 'normal')) #if it is a toplevel textbox, set its title. self.text.pack() def write(self, text): self.popupnow(self.titleName) #if len(self.text.get("1.0")) > 1024: # self.text.delete("1.0",END) self.text.insert(END, str(text)) self.text.see(END) self.text.update() def writelines(self, lines): # lines already have '\n' for line in lines: self.write(line) # or map(self.write, lines) def flush(self): pass
class ServerGUI(object): server_on = False def __init__(self, window_title="Server GUI"): self.base_gui = pygui.Tk() self.window_title = window_title self.server_port = 0 self.server = None # [GUI Initialization] ::start self.server_config_frame = pygui.Frame(self.base_gui) self.port_to_use_field = pygui.Entry(self.server_config_frame) self.server_controls_frame = pygui.Frame(self.base_gui) self.create_server_btn = pygui.Button(self.server_controls_frame, text="Start Server", command=self.invoke_server) self.stop_server_btn = pygui.Button(self.server_controls_frame, text="Stop Server", command=self.stop_server) self.quit_btn = pygui.Button(self.server_controls_frame, text="Quit", command=self.destroy_gui) # [GUI Initialization] ::end self.server_logs_frame = pygui.Frame(self.base_gui) self.activity_log_area = ScrolledText(self.server_logs_frame, height=10, width=50) def bootstrap(self): if self.server is None: print "Server Object must be specified. Call the set_server() method and set the ServerGUI Object." sys.exit(1) # set window title self.base_gui.wm_title(self.window_title) # [Config Section] :start self.server_config_frame.pack(side=pygui.TOP, pady=10) # Add field for port to use pygui.Label(self.server_config_frame, text="Server port to use").grid(row=0, column=0) self.port_to_use_field.grid(row=0, column=1) self.port_to_use_field.bind("<Return>", self.invoke_server) # [Config Section] :end # [Controls Section] ::start self.server_controls_frame.pack(side=pygui.RIGHT, fill=pygui.Y) # Add Start server button self.create_server_btn.grid(row=0, column=1) # Stop Server self.stop_server_btn.grid(row=1, column=1) # Quit Button self.quit_btn.grid(row=2, column=1) # [Controls Section] ::end # [Logs Section] ::start self.server_logs_frame.pack(side=pygui.LEFT, padx=10, pady=10) # Create a text area for showing logs. pygui.Label(self.server_logs_frame, text="Logs").grid(row=0) self.activity_log_area.edit_modified(0) self.activity_log_area.grid(row=1) self.activity_log_area.config(highlightbackground="black") self.activity_log_area.bind('<<Modified>>', self.scroll_to_end) # [Logs Section] ::end # handle close button self.base_gui.protocol("WM_DELETE_WINDOW", self.destroy_gui) # Start the GUI self.base_gui.mainloop() def set_server(self, server): self.server = server def scroll_to_end(self, *_): # scroll to the end of text area self.activity_log_area.see(pygui.END) self.activity_log_area.edit_modified(0) def destroy_gui(self): self.stop_server() self.base_gui.destroy() def stop_server(self, *_): if self.server_on is True: self.server.stop(self.log) # set the SERVER_ON flag to false to enable create a new server instance self.server_on = False else: self.log("Server already stopped.") def invoke_server(self, *_): portval = self.port_to_use_field.get() if portval != '': # check if the input for port number is a valid integer try: self.server_port = int(portval) except ValueError: msgBox.showinfo("Client GUI", "Invalid Port Number") return # start the server if not yet started if self.server_on is False: # log the message self.server.set_port(self.server_port) if not self.server.invoke(self.log): msgBox.showinfo( "Client GUI", "Cannot bind to port: %s. Please select another port to bind on." % str(self.server_port)) return # Prevent starting another instance of server self.server_on = True else: self.log("Server already started on port: " + str(self.server_port)) else: self.log( "Please provide port number for the server to bind on. Thanks!" ) def log(self, message): self.activity_log_area.insert(pygui.END, message + "\n")
class BackupUI(Frame): def __init__(self, parent=None, **options): Frame.__init__(self, parent, padx=10, pady=10) self.dataQueue = queue.Queue() self.thread = None self.outputPath = StringVar() self.userVar = IntVar() self.photoVar = IntVar() self.photoVar.set(1) self.top = Frame(self) self.top.pack(side=TOP, expand=YES, fill=X) self.top.config(bd=2) self.createForm() self.createButtons() self.createText() def createButtons(self): frm = Frame(self.top) frm.pack(side=RIGHT, expand=YES, anchor=NE) self.btnStart = Button(frm, text='开始备份', command=self.start) self.btnStart.pack(side=TOP) self.btnStop = Button(frm, text='停止备份', command=self.stop) self.btnStop.pack(side=TOP) self.btnStop.config(state=DISABLED) frm = Frame(self.top) frm.pack(side=RIGHT, expand=YES, anchor=NE) self.userCheck = Checkbutton(frm, text='备份好友资料', variable=self.userVar) self.userCheck.config(command=self.callback) self.userCheck.pack(side=TOP) self.photoCheck = Checkbutton( frm, text='备份相册照片', variable=self.photoVar) self.photoCheck.config(command=self.callback) self.photoCheck.pack(side=TOP) frm = Frame(self, pady=5, padx=5) frm.pack(side=TOP, anchor=W) self.btnSelect = Button(frm, text='选择保存路径', command=self.selectPath) self.btnSelect.pack(side=LEFT) self.savePath = Entry(frm, width=45, textvariable=self.outputPath) self.savePath.pack(side=LEFT) self.savePath.insert(END, os.path.abspath(os.path.join('.', 'output'))) def createForm(self): self.login = Frame(self.top) # self.login.config(padx=4, pady=4) self.login.pack(side=LEFT, anchor=W) fields = const.LOGIN_FIELDS self.inputs = [] for i in range(len(fields)): lbl = Label(self.login, text=fields[i]) lbl.grid(row=i, column=0) var = StringVar() self.inputs.append(var) ent = Entry(self.login, textvariable=var) ent.grid(row=i, column=1) self.login.rowconfigure(i, weight=1) self.login.columnconfigure(0, weight=1) self.login.columnconfigure(1, weight=1) def createText(self): winfont = ('simhei', 10, 'normal') font = ('Helvetica', 12, 'normal') self.content = Frame(self, pady=5) self.content.pack(side=LEFT, expand=YES, fill=BOTH) self.text = ScrolledText(self.content) self.text.pack(side=TOP, expand=YES, fill=BOTH) self.text.config(bg='light gray', fg='black') self.text.config(padx=10, pady=10, font=winfont if isWin32 else font) self.text.insert(END, const.USER_GUIDE) self.text.config(state=DISABLED) def selectPath(self): path = askdirectory(initialdir='.') if path: self.savePath.delete(0, END) self.savePath.insert(END, path) def callback(self): #print('callback', self.userVar.get(), self.photoVar.get()) pass def write(self, message): if message and message.strip(): # timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.dataQueue.put(timestamp+" - "+message+'\n') def updateText(self, message): self.text.config(state=NORMAL) self.text.insert(END, str(message)) self.text.config(state=DISABLED) self.text.see(END) self.text.update() def updateUI(self): try: message = self.dataQueue.get(block=False) if message: self.updateText(message) except queue.Empty: pass running = self.thread and self.thread.is_alive() self.btnStart.config(state=DISABLED if running else NORMAL) self.btnStop.config(state=NORMAL if running else DISABLED) self.after(100, self.updateUI) def stop(self): if getattr(self, 'thread'): self.thread.stop() def start(self): keys = ['username', 'password', 'target'] values = map(lambda x: x.get(), self.inputs) if not any(values): showerror(const.NO_INPUT_TITLE, const.NO_INPUT_MESSAGE) return options = dict(zip(keys, values)) options['output'] = self.savePath.get() options['include_user'] = self.userVar.get() options['include_photo'] = self.photoVar.get() print('启动参数:', options) self.text.config(state=NORMAL) self.text.delete('0.0', END) self.text.config(state=DISABLED) self.updateUI() self.thread = BackupThread(self, self.dataQueue, **options) self.thread.start()
def viewfile(): new = Toplevel() text = ScrolledText(new, height=30, width=90) text.config(font=('Comic Sans MS', 14, 'normal')) text.pack() text.insert('0.0', askopenfile().read(16384))
class LogFrame: def __init__(self, root, options, main_logger): self.root = root self.options = options self.main_logger = main_logger self.frame = tk.Frame(self.root) self.frame.columnconfigure(0, weight=1) # first row doesn't expoands self.frame.rowconfigure(0, weight=0) # let the second row grow self.frame.rowconfigure(1, weight=1) self.log_commands_frame = tk.LabelFrame(self.frame, text="Controls", padx=5, pady=5) self.log_commands_frame.grid(row=0, column=0, sticky=tk.NSEW, padx=4, pady=5) self.log_messages_frame = tk.Frame(self.frame) self.log_messages_frame.grid(row=1, column=0, sticky=tk.NSEW) # let the SIP trace growing self.log_messages_frame.columnconfigure(0, weight=1) self.log_messages_frame.rowconfigure(0, weight=1) self.log_messages = ScrolledText(self.log_messages_frame) self.log_messages.grid(row=0, column=0, sticky=tk.NSEW) # Log Messages frame row = 0 self.log_messages_clear_button = tk.Button(self.log_commands_frame, text="Clear", command=self.clear_log_messages) self.log_messages_clear_button.grid(row=row, column=0, sticky=tk.N) self.log_messages_pause_button = tk.Button(self.log_commands_frame, text="Pause", command=self.pause_log_messages) self.log_messages_pause_button.grid(row=row, column=1, sticky=tk.N) row = row + 1 def get_frame(self): return self.frame def clear_log_messages(self): self.log_messages.config(state='normal') self.log_messages.delete(0.0, tk.END) self.log_messages.config(state='disabled') def pause_log_messages(self): if self.log_messages_alarm is not None: self.log_messages.after_cancel(self.log_messages_alarm) self.log_messages_pause_button.configure(text="Resume", command=self.start_log_messages) self.log_messages_alarm = None def start_log_messages(self): self.update_log_messages_widget() self.log_messages_pause_button.configure(text="Pause", command=self.pause_log_messages) def update_log_messages_widget(self): self.update_widget(self.log_messages, self.log_queue) self.log_messages_alarm = self.log_messages.after(20, self.update_log_messages_widget) def update_widget(self, widget, queue): widget.config(state='normal') while not queue.empty(): line = queue.get() widget.insert(tk.END, line) widget.see(tk.END) # Scroll to the bottom widget.update_idletasks() widget.config(state='disabled')
class Crawler_plusplus(): def __init__(self): self.rt = tk.Tk() #创建窗口 self.rt.title('Automatically download pictures') #窗口标题 self.menu = tk.Menu(self.rt) #在根窗口里创建一个菜单 self.rt.config(menu=self.menu) #把新创建菜单定为根窗口的菜单 self.aboutmenu = tk.Menu(self.menu) #在根窗口菜单里创建一个菜单 self.picturemenu = tk.Menu(self.menu) #在根窗口菜单里创建一个菜单 self.aboutmenu.add_command(label='help', command=self.help) #菜单里的菜单增加“help”命令 self.menu.add_cascade(label='About', menu=self.aboutmenu) #把菜单里的菜单命名为about self.menu.add_cascade(label='Picture Proecessing', menu=self.picturemenu) self.picturemenu.add_command(label='Start Proecessing', command=self.Picture_Processing) self.menu.add_command(label='refresh', command=self.refresh) self.menu.add_command(label='Exit', command=self.close) self.frame1 = tk.Frame(self.rt, height=260, width=520) #左边模块,负责爬取百度图片 self.middle = tk.Frame(self.rt, height=260, width=120) #右边模块,用来提示错误信息 self.lframe1 = tk.LabelFrame(self.frame1, height=60, width=520, text='Save path') self.lframe2 = tk.LabelFrame(self.frame1, height=200, width=520, text='Download') self.b1 = tk.Button(self.lframe1, text='Choose', width=8, height=1, command=self.get_directory1) self.b2 = tk.Button(self.lframe1, text='Confirm', width=10, height=1, command=self.confirm_e) self.b3 = tk.Button(self.lframe1, text='Cancel', width=10, height=1, command=self.deconfirm_e, state='disabled') self.a1 = tk.Button(self.lframe2, text='Get the picture', width=10, height=1, command=self.start_cr, state='disabled') self.e1 = tk.Entry(self.lframe1, takefocus=True) self.e2 = tk.Entry(self.lframe2, state='disabled') self.alo = tk.Label(self.rt, text='Note:') #中间模块的内容 self.ala = tk.Label(self.rt, text='', foreground='red') #中间模块的错误提示,内容现在是空的 self.l1 = tk.Label(self.lframe2, text='Key words:', relief='flat') self.l2 = tk.Label(self.lframe2, text='Download progress:', relief='groove') self.s = ScrolledText(self.lframe2, height=8, width=40, state='disabled', wrap='char', borderwidth=0) self.frame1.grid(column=0, row=0, rowspan=2, columnspan=1) self.lframe1.grid(row=0, column=1) self.b1.place(x=45, y=15, anchor='center') self.e1.place(x=280, y=15, anchor='e') self.b2.place(x=400, y=15, anchor='e') self.b3.place(x=480, y=15, anchor='e') self.lframe2.grid(row=1, column=1) self.l1.place(x=130, y=15, anchor='e') self.e2.place(x=280, y=15, anchor='e') self.a1.place(x=400, y=15, anchor='e') self.l2.place(x=15, y=45, anchor='w') self.s.place(x=15, y=115, anchor='w') self.middle.grid(column=1, row=0) self.ala.place(x=580, y=140, anchor='center') self.alo.place(x=580, y=120, anchor='center') #图形处理界面 def Picture_Processing(self): top = tk.Toplevel() top.title('Picture Processing') top.geometry('520x260') self.frame2 = tk.Frame(top, height=260, width=520) #框架 用来批量处理图片 self.lframe3 = tk.LabelFrame(self.frame2, height=140, width=520, text='图片预处理') self.lframe4 = tk.LabelFrame(self.frame2, height=60, width=520, text='保存图片集') self.lframe5 = tk.LabelFrame(self.frame2, height=60, width=520, text='预处理图片路径选择') self.b4 = tk.Button(self.lframe5, text='选择图片目录', width=12, height=1, command=self.get_directory5) self.b5 = tk.Button(self.lframe5, text='确定该目录', width=10, height=1, command=self.confirm_e1) self.b6 = tk.Button(self.lframe5, text='取消确定', width=10, height=1, command=self.deconfirm_e1, state='disabled') self.a2 = tk.Button(self.lframe3, text='图片处理启动', width=10, height=1, command=self.start_pi, state='disabled') self.ad = tk.Button(self.lframe4, text='选择保存文件夹', width=14, height=1, command=self.get_directory4, state='disabled') self.a3 = tk.Button(self.lframe4, text='确定该目录', width=10, height=0, command=self.confirm_e2, state='disabled') self.a4 = tk.Button(self.lframe4, text='取消确定', width=10, height=0, command=self.deconfirm_e2, state='disabled') self.a5 = tk.Button(self.lframe3, text='默认设置', width=10, height=1, command=self.reset, state='disabled') self.e3 = tk.Entry(self.lframe5, takefocus=True) self.e4 = tk.Entry(self.lframe4, takefocus=True, state='disabled') self.alb = tk.Label(self.lframe5, text='', foreground='red') self.l3 = tk.Label(self.lframe3, text='处理进度:', relief='groove') self.xlen = tk.IntVar() self.xlen.set(128) self.ylen = tk.IntVar() self.ylen.set(128) self.xl = tk.Entry(self.lframe3, state='readonly', width=4, textvariable=self.xlen, invcmd=self.alarm) self.yl = tk.Entry(self.lframe3, state='readonly', width=4, textvariable=self.ylen, invcmd=self.alarm) self.xv = tk.Label(self.lframe3, text='输出图宽:') self.yv = tk.Label(self.lframe3, text='输出图高:') self.note1 = tk.Label(self.lframe3, text='建议输出\n128*128') self.s1 = ScrolledText(self.lframe3, height=6, width=40, state='disabled', borderwidth=0) self.color = tk.IntVar() self.color.set(0) self.rb1 = tk.Radiobutton(self.lframe3, text='灰色', variable=self.color, value=0, state='disabled') self.rb2 = tk.Radiobutton(self.lframe3, text='彩色', variable=self.color, value=1, state='disabled') self.cls = tk.Label(self.lframe3, text='输出图片颜色') self.type = tk.Label(self.lframe3, text='输出图片格式') self.type.place(x=75, y=5, anchor='w') self.ty = tk.IntVar() self.ty.set(0) self.rb3 = tk.Radiobutton(self.lframe3, text='jpg', variable=self.ty, value=0, state='disabled') self.rb4 = tk.Radiobutton(self.lframe3, text='png', variable=self.ty, value=1, state='disabled') self.rb5 = tk.Radiobutton(self.lframe3, text='jpeg', variable=self.ty, value=2, state='disabled') self.rb3.place(x=150, y=5, anchor='w') self.rb4.place(x=200, y=5, anchor='w') self.rb5.place(x=250, y=5, anchor='w') self.a3.place(x=400, y=45, anchor='e') self.a4.place(x=480, y=45, anchor='e') self.frame2.grid(column=2, row=0, rowspan=3, columnspan=1) self.lframe5.grid(column=0, row=0) self.b4.place(x=80, y=15, anchor='center') self.e3.place(x=280, y=15, anchor='e') self.b5.place(x=400, y=15, anchor='e') self.b6.place(x=480, y=15, anchor='e') self.alb.place(x=550, y=15, anchor='e') self.lframe4.grid(column=0, row=1) self.ad.place(x=80, y=15, anchor='center') self.e4.place(x=280, y=15, anchor='e') self.a3.place(x=400, y=15, anchor='e') self.a4.place(x=480, y=15, anchor='e') self.lframe3.grid(column=0, row=2) self.l3.place(x=15, y=15, anchor='w') self.s1.place(x=15, y=70, anchor='w') self.xv.place(x=330, y=30, anchor='w') self.xl.place(x=390, y=30, anchor='w') self.yv.place(x=330, y=60, anchor='w') self.yl.place(x=390, y=60, anchor='w') self.note1.place(x=420, y=45, anchor='w') self.rb1.place(x=380, y=5, anchor='w') self.rb2.place(x=440, y=5, anchor='w') self.cls.place(x=305, y=5, anchor='w') self.a2.place(x=480, y=90, anchor='e') self.a5.place(x=400, y=90, anchor='e') #打开readme.txt文件查看帮助 def help(self): os.system('notepad.exe readme.txt') #程序功能无法使用时刷新,重新启动该脚本 def refresh(self): self.quit() os.system('python root.py') #运行程序,打开窗口 def run(self): self.rt.mainloop() #爬图前确认图片关键字是否存在 def start_cr(self): word = self.e2.get() if word != '': st = askyesno(title='确认开始', message='确定开始下载图片?这会有一段时间的卡顿,中途不要退出页面') if st: self.start_in() #图片关键字存在,开始爬图 else: self.s.config(state='normal') self.s.delete(1.0, 'end') self.s.insert('end', '请先输入图片关键字(如:周杰伦)') self.s.config(state='disabled') def close(self): cl = askyesno(title='确认关闭', message='确定要关闭吗?') if cl: self.quit() def quit(self): self.rt.destroy() def confirm_e(self): path = self.e1.get() if path == '': self.ala.config(text='请先选择图片保存目录!') elif os.path.exists(path) is False: self.ala.config(text='该路径不存在!') else: self.ala.config(text='') self.e1.config(state='disabled') self.e2.config(state='normal') self.b1.config(state='disabled') self.b2.config(state='disabled') self.b3.config(state='normal') self.a1.config(state='normal') def confirm_e1(self): path = self.e3.get() if path == '': self.ala.config(text='请先选择图片目录!') elif os.path.exists(path) is False: self.ala.config(text='该路径不存在!') else: self.ala.config(text='') self.b4.config(state='disabled') self.b5.config(state='disabled') self.e3.config(state='disabled') self.e4.config(state='normal') self.b6.config(state='normal') self.ad.config(state='normal') self.a3.config(state='normal') def confirm_e2(self): path = self.e4.get() if path == '': self.ala.config(text='请先选择图片保存目录!') elif os.path.exists(path) is False: self.ala.config(text='该路径不存在!') else: self.ala.config(text='') self.b6.config(state='disabled') self.ad.config(state='disabled') self.e4.config(state='disabled') self.a3.config(state='disabled') self.a4.config(state='normal') self.rb1.config(state='normal') self.rb2.config(state='normal') self.rb3.config(state='normal') self.rb4.config(state='normal') self.rb5.config(state='normal') self.xl.config(state='normal') self.yl.config(state='normal') self.a2.config(state='normal') self.a5.config(state='normal') def deconfirm_e(self): self.e1.config(state='normal') self.e2.config(state='disabled') self.b1.config(state='normal') self.b2.config(state='normal') self.b3.config(state='disabled') self.a1.config(state='disabled') self.a3.config(state='disabled') self.s.config(state='disabled') def deconfirm_e1(self): self.b4.config(state='normal') self.b5.config(state='normal') self.e3.config(state='normal') self.e4.config(state='disabled') self.b6.config(state='disabled') self.ad.config(state='disabled') self.a3.config(state='disabled') def deconfirm_e2(self): self.b6.config(state='normal') self.ad.config(state='normal') self.e4.config(state='normal') self.a3.config(state='normal') self.a4.config(state='disabled') self.b6.config(state='normal') self.ad.config(state='normal') self.e4.config(state='normal') self.a3.config(state='normal') self.a4.config(state='disabled') self.rb1.config(state='disabled') self.rb2.config(state='disabled') self.rb3.config(state='disabled') self.rb4.config(state='disabled') self.rb5.config(state='disabled') self.xl.config(state='disabled') self.yl.config(state='disabled') self.a2.config(state='disabled') self.a5.config(state='disabled') def reset(self): self.xlen.set(128) self.ylen.set(128) self.color.set(0) self.ty.set(0) self.a2.config(state='normal') #开始收集'存储地址'和'图片关键字'并开始爬图 def start_in(self): word = self.e2.get() self.a1.config(state='disabled') self.e2.config(state='disabled') self.s.config(state='normal') self.b1.config(state='disabled') self.b2.config(state='disabled') self.b3.config(state='disabled') path = self.e1.get() self.s.delete(1.0, 'end') ins = word.encode('utf-8') self.s.insert('end', '正在百度搜索:' + ins) self.get_images(word, path) #这是爬图的主程序 #格式错误反馈 def alarm(self): self.ala.config(text='输入格式有误!') #self.a.delete(0,'end') #读取网页url def readurl(self, url): page = urllib.urlopen(url) htm = page.read() return htm #下载网络图片 #imgurl:单张网络图片的url地址 #path:图片存储路径 #x:图片编号,同时也是图片名 #lastname:网络图片的后缀名 def downloadimg(self, imgurl, path, x, lastname): error_time = 0 while True: time.sleep(1) try: try: urllib.urlretrieve(imgurl, path + '/%s' % x + lastname) # 从地址上下载单张图片到指定存储位置上 #self.s.insert('insert', '\n第%s张图片下载成功' % x) except socket.timeout: # 防止超时卡死,重新下载 self.s.insert('insert', '\nReloading...') count = 1 # 卡死计数 while count <= 2: # 重新下载图片两次 try: urllib.urlretrieve(imgurl, path + '/%s' % x + lastname) time.sleep(0.001) self.s.insert('insert', '\n第%s张图片下载成功' % x) break except socket.timeout: err_info = 'Reloading for %d time' % count if count == 1 else 'Reloading for %d times' % count self.s.insert('insert', '\n' + err_info) count = count + 1 if count > 2: # 卡死次数过多 # 删除错误文件 os.remove(path + '/%s' % x + lastname) imgname = path + '/%s' % x + lastname size = os.path.getsize(imgname) / float(1024) # 获取图片大小 # size单位为kb if size < 20: # 删除小于20kb的图片 os.remove(path + '/%s' % x + lastname) self.s.insert('insert', '\n第%s张图片大小太小,跳过' % x) except: error_time += 1 if error_time == 100: print('your network is little bad') time.sleep(60) if error_time == 101: print('your network is broken') break continue break #获取图片地址列表 #jpgre:jpg图片地址的正则表达式形式 #pngre和jpegre同上 #htm:网页源代码 def get_imglist(self, jpgre, pngre, jpegre, htm): jpglist = re.findall(jpgre, htm) #在htm里寻找所有jpg图片的源代码,并做成一个列表 pnglist = re.findall(pngre, htm) jpeglist = re.findall(jpegre, htm) piclist = [jpglist, pnglist, jpeglist] return piclist #piclist是一个三元列表,每一个元素也是一个列表 #获得文件夹目录 def get_directory1(self): savepath = askdirectory() self.e1.delete(0, 'end') self.e1.insert('insert', savepath) def get_directory5(self): savepath = askdirectory() self.e3.delete(0, 'end') self.e3.insert('insert', savepath) def get_directory4(self): savepath = askdirectory() self.e4.delete(0, 'end') self.e4.insert('insert', savepath) #爬取图片主程序 #word:图片关键字 #path:图片存储路径 def get_images(self, word, path): var1 = word.encode('utf-8') #get()函数得到的字符串不是utf-8编码,需要转到utf-8 search = urllib.quote(var1) #用urllib的网页格式转码utf-8格式的图片关键字 pn = 0 # pn = 20*(页数+1) err_num = 0 #错误计数,连续十个网址下载出现错误时就终止爬图 x = 1 #图片编号 jpg = 'objURL":"(.+?.jpg)",' #百度图片的URL地址的正则表达式 jpgre = re.compile(jpg) #编译正则表达式,用于寻找网页源代码里的图片地址 jpeg = 'objURL":"(.+?.jpeg)",' jpegre = re.compile(jpeg) png = 'objURL":"(.+?.png)",' pngre = re.compile(png) self.s.insert('insert', '\n--------开始爬图--------') while True: url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + search + '&pn=' + str( pn) + '&gsm=3c&ct=&ic=0&lm=-1&width=0&height=0' try: self.s.insert('insert', '\n正在读取源代码...') htm = self.readurl(url) #从网页地址里读取网页源代码 piclist = self.get_imglist(jpgre, pngre, jpegre, htm) #在网页文件里寻找编译后的URL地址,并返回一个列表 namelist = ['.jpg', '.png', '.jpeg'] #后缀名列表,百度图片的后缀名一般只有三种:jpg,png,jpeg n = 0 m = 0 self.s.insert('insert', '\n--------------') self.s.insert('insert', '\n源代码读取完毕') self.s.insert('insert', '\n--------------') for list in piclist: #注意:piclist是一个三元列表,每一个元素也是一个列表 lastname = namelist[n] n = n + 1 for imgurl in list: #list存储着许多图片的URL地址,每个imgurl是单张图片的url地址 dlth = threading.Thread( target=self.downloadimg, args=( imgurl, path, x, lastname, )) #把下载单张图片交给子进程去完成,提供进程需要执行的目标函数和函数参数 dlth.setDaemon(True) #dlth这三行缺一不可 dlth.start() #开始执行进程 self.s.insert('insert', '\n第%s张图片下载成功' % x) x = x + 1 #开始下载下一张图片 err_num = 0 #一张网页的下载顺利完成,错误代码归零 except: self.s.insert('insert', '\n...结束本页内容下载 继续') #跳过该页面下载下一页 pn = pn + 20 #pn = 20*(页数+1) err_num = err_num + 1 if pn > 1960: #图片关键字只会存100页的图片,所以pn>1960时不可能查到图 self.s.insert('insert', '\n...图片全部下载完毕') break elif err_num > 10: self.s.insert('insert', '\n...搜索不到更多图片,下载完毕') break elif x >= 1024: self.s.insert('insert', '\n...图片下载已达到上限') break self.s.insert('insert', '\n--------加载下一页--------') #以下为图片预处理部分 def start_pi(self): st = askyesno(title='确认开始', message='确定开始批处理图片?这会有一段时间的卡顿,但是可以去存储的文件夹拿到处理好的图') if st: reload(sys) sys.setdefaultencoding('utf8') self.start_pic() def start_pic(self): xLen = self.xl.get() yLen = self.yl.get() if xLen.isdigit() is True and yLen.isdigit() is True: self.ala.config(text='') self.a2.config(state='disabled') self.s1.config(state='normal') self.s1.insert('end', '\nxLen:' + str(xLen)) self.s1.insert('end', '\nyLen:' + str(yLen)) picpath = self.e3.get() savepath = self.e4.get() self.s1.insert('end', '\npicpath:' + picpath) self.s1.insert('end', '\nsavepath:' + savepath) pictypelist = ['LA', 'RGB'] pictype = pictypelist[self.color.get()] self.s1.insert('end', '\npictype:' + pictype) lastnamelist = ['.jpg', '.png', '.jpeg'] lastname = lastnamelist[self.ty.get()] self.s1.insert('end', '\nlastname:' + lastname) self.pre_main(picpath, savepath, pictype, xLen, yLen, lastname) else: self.ala.config(text='长宽输入格式有误!') def getNameList(self, picpath): if os.path.exists(picpath) is False: self.ala.config(text='该路径不存在!') else: self.ala.config(text='') files = os.listdir(picpath) return files def picdeal(self, name, picpath, savepath, pictype, xLen, yLen, lastname): try: names = name.split('.')[0] img = Image.open(picpath + '/' + name).convert(pictype).resize( (int(xLen), int(yLen))) img.save(savepath + '/%s' % names + lastname) except socket.timeout: count = 1 while count <= 2: try: img.save(savepath + '/%s' % names + lastname) self.s1.insert('end', '\n重新保存图片%s' % name + '1次') except socket.timeout: img.save(savepath + '/%s' % names + lastname) self.s1.insert('end', '\n重新保存图片%s' % name + '%d次' % (count + 1)) count = count + 1 if count >= 2: os.remove(savepath + '/%s' % names + lastname) except: names = name.split('.')[0] os.remove(savepath + '/%s' % names + lastname) def pre_main(self, picpath, savepath, pictype, xLen, yLen, lastname): nameList = self.getNameList(picpath) self.s1.insert('end', '\n共有%d张图片需要处理' % len(nameList)) for name in nameList: self.s1.insert('end', '\n正在处理图片:' + name) prth = threading.Thread(target=self.picdeal, args=( name, picpath, savepath, pictype, xLen, yLen, lastname, )) prth.setDaemon(True) prth.start()
class ClientGUI(object): def __init__(self, windowTitle="Client GUI"): # create new instance of TK self.base_gui = pygui.Tk() # store the windowTitle in an object attribute self.base_window_title = windowTitle # Connection Details self.connection_host = '' self.connection_name = '' self.connection_port = 0 # Client Object self.client = None # [Connection GUI Initialization] ::start self.connection_gui_bootstrapped = False self.connection_config_frame = pygui.Frame(self.base_gui) self.host_to_use_field = pygui.Entry(self.connection_config_frame) self.port_to_use_field = pygui.Entry(self.connection_config_frame) self.name_field = pygui.Entry(self.connection_config_frame) self.connect_server_btn = pygui.Button(self.connection_config_frame, text="Connect", command=self.connect_to_server) # [Connection GUI Initialization] ::end # [Main GUI Initialization] ::start self.main_gui_bootstrapped = False self.chat_room_frame = pygui.Frame(self.base_gui) self.activity_log_area = ScrolledText(self.chat_room_frame, height=10, width=50) self.message_field = pygui.Entry(self.chat_room_frame) self.submit_msg_btn = pygui.Button(self.chat_room_frame, text="Send", command=self.send_msg) self.exit_chat_btn = pygui.Button(self.chat_room_frame, text="Leave Chat Room", command=lambda: self.switch_context('connection')) # [Connection GUI Initialization] ::end def bootstrap(self): if self.client is None: print "Client Object must be specified. Call the set_client() method and set the ClientGUI Object." sys.exit(1) self.connection_gui() # set window title self.base_gui.wm_title(self.base_window_title) # handle close button self.base_gui.protocol("WM_DELETE_WINDOW", self.destroy_gui) # Start the GUI self.base_gui.mainloop() def connection_gui(self): # [Config Section] :start # assemble the UI and the frame if the attribute does not exist if self.connection_gui_bootstrapped is False: # Add field for host/hostname to use pygui.Label(self.connection_config_frame, text="Host").grid(row=0, column=0) self.host_to_use_field.grid(row=0, column=1) # Add field for port to use pygui.Label(self.connection_config_frame, text="Port").grid(row=1, column=0) self.port_to_use_field.grid(row=1, column=1) # Add field for chat username/alias pygui.Label(self.connection_config_frame, text="Name").grid(row=2, column=0) self.name_field.grid(row=2, column=1) self.connect_server_btn.grid(row=3, column=1) self.connection_gui_bootstrapped = True self.connection_config_frame.pack(side=pygui.TOP, padx=10, pady=10) # [Config Section] :end def main_gui(self): # [Chat Room] ::start # assemble the UI and the frame if the attribute does not exist if self.main_gui_bootstrapped is False: self.activity_log_area.grid(row=0) self.activity_log_area.edit_modified(0) self.activity_log_area.config(highlightbackground="black") self.activity_log_area.bind('<<Modified>>', self.scroll_to_end) self.message_field.grid(row=1, column=0) self.message_field.config(width=30) self.message_field.bind("<Return>", self.send_msg) self.submit_msg_btn.grid(row=1, column=1) self.exit_chat_btn.grid(row=2) self.main_gui_bootstrapped = True # empty the chat logs self.activity_log_area.delete("1.0", pygui.END) # show the frame for chat room self.chat_room_frame.pack(side=pygui.TOP, padx=10, pady=10) # [Chat Room] ::end def destroy_gui(self): # disconnect from the server self.client.disconnect() # destroy the window self.base_gui.destroy() def switch_context(self, context): if context == 'main': # hide the connection frame/GUI from the window if hasattr(self, 'connection_config_frame'): self.connection_config_frame.pack_forget() self.main_gui() title = "%s connected on %s:%s - %s" % (strip_uid(self.connection_name), self.connection_host, str(self.connection_port), self.base_window_title) # change the window title to show the connection details self.base_gui.wm_title(title) else: # disconnect from the server self.client.disconnect() # hide the chat room frame/GUI from the window if hasattr(self, 'chat_room_frame'): self.chat_room_frame.pack_forget() self.connection_gui() # set window title self.base_gui.wm_title(self.base_window_title) def scroll_to_end(self, *_): # scroll to the end of text area self.activity_log_area.see(pygui.END) self.activity_log_area.edit_modified(0) def connect_to_server(self): hostval = self.host_to_use_field.get() portval = self.port_to_use_field.get() nameval = self.name_field.get() if hostval != '' and portval != '' and nameval != '': self.connection_host = str(hostval) self.connection_name = str(nameval) # check if the host supplied is a valid ip address if not is_ipv4(self.connection_host): msgBox.showinfo("Client GUI", "Invalid IP Address") return # check if the input for port number is a valid integer try: self.connection_port = int(portval) except ValueError: msgBox.showinfo("Client GUI", "Invalid Port Number") return # initiate client-server connection if self.client.connect(self.connection_host, self.connection_port, self.connection_name) is True: # swap UI components/widgets self.switch_context('main') # log any broadcast message and disconnect on lost connection self.client.start_communications(self.log, lambda: self.switch_context('connection')) else: msgBox.showinfo("Client GUI", "Cant connect to server. Please try again later.") else: msgBox.showinfo("Client GUI", "Please enter the host, and port to connect to as well as your chat name") def set_client(self, client): self.client = client def send_msg(self, *_): message = self.message_field.get() # only send messages which are not empty if message: # show the message on your side self.log('[' + strip_uid(self.connection_name) + '] ' + message) # send the message to the other side self.client.send_msg(str(message)) # delete the message self.message_field.delete(0, pygui.END) def log(self, message): self.activity_log_area.insert(pygui.END, message + "\n")
data_param3.grid(row=6, column=1) data_param3.config(state="normal") label_a2 = Label(master=raiz, text="TBD") label_a2.configure(background='powder blue') label_a2.grid(row=6, column=0) data_medidas = Entry(raiz) data_medidas.grid(row=7, column=1) data_medidas.config(state="normal") label_med = Label(master=raiz, text="Number of Readings") label_med.configure(background='powder blue') label_med.grid(row=7, column=0) botao3 = Button(raiz, text="Start Readings", command=lambda: inicia(1)) botao3.configure(font=("Arial", 10, "bold"), background='powder blue') botao3.grid(row=1, column=34, padx=5, pady=5, sticky='NSEW') conteudo = ScrolledText(raiz, width=35, height=15, padx=5, pady=5) conteudo.config(state="disabled") conteudo.grid(row=2, column=34, rowspan=8, padx=5, pady=5, sticky='NSEW') botao4 = Button(raiz, text="Get Graphic", command=grafico_e) botao4.configure(font=("Arial", 10, "bold"), background='powder blue') botao4.grid(row=25, column=34, padx=5, pady=5, sticky='NSEW') botao4.config(state="normal") raiz.protocol("WM_DELETE_WINDOW", callback) raiz.mainloop()
class SourceEditor: def __init__(self,central,name,bodyTopNode,specTopNode): self.dirty = False self.central = central self.name = name self.toplevel = Toplevel() self.toplevel.title(name) self.pw = Pmw.PanedWidget(self.toplevel, orient='vertical') specpane = self.pw.add("spec") bodypane = self.pw.add("body") self.specText = ScrolledText(specpane,font=("monaco",10),height=5,background=Colors.background) self.specText.pack(expand=YES,fill=BOTH) self.bodyText = ScrolledText(bodypane,font=("monaco",10),height=15,background=Colors.background) self.bodyText.pack(expand=YES,fill=BOTH) self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText} self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode} Widget.bind(self.bodyText,'<Any-KeyPress>',self.setDirty) Widget.bind(self.specText,'<Any-KeyPress>',self.setDirty) self.popup = Menu(self.toplevel,tearoff=0) self.popup.add_command(label="Dismiss", command=self.nothing) self.popup.add_command(label="Diagram", command=self.goDiagram) self.popup.add_command(label="Abort", command=self.abort) self.popup.add_command(label="Accept", command=self.accept) self.popup.add_command(label="Recolor", command=self.recolor) def popupMenu(event): self.popup.post(event.x_root,event.y_root) self.toplevel.bind('<Button-3>', popupMenu) self.pw.pack(expand=YES,fill=BOTH) self.toplevel.protocol("WM_DELETE_WINDOW",self.central.doQuit) self.refresh() def nothing(self): pass def setClean(self): if self.dirty: self.dirty = False self.toplevel.title(self.name) self.central.unlockGraphics(self.name) def setDirty(self,event): if event.keysym in ['Shift_L', 'Shift_R', 'Alt_L', 'Alt_R', 'Win_L', 'Win_R']: return if not self.dirty: self.dirty = True self.toplevel.title(self.name+"*") self.central.lockGraphics(self.name) def abort(self): if self.dirty: self.setClean() self.setSource() def getSource(self): return (self.specText.get("1.0",END), self.bodyText.get("1.0",END)) def accept(self): if self.dirty: self.bodyText.config(cursor="watch") self.specText.config(cursor="watch") self.bodyText.update() # so that the cursor will show self.specText.update() self.central.update(self.name, self.specText.get("1.0",END), self.bodyText.get("1.0",END),saveOutput=False) self.central.setChanged(self.name) self.setClean() self.bodyText.config(cursor="xterm") self.specText.config(cursor="xterm") def recolor(self): stext,btext = self.getSource() self.colorize(self.specText,stext) self.colorize(self.bodyText,btext) def show(self, specTopNode, bodyTopNode): self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText} self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode} self.setSource() def setSource(self): oldScroll,dummy = self.specText.yview() self.specText.delete('1.0',END) stext = self.textMap[self.specText].regen(forDisplay=True) self.specText.insert(END,stext) self.colorize(self.specText,stext) self.specText.yview("moveto", oldScroll) oldScroll,dummy = self.bodyText.yview() self.bodyText.delete('1.0',END) btext = self.textMap[self.bodyText].regen(forDisplay=True) self.bodyText.insert(END,btext) self.colorize(self.bodyText,btext) self.bodyText.yview("moveto", oldScroll) def colorize(self,textWidget,progText): def colorizeSub(color,wordList): textWidget.tag_remove(color,'1.0',END) textWidget.tag_configure(color,foreground=color) keywords = re.compile(r'\b(' + string.join(wordList,"|") + r')\b') iter = keywords.finditer(progText) for match in iter: start, stop = match.span() textWidget.tag_add(color,"1.0+%dc" % start, "1.0+%dc" % stop) textWidget.tag_remove('hilite','1.0',END) colorizeSub(Colors.keyword, Lexis.keywords) colorizeSub(Colors.reserved, Lexis.reservedWords) def refresh(self): self.setSource() def goDiagram(self): self.central.showDiagram(self.name) def showSource(self,node): self.makeTop() topNode = node.getTopNode() self.text = self.nodeMap[topNode] self.text.tag_remove('hilite','1.0',END) start, end = node.lineRange() startIdx = '%d.0' % int(start) endIdx = '%d.0' % (int(end)+1) self.text.tag_configure('hilite',background=Colors.locatecolor,foreground='black') self.text.see(startIdx) self.text.tag_add('hilite',startIdx,endIdx) def coolSource(self): self.text.tag_configure('hilite',background='white',foreground=Colors.locatecooledcolor) def makeTop(self): TkWorkaround.raiseWindow(self.toplevel) def rescueResource(self): return repr(self.toplevel.geometry()) def setGeom(self,geom): self.toplevel.geometry(geom) def showError(self, unitType, lineNo): text = {'m': self.bodyText, 'i': self.specText}[unitType] startIdx = '%s.0' % int(lineNo) endIdx = '%s.0' % (int(lineNo)+1) text.tag_remove('hilite','1.0',END) text.tag_configure('hilite',background=Colors.locatecolor,foreground='black') text.see(startIdx) text.tag_add('hilite',startIdx,endIdx) self.makeTop()
class GUI_hcheck: # do everything! def __init__(self): self.top = Tk() self.top.title('Health Check Tool') self.top.geometry('1400x800') #------- Label,Entry defination ----------# self.l1 = Label(self.top, text="IP:").grid(row=1, column=1, sticky="w") self.e1 = Entry(self.top) self.e1.grid(row=1, column=2,sticky="ew") self.l2 = Label(self.top, text="User:"******"w") self.e2 = Entry(self.top) self.e2.grid(row=2, column=2,sticky="ew") self.l3 = Label(self.top, text="Passwd:").grid(row=3, column=1, sticky="w") self.e3 = Entry(self.top) self.e3['show'] = '*' self.e3.grid(row=3, column=2,sticky="ew") self.l4 = Label(self.top, text="Command pool:").grid(row=4, column=1, sticky="e") self.l5 = Label(self.top, text="To be run command:").grid(row=4, column=5, sticky="e") self.e4 = Entry(self.top, width=30) self.e4.grid(row=16, column=0, columnspan=3, sticky="ew") #------- Checkbutton defination ----------# self.cb1State = IntVar() self.cb1 = Checkbutton(self.top, variable=self.cb1State, text = "Always Yes", command=self.callCheckbutton) self.cb1.grid(row=21, column=16) #------- Listbox defination ----------# self.cmdfm = Frame(self.top) self.cmdsb = Scrollbar(self.cmdfm) self.cmdsb_x = Scrollbar(self.cmdfm,orient = HORIZONTAL) self.cmdsb.pack(side=RIGHT, fill=Y) self.cmdsb_x.pack(side=BOTTOM, fill=X) self.cmdls = Listbox(self.cmdfm, selectmode=EXTENDED, height=25, width=40, xscrollcommand=self.cmdsb_x.set, yscrollcommand=self.cmdsb.set) self.cmdsb.config(command=self.cmdls.yview) self.cmdsb_x.config(command=self.cmdls.xview) self.cmdls.pack(side=LEFT, fill=BOTH) self.cmdfm.grid(row=5, rowspan=10, column=0,columnspan=4,sticky="ew") self.db_file = os.path.join(os.getcwd(),'%s' % constants.DB_NAME) flist = utility.load_file(self.db_file) if flist != None: log.debug ("db file found, start load command") for element in flist: element = element.strip('\n') if element == '' or element.startswith('#'): continue self.cmdls.insert(END, element) else: log.debug ("db file doesn't existed, initail cmd") for element in constants.CMD_LIST_COMM: self.cmdls.insert(END, element) self.dirfm = Frame(self.top) self.dirsb = Scrollbar(self.dirfm) self.dirsb_x = Scrollbar(self.dirfm,orient = HORIZONTAL) self.dirsb.pack(side=RIGHT, fill=Y) self.dirsb_x.pack(side=BOTTOM, fill=X) self.dirs = Listbox(self.dirfm, selectmode=EXTENDED, height=25, width=40, xscrollcommand=self.dirsb_x.set,yscrollcommand=self.dirsb.set) self.dirsb.config(command=self.dirs.yview) self.dirsb_x.config(command=self.dirs.xview) self.dirs.pack(side=LEFT, fill=BOTH) self.dirfm.grid(row=5, rowspan=10, column=5,columnspan=4,sticky="ew") #------- Buttion defination ----------# # add command button self.b1 = Button(self.top,text=">>",width=6,borderwidth=3,relief=RAISED, command=self.move_cmd) self.b1.grid(row=7, column=4) # del command button self.b2 = Button(self.top,text="<<",width=6,borderwidth=3,relief=RAISED, command=self.del_cmd) self.b2.grid(row=8, column=4) # move up command button self.b3 = Button(self.top,text="up",width=6,borderwidth=3,relief=RAISED, command=self.up_cmd) self.b3.grid(row=7, column=10) # move down command button self.b4 = Button(self.top,text="down",width=6,borderwidth=3,relief=RAISED, command=self.down_cmd) self.b4.grid(row=8, column=10) # start command button self.b5 = Button(self.top,text="Start",bg='red',width=10,borderwidth=3,relief=RAISED, command=self.start_process) self.b5.grid(row=2, column=11) # yes button self.b6 = Button(self.top,text="Yes",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_yes) self.b6.grid(row=21, column=13) # No button self.b7 = Button(self.top,text="No",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_no) self.b7.grid(row=21, column=14) # Skip button self.b8 = Button(self.top,text="Skip",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_skip) self.b8.grid(row=21, column=15) # Add button self.b9 = Button(self.top,text="add cmd",width=10,borderwidth=3,relief=RAISED, command=self.add_command) self.b9.grid(row=15, column=1) # Del button self.b10 = Button(self.top,text="del cmd",width=10,borderwidth=3,relief=RAISED, command=self.del_command) self.b10.grid(row=15, column=2) # Manual button self.manual = False self.b11 = Button(self.top,text="Manual model",width=10,borderwidth=3,relief=RAISED, command=self.manual_mode) self.b11.grid(row=2, column=12) #------- ScrolledText defination ----------# self.sfm = Frame(self.top) self.console = ScrolledText(self.sfm,height=45, width=86,bg='black',fg='green',insertbackground='green') self.console['font'] = ('lucida console','10') self.console.bind("<Return>", self.process_input) self.console.pack() self.sfm.grid(row=4, rowspan=15, column=11,columnspan=10,sticky="ew") self.redir = redirect(self.console) sys.stdout = self.redir sys.stderr = self.redir self.fconsole = logging.StreamHandler(sys.stdout) self.fconsole.setLevel(logging.INFO) logging.getLogger('').addHandler(self.fconsole) #------- Menu defination ----------# self.menubar = Menu() # file menu self.fmenu = Menu() #self.fmenu.add_command(label = 'New',command=self.new_win) self.fmenu.add_command(label = 'Import cmd',command=self.load_cmd) self.fmenu.add_command(label = 'Export cmd',command=self.export_cmd) self.menubar.add_cascade(label = 'File', menu = self.fmenu) # edit menu self.emenu = Menu() self.cmenu = Menu() self.cvar = StringVar() for item in ['white/black', 'black/white', 'green/black']: self.cmenu.add_radiobutton(label = item, variable=self.cvar, value=item, command=self.sel_color_style) self.emenu.add_cascade(label = 'console style', menu = self.cmenu) self.emenu.add_command(label = 'reset cmd pool',command=self.reset_cmd_pool) self.menubar.add_cascade(label = 'Edit', menu = self.emenu) self.top['menu'] = self.menubar def new_win(self): #GUI_hcheck() pass def sel_color_style(self): log.debug ("select console color style: %s " % self.cvar.get()) color = self.cvar.get() if color == 'white/black': self.console.config(bg='black',fg='white',insertbackground='white') elif color == 'black/white': self.console.config(bg='white',fg='black',insertbackground='black') elif color == 'green/black': self.console.config(bg='black',fg='green',insertbackground='green') def move_cmd(self): if self.cmdls.curselection() != (): for i in self.cmdls.curselection(): if utility.elemet_exists(self.dirs.get(0,END), self.cmdls.get(i)) == None: self.dirs.insert(END,self.cmdls.get(i)) log.debug ("move command %s" % self.cmdls.get(i)) else: tkMessageBox.showwarning('Message', 'Please select at lease one item') def load_cmd(self): file = tkFileDialog.askopenfilename() flist = utility.load_file(file) if flist != None: self.dirs.delete(0,END) for element in flist: element = element.strip('\n') if element == '' or element.startswith('#'): continue if utility.elemet_exists(self.dirs.get(0,END), element) == None: self.dirs.insert(END, element) else: tkMessageBox.showerror('Message', 'import failed') def export_cmd(self): file = tkFileDialog.askopenfilename() if utility.export_file(self.dirs.get(0,END), file) == True: tkMessageBox.showinfo('Message', 'export finish') else: tkMessageBox.showerror('Message', 'export failed') def del_cmd(self): if self.dirs.curselection() != (): for i in self.dirs.curselection(): self.dirs.delete(i) else: tkMessageBox.showwarning('Message', 'Please select at lease one item') def up_cmd(self): select = self.dirs.curselection() if (len(select)) >= 2: tkMessageBox.showwarning('Message', 'Only one select is supported') return log.debug ("move up select pos: %s" % str(select)) if select != () and select != (0,): element = self.dirs.get(select) self.dirs.delete(select) self.dirs.insert((select[0] - 1), element) self.dirs.select_set(select[0] - 1) def down_cmd(self): select = self.dirs.curselection() if (len(select)) >= 2: tkMessageBox.showwarning('Message', 'Only one select is supported') return log.debug ("move down select pos: %s" % str(select)) if select != () and select != (END,): element = self.dirs.get(select) self.dirs.delete(select) self.dirs.insert((select[0] + 1), element) self.dirs.select_set(select[0] + 1) def start_process(self): log.debug ("current thread total numbers: %d" % threading.activeCount()) response = tkMessageBox.askokcancel('Message', 'Will start healthcheck, please click OK to continue, or cancel') if response == False: return th = threading.Thread(target=self.start_cmd) th.setDaemon(True) th.start() def start_cmd(self): self.manual = False cmd = list(self.dirs.get(0,END)) if len(cmd) == 0: log.info ("To be run cmd numbers none, quit...") return log.debug ("fetch cmd list from GUI: %s" % cmd) (ip, port) = utility.getipinfo(self.e1.get()) log.debug ("get ip infor-> ip: %s, port:%s" % (ip,port)) if ip == False: log.error ("Given ip infor is wrong! The right ip address: xxx.xxx.xxx.xxx or IP:port ") return self.b5.config(state=DISABLED) self.b11.config(state=DISABLED) self.console.delete('1.0',END) try: self.wf = Workflow(cmd, ip, self.e2.get(), self.e3.get(), port) self.wf.start() except: pass self.b5.config(state=NORMAL) self.b11.config(state=NORMAL) def manual_mode(self): cmd = [] (ip, port) = utility.getipinfo(self.e1.get()) log.debug ("get ip infor-> ip: %s, port:%s" % (ip,port)) if ip == False: log.error ("Given ip infor is wrong! The right ip address: xxx.xxx.xxx.xxx or IP:port ") return self.wf_manual = Workflow(cmd, ip, self.e2.get(), self.e3.get(), port) if self.wf_manual.setup_ssh(self.wf_manual.hostip) == False: log.error ("\nssh setup error! please check ip/user/passwd and network is okay") del self.wf_manual return self.console.delete('1.0',END) self.console.insert(END, "Switch to manual mode...\n\ Please input command directly after \">>> \"\n\n") self.prompt = ">>> " self.insert_prompt() self.manual = True self.b5.config(state=DISABLED) self.b11.config(state=DISABLED) def set_confirm_yes(self): try: self.wf.set_confirm('Yes') except AttributeError: log.debug("wf doesn't existed") def set_confirm_no(self): try: self.wf.set_confirm('No') except AttributeError: log.debug("wf doesn't existed") def set_confirm_skip(self): try: self.wf.set_confirm('Skip') except AttributeError: log.debug("wf doesn't existed") def callCheckbutton(self): try: if self.cb1State.get() == 1: self.wf.set_automatic(5) else: self.wf.set_automatic(None) except AttributeError: log.debug("wf doesn't existed") self.cb1.deselect() tkMessageBox.showwarning('Message', 'please press start button first') def saveinfo(self): pass def add_command(self): item = self.e4.get() if item != '': if utility.elemet_exists(self.cmdls.get(0,END), item) == None: self.cmdls.insert(END,item) self.cmdls.see(END) log.debug ("add new command %s" % item) self.save_command() else: tkMessageBox.showwarning('Message', 'entry can not empty') def del_command(self): if self.cmdls.curselection() != (): for i in self.cmdls.curselection(): self.cmdls.delete(i) self.save_command() else: tkMessageBox.showwarning('Message', 'Please select at lease one item') def save_command(self): if utility.export_file(self.cmdls.get(0,END), self.db_file) != True: log.error ("save command pool failed") def reset_cmd_pool(self): log.debug ("start to reset command pool list") self.cmdls.delete(0,END) for element in constants.CMD_LIST_COMM: self.cmdls.insert(END, element) self.save_command() def insert_prompt(self): c = self.console.get("end-2c") if c != "\n": self.console.insert("end", "\n") self.console.insert("end", self.prompt, ("prompt",)) #self.text.insert("end", self.prompt) # this mark lets us find the end of the prompt, and thus # the beggining of the user input self.console.mark_set("end-of-prompt", "end-1c") self.console.mark_gravity("end-of-prompt", "left") def process_input(self,event): index = self.console.index("end-1c linestart") line = self.console.get(index,'end-1c') log.debug ("last line: %s" % line) if self.manual == True: self.console.insert("end", "\n") command = self.console.get("end-of-prompt", "end-1c") command = command.strip() if command != '': if command == 'bye' or command == 'exit': log.info ("quit from manual mode...") self.wf_manual.ssh.close() self.manual = False self.b5.config(state=NORMAL) self.b11.config(state=NORMAL) return elif command == 'help': log.info ("This is used for run command on target server by ssh, for example: >>> df -h, >>> svcs -xv") elif self.wf_manual.remote_cmd(command) == 1: log.error ("command %s execute failed" % command) self.insert_prompt() self.console.see("end") # this prevents the class binding from firing, since we # inserted the newline in this method return "break" else: if line == 'Yes' or line == 'y' or line == 'yes': self.set_confirm_yes() elif line == 'No' or line == 'n' or line == 'no': self.set_confirm_no() elif line == 'Skip' or line == 's' or line == 'skip': self.set_confirm_skip() else: pass
class App: def __init__(self, master): self.tweetProcessorObject = TweetProcessor() self.politicianObject = Politician() # tweet processor frame rowTweetProcessor = 0 tweetProcessorFrame = LabelFrame(master, text="Tweet Processor") tweetProcessorFrame.grid(row=rowTweetProcessor, column=0) ## add tweet lblAddTweet = Label(tweetProcessorFrame, text="Add Tweet (json): ", anchor='w', justify='left') self.txtAddTweet = Text(tweetProcessorFrame, height=10) lblAddTweet.grid(row=0, column=0) self.txtAddTweet.grid(row=1, column=0) btnAddTweet = Button(tweetProcessorFrame, text="Add", command=self.addTweet) btnAddTweet.grid(row=2, column=0) btnExportGephi = Button(tweetProcessorFrame, text="Export Gephi file (*.gexf)", command=self.exportGephi) btnExportGephi.grid(row=3, column=0) # politician frame rowPolitician = 1 politicianFrame = LabelFrame(master, text="Politician") politicianFrame.grid(row=rowPolitician, column=0) ## add politician lblAddPolitican = Label(politicianFrame, text="Add Politician (dbpedia URI): ", anchor='w', justify='left') self.entryAddPolitician = Entry(politicianFrame, width=40) lblAddPolitican.grid(row=0, column=0) self.entryAddPolitician.grid(row=0, column=1) btnAddPolitician = Button(politicianFrame, text="Add", command=self.addPolitician) btnAddPolitician.grid(row=0, column=2) ## list politicians btnListPoliticians = Button(politicianFrame, text="List", command=self.listPoliticians) btnListPoliticians.grid(row=1, column=0, columnspan=3) # output frame rowOutputFrame = 2 outputFrame = LabelFrame(master, text="Output") outputFrame.grid(row=rowOutputFrame, column=0, sticky=W + E + N + S) self.txtOutputFrame = ScrolledText(outputFrame, width=160) self.txtOutputFrame.pack(fill=BOTH, expand=1) self.txtOutputFrame.config(wrap=NONE) def addTweet(self): try: output = self.tweetProcessorObject.process( self.txtAddTweet.get(1.0, END)) if len(output) == 0: out = "Match politician <-> tweet not found" else: out = "" out += str(len(output)) + " sentiments added\n" out += "-------- DETAILS ------------\n" for [politician, sentiment] in output: out += "Politician: " + politician[ "familyName"] + " " + politician["givenName"] + "\n" out += sentiment.upper() + " sentiment\n" out += "-------------------------------\n" self.writeOutput(out) except Exception as eDetail: self.writeOutput(eDetail) raise def addPolitician(self): try: if self.politicianObject.add(self.entryAddPolitician.get()): self.writeOutput("Politician added") else: self.writeOutput("Internal error") except Exception as eDetail: self.writeOutput(eDetail) raise def exportGephi(self): e = Etl() from tkFileDialog import asksaveasfilename import tkMessageBox filename = asksaveasfilename() if e.exportGephi(filename): tkMessageBox.showinfo("Info", "File salvato con successo.") def listPoliticians(self): out = "" for politician in self.politicianObject.getRawList(): out += politician self.writeOutput(out) def writeOutput(self, text): #self.txtOutputFrame.config(state=NORMAL) self.txtOutputFrame.delete(1.0, END) self.txtOutputFrame.insert(END, text)
class Application: def __init__(self, parent): self.parent = parent self.frames() self.f_saved = True #Sampled data saved root.protocol("WM_DELETE_WINDOW", self.on_closing) def on_closing(self): if (self.f_saved==False): if tkMessageBox.askokcancel("Quit", "Sampled data not saved. Do you wanto to quit?"): root.destroy() else: root.destroy() def frames(self): frame1 = Tk.Frame(root, bd=5, relief='raised', borderwidth=1) frame2 = Tk.Frame(root, bd=5, relief='raised') note = ttk.Notebook(frame2) self.tab1 = ttk.Frame(note) self.tab2 = ttk.Frame(note) note.add(self.tab1, text = "Frquency") note.add(self.tab2, text = "Time") # Positioning frame1.pack(side='left', fill='both', padx=5, pady=5) frame2.pack(side='right', fill='both', expand='true') boton_open = Tk.Button(frame1, text ="Open file", command=self.open_file) boton_save = Tk.Button(frame1, text ="Save to file", command=self.save_file) boton_scan = Tk.Button(frame1, text="Scan serial ports", command=self.scan_ports) boton_read = Tk.Button(frame1, text="Read serial data", command=self.read_serial) label1 = Tk.Label(frame1, text="Select Serial Port:") self.sel_puerto = ttk.Combobox(frame1, textvariable='', state="readonly") portnames = scan_serial() self.sel_puerto['values'] = portnames if (portnames != []): self.sel_puerto.current(0) self.text_message = ScrolledText(frame1, height=10, width=20) self.window_var = Tk.IntVar() self.window_var.set(1) #Option rectangular window radio_button1 = Tk.Radiobutton(frame1, text="Rectangular Window", variable=self.window_var, value=1, command=self.win_sel) radio_button2 = Tk.Radiobutton(frame1, text="Hann Window", variable=self.window_var, value=2, command=self.win_sel) radio_button3 = Tk.Radiobutton(frame1, text="Flattop Window", variable=self.window_var, value=3, command=self.win_sel) # Grid boton_open.grid(row=1, column=0, padx=5, pady=5) boton_save.grid(row=2, column=0, padx=5, pady=5) boton_scan.grid(row=3, column=0, padx=5, pady=5) label1.grid(row=4, column=0, padx=5, pady=5) self.sel_puerto.grid(row=5, column=0, padx=5, pady=5) boton_read.grid(row=6, column=0, padx=5, pady=5) self.text_message.grid(row=7, column=0, padx=5, pady=5) radio_button1.grid(row=8, column=0, sticky="W") radio_button2.grid(row=9, column=0, sticky="W") radio_button3.grid(row=10, column=0, sticky="W") #note.grid(row = 0, column=0) note.pack(side='top', fill='both', padx=5, pady=5) #Figure 1 fig1 = Figure(figsize=(10,7)) fig1.suptitle('Sampled signal - Acceleration') ax_11 = fig1.add_subplot(3,1,1) ax_11.hold(False) ax_11.set_title("Channel X") ax_11.set_ylabel('g') ax_11.grid() #Shows grid. ax_12 = fig1.add_subplot(3,1,2) ax_12.hold(False) ax_12.set_title("Channel Y") #ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. ax_12 = fig1.add_subplot(3,1,3) ax_12.hold(False) ax_12.set_title("Channel Z") ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. #Figure 2 fig2 = Figure(figsize=(10,7)) fig2.suptitle('FFT spectrum') ax_21 = fig2.add_subplot(3,1,1) ax_21.hold(False) ax_21.set_title("Channel X") ax_21.set_ylabel('g') ax_21.set_xlim(xmax=max_freq) ax_21.grid() ax_22 = fig2.add_subplot(3,1,2) ax_22.hold(False) ax_22.set_title("Channel Y") #ax_22.set_xlabel('Hz') ax_22.set_xlim(xmax=max_freq) ax_22.set_ylabel('g') ax_22.grid() ax_23 = fig2.add_subplot(3,1,3) ax_23.hold(False) ax_23.set_title("Channel Z") ax_23.set_xlabel('Hz') #ax_23.set_xlim(xmax=max_freq) ax_23.set_xlim(xmax=max_freq_z) ax_23.set_ylabel('g') ax_23.grid() # Canvas self.canvas2 = FigureCanvasTkAgg(fig1, master=self.tab2) self.canvas2.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar2 = NavigationToolbar2TkAgg(self.canvas2, self.tab2) self.toolbar2.update() self.canvas2._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas1 = FigureCanvasTkAgg(fig2, master=self.tab1) self.canvas1.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar1 = NavigationToolbar2TkAgg(self.canvas1, self.tab1) self.toolbar1.update() self.canvas1._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def read_serial(self): puerto = self.sel_puerto.get() print(puerto) message_string = "Port: {0} \n".format(puerto) self.show_message(self.text_message, message_string) estado_serial = False try: serial_avr = serial.Serial(port=puerto, baudrate=500000, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0) time.sleep(2) # waiting the initialization... print("Initializing") message_string = "Initializing... \n" self.show_message(self.text_message, message_string) if (serial_avr.isOpen() == True): estado_serial = True else: estado_serial = False except (serial.SerialException, ValueError) as ex: #print "Can´t open serial port: " + str(ex) tkMessageBox.showerror( "Result", "Can't open serial port: " + str(ex)) if (estado_serial == True): global g_canal_1, g_canal_2, g_canal_3, datos_a_leer canal_1 = [] canal_2 = [] canal_3 = [] buffer = '' paquete = '' valores = [] serial_avr.flushInput() serial_avr.flushOutput() valores_decod = [] conta_datos_rx = 0; #Received samples counter. print("Sending INI") message_string = "Sending INI \n" self.show_message(self.text_message, message_string) serial_avr.write('INI') #Start data sampling command. #serial_avr.write(chr(0x22)) #CRC 'INI'. Not used. serial_avr.write(chr(0x7E)) #End of packet. while conta_datos_rx < datos_a_leer: if serial_avr.inWaiting(): lectura = serial_avr.read(serial_avr.inWaiting()) buffer = buffer + lectura valores = [] if len(buffer) > 15: i = buffer.find(chr(0x7E)) if i >= 0: paquete = buffer[:i] buffer = buffer[i+1:] #print("Paquete: %s" % (paquete)) valores=[ord(i) for i in paquete] paquete = '' x = 0 while x < len(valores): if valores[x] == 0x7D: valores_decod.append(valores[x+1] ^ 0x20) x = x + 1 else: valores_decod.append(valores[x]) x = x + 1 canal1 = (valores_decod[0] * 256) + valores_decod[1] canal2 = (valores_decod[2] * 256) + valores_decod[3] canal3 = (valores_decod[4] * 256) + valores_decod[5] canal_1.append(canal1) canal_2.append(canal2) canal_3.append(canal3) #print("Canal 1: %s Canal2: %s " % (canal1, canal2)) valores = [] valores_decod = [] conta_datos_rx += 1 ; #print("conta_datos_rx = %s" %conta_datos_rx) #time.sleep(0.001) #Sin esta línea, el programa consume 90% de recursos CPU #Cuando la velocidad del puerto serial es alta y se recibe una gran cantidad #de datos, time.sleep() impone un tiempo demasiado largo. print("Sending PAR") self.text_message.config(state=Tk.NORMAL) #Enable to modify self.text_message.insert(Tk.END, "Sending PAR \n") self.text_message.config(state=Tk.DISABLED) #Disable - Read only root.update_idletasks() #Needed to make message visible serial_avr.write('PAR') #Stop data sampling. serial_avr.write(chr(0x7E)) #End of packet. serial_avr.close() #Close serial port. print("Amount of samples channel 1: %s" %len(canal_1)) print("Amount of samples channel 2: %s" %len(canal_2)) print("Amount of samples channel 3: %s" %len(canal_3)) message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1)) message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2)) message_string += "Amount of samples channel 3: {0} \n".format(len(canal_3)) self.show_message(self.text_message, message_string) #Keep a copy of the original values g_canal_1 = canal_1[:] #Copy list by value not by reference g_canal_2 = canal_2[:] g_canal_3 = canal_3[:] self.f_saved = False #Sampled data not saved self.window_var.set(1) #Option rectangular window self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var=1) def show_message(self, text_message, message_string): """Shows messages on a scrollable textbox""" text_message.config(state=Tk.NORMAL) #Enable to modify text_message.insert(Tk.END, message_string) text_message.config(state=Tk.DISABLED) #Disable - Read only text_message.see("end") #Show the "end" of text root.update_idletasks() #Needed to make message visible def scan_ports(self): portnames = [] portnames = scan_serial() self.sel_puerto['values'] = portnames if (portnames != []): self.sel_puerto.current(0) def plot(self, tab1, tab2, canal_1, canal_2, canal_3, win_var=1): num_datos = len(canal_1) X = range(0, num_datos, 1) # Scale the signal in g's for indice in X: canal_1[indice] *= g_scale canal_2[indice] *= g_scale canal_3[indice] *= g_scale # Calculates medium value for each channel. vdc_canal_1 = 0 vdc_canal_2 = 0 vdc_canal_3 = 0 for indice in X: vdc_canal_1 += canal_1[indice] vdc_canal_2 += canal_2[indice] vdc_canal_3 += canal_3[indice] vdc_canal_1 = vdc_canal_1 / num_datos vdc_canal_2 = vdc_canal_2 / num_datos vdc_canal_3 = vdc_canal_3 / num_datos #print("Vdc Channel 1: {0}, Vdc Channel 2: {1}".format(vdc_canal_1, vdc_canal_2)) # Substract DC offset for indice in X: canal_1[indice] -= vdc_canal_1 canal_2[indice] -= vdc_canal_2 canal_3[indice] -= vdc_canal_3 #----------------- Plotting ---------- X1 = np.linspace(0, num_datos/5, num=num_datos) # X axis, 5000 sps, 1/5 ms. # Figure 1. Sampled signals. #Channel X ax_11, ax_12, ax_13 = self.canvas2.figure.get_axes() ax_11.clear() ax_11.plot(X1,canal_1) ax_11.set_title("Channel X") ax_11.set_ylabel('g') ax_11.grid() #Shows grid. #Channel Y ax_12.clear() ax_12.plot(X1,canal_2) ax_12.set_title("Channel Y") #ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. #Channel Z ax_13.clear() ax_13.plot(X1,canal_3) ax_13.set_title("Channel Z") ax_13.set_xlabel('ms') ax_13.set_ylabel('g') ax_13.grid() #Shows grid. # Figure 2. FFT from signals. #Channel X canal_fft = [] canal_fft = canal_1 N = len(canal_fft) # length of the signal #Window function if(win_var == 2): w = signal.hann(N, sym=False) #Hann (Hanning) window elif(win_var == 3): w = signal.flattop(N, sym=False) #Flattop window else: w = 1 #Rectangular window T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_21, ax_22, ax_23 = self.canvas1.figure.get_axes() ax_21.clear() ax_21.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_21.grid() ax_21.set_title("Channel X") ax_21.set_ylabel('g') ax_21.set_xlim(xmax=max_freq) #Channel Y canal_fft = [] canal_fft = canal_2 N = len(canal_fft) # length of the signal T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_22.clear() ax_22.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_22.grid() ax_22.set_title("Channel Y") #ax_22.set_xlabel('Hz') ax_22.set_xlim(xmax=max_freq) ax_22.set_ylabel('g') #Channel Z canal_fft = [] canal_fft = canal_3 N = len(canal_fft) # length of the signal T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_23.clear() ax_23.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_23.grid() ax_23.set_title("Channel Z") ax_23.set_xlabel('Hz') #ax_23.set_xlim(xmax=max_freq) ax_23.set_xlim(xmax=max_freq_z) ax_23.set_ylabel('g') self.canvas1.draw() self.canvas2.draw() def win_sel(self): """Window selection. Every time a window is selected, the FFT spectrum is calculated, applying the selected window function""" global g_canal_1, g_canal_2, g_canal_3 canal_1 = g_canal_1[:] #Copy list by value not by reference canal_2 = g_canal_2[:] canal_3 = g_canal_3[:] win_var = self.window_var.get() if(len(canal_1) != 0): #Apply only if data available self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var) def open_file(self): """Opens dialog to select a file, reads data from file and plots the data""" ftypes = [('Text files', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(root, filetypes = ftypes) fl = dlg.show() if fl != '': # Open file for reading arch = open(fl, "r") datos_arch = arch.read() # Searches for every channel, delimited by L1, L2 and L3 tags. canal_1 = extraer_int_tag(datos_arch, 'L1') canal_2 = extraer_int_tag(datos_arch, 'L2') canal_3 = extraer_int_tag(datos_arch, 'L3') print("Amount of samples in channel 1: %s" %len(canal_1)) print("Amount of samples on channel 2: %s" %len(canal_2)) print("Amount of samples on channel 3: %s" %len(canal_3)) message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1)) message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2)) message_string += "Amount of samples channel 3: {0} \n".format(len(canal_3)) self.show_message(self.text_message, message_string) global g_canal_1, g_canal_2, g_canal_3 #Keep a copy of the original values g_canal_1 = canal_1[:] #Copy list by value not by reference g_canal_2 = canal_2[:] g_canal_3 = canal_3[:] self.window_var.set(1) #Option rectangular window self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var=1) def save_file(self): ftypes = [('Text files', '*.txt'), ('All files', '*')] dlg = tkFileDialog.SaveAs(root, filetypes = ftypes) fl = dlg.show() if fl != '': global g_canal_1, g_canal_2, g_canal_2 if (len(g_canal_1) > 0): grabar(g_canal_1, g_canal_2, g_canal_3, fl) self.f_saved = True #Sampled data saved else: print("No samled data to save") message_string = "No samled data to save\n" self.show_message(self.text_message, message_string)
class ViewportCard(object): ''' Manages the graphical representation of a card in a Tkinter canvas. Creates and destroys items as necessary, facilitates editing, and so on and so forth. Members: * card: model.Card * viewport: GPViewport * gpfile: gpfile.GraphPaperFile, contains model.graph() * canvas: TKinter canvas we get drawn on * editing: bool, text is being edited * moving: bool, being dragged * moving_edgescroll_id: callback id to scroll periodically when hovering near edge of screen * resize_state: {} * resize_edgescroll_id: as moving_edgescroll_id * slot: calls callbacks whenever geometry changes * new_edge: if an edge is being dragged out from a handle, this is it. * card_after_new_edge: bool, if we should make a new card when edge is dropped. ''' def __init__(self, viewport, gpfile, card): self.card = card self.viewport = viewport self.gpfile = gpfile self.canvas = viewport.canvas self.draw() self.editing = False self.moving = False self.moving_edgescroll_id = None self.resize_state = None self.resize_edgescroll_id = None # slot triggered when geometry (pos/size) changes # fn args: (self, x, y, w, h) self.geom_slot = Slot() self.deletion_slot = Slot() self.new_edge = None def draw(self): self.frame_thickness = 5 self.window = ResizableCanvasFrame(self.canvas, self.card.x, self.card.y, self.card.w, self.card.h, min_width=MIN_CARD_SIZE, min_height=MIN_CARD_SIZE) self.text = ScrolledText(self.window, wrap=WORD) self.text.pack(expand=1, fill='both') # set up text for editing, dragging, deleting self.text.bind("<Button-1>", self.mousedown) self.text.bind("<Shift-Button-1>", self.shiftmousedown) self.text.bind("<Double-Button-1>", self.doubleclick) self.text.bind("<B1-Motion>", self.mousemove) self.text.bind("<ButtonRelease-1>", self.mouseup) self.text.bind("<FocusIn>", self.focusin) self.text.bind("<FocusOut>", self.focusout) self.text.bind("<Control-Delete>", self.ctrldelete) self.text.insert(END, self.card.text) # set up frame for resizing self.window.bind('<Configure>', self.configure) self.window.save_callback = self.save_card # draw edge handles self.edge_handles = None #self.redraw_edge_handles() def redraw_edge_handles(self): ''' Either creates or modifies the edge handles, little circles poking out the side of the card, based on the current position and width. self.edge_handles is a list of itemids of the circles in (top, right, bottom, left) order. ''' def create_circle(bbox): # create circle suitable for edge-handle use new = self.canvas.create_oval(bbox[0], bbox[1], bbox[2], bbox[3], fill='green', outline='') self.canvas.addtag_withtag('card_handle_tag', new) # for z-ordering self.canvas.tag_bind(new, '<Button-1>', self.handle_click) self.canvas.tag_bind(new, '<Shift-Button-1>', self.handle_shift_click) self.canvas.tag_bind(new, '<B1-Motion>', self.handle_mousemove) self.canvas.tag_bind(new, '<ButtonRelease-1>', self.handle_mouseup) return new x, y = self.window.canvas_coords() w, h = self.window.winfo_width(), self.window.winfo_height() # 2*radius should be < MIN_CARD_SIZE, and offset < radius radius = 30 offset = 19 # offset of center of circle from card edge left_coords = (x + offset, y + h / 2) right_coords = (x + w - offset, y + h / 2) top_coords = (x + w / 2, y + offset) bottom_coords = (x + w / 2, y + h - offset) all_coords = (top_coords, right_coords, bottom_coords, left_coords) bboxes = [(x - radius, y - radius, x + radius, y + radius) for x, y in all_coords] if self.edge_handles: # move the edge handles for i, box in enumerate(bboxes): #self.canvas.coords(handle, box[0], box[1], box[2], box[3]) self.canvas.delete(self.edge_handles[i]) self.edge_handles[i] = create_circle(box) #self.canvas.itemconfig(handle, bbox = box) else: # create new ones self.edge_handles = [create_circle(b) for b in bboxes] # have to do this every time, every time we recreate the edge handles self.viewport.fix_z_order() def get_text(self): "gets the text from the actual editor, which may not be saved yet" return self.text.get('0.0', END) def save_text(self): # get text from window text = self.get_text() if text != self.card.text: self.card.text = text self.gpfile.commit() def canvas_coords(self): return self.window.canvas_coords() def start_moving(self, event): # set up state for a drag self.moving = True self.foocoords = (event.x, event.y) self.set_moving_edgescroll_callback() def edge_scroll(self): # if any edges are too close to the edge, move and scroll the canvas canvas_coords = self.canvas_coords() relative_mouse_pos = self.foocoords canvas_mouse_coords = (canvas_coords[0] + relative_mouse_pos[0] + self.frame_thickness, canvas_coords[1] + relative_mouse_pos[1] + self.frame_thickness) scroll_x, scroll_y = self.viewport.edge_scroll(canvas_mouse_coords) # move the opposite direction the viewport scrolled scroll_x, scroll_y = -scroll_x, -scroll_y #print 'card.edgescroll x y', scroll_x, scroll_y, 'relative_mouse_pos', relative_mouse_pos self.window.move(scroll_x, scroll_y) self.viewport.reset_scroll_region() self.set_moving_edgescroll_callback() def set_moving_edgescroll_callback(self): self.moving_edgescroll_id = self.text.after(10, self.edge_scroll) def cancel_moving_edgescroll_callback(self): self.text.after_cancel(self.moving_edgescroll_id) self.moving_edgescroll_id = None def mousedown(self, event): self.window.lift() def doubleclick(self, event): self.start_moving(event) return 'break' def shiftmousedown(self, event): self.mousedown(event) self.start_moving(event) return "break" def mousemove(self, event): if self.moving: # coords are relative to card, not canvas if self.foocoords: delta = (event.x - self.foocoords[0], event.y - self.foocoords[1]) else: delta = (event.x, event.y) self.window.move(delta[0], delta[1]) self.geometry_callback() self.viewport.reset_scroll_region() return "break" def mouseup(self, event): if self.moving: self.moving = False new_coords = self.canvas_coords() self.card.x, self.card.y = new_coords[0], new_coords[1] self.gpfile.commit() self.cancel_moving_edgescroll_callback() self.geometry_callback() # next several functions are bound to the circular edge handles def handle_click(self, event): # create new edge self.new_edge = ViewportEdge(self.viewport, self.gpfile, None, self, None) self.new_edge.mousemove(event) # give it a real start pos def handle_shift_click(self, event): self.handle_click(event) self.new_edge.make_new_card = True def handle_mousemove(self, event): if self.new_edge: self.new_edge.mousemove(event) def handle_mouseup(self, event): if self.new_edge: self.new_edge.mouseup(event) self.new_edge = None def configure(self, event): self.redraw_edge_handles() def focusin(self, event): self.editing = True def focusout(self, event): self.editing = False self.save_text() def ctrldelete(self, event): title_sample = self.get_text().split('\n', 1)[0] if len(title_sample) > 20: title_sample = title_sample[:20] + '...' # delete the card if tkMessageBox.askokcancel( "Delete?", "Delete card \"%s\" and all its edges?" % title_sample): for handle in self.edge_handles: self.canvas.delete(handle) self.deletion_slot.signal() self.viewport.remove_card(self) self.card.delete() self.window.destroy() self.gpfile.commit() return "break" def save_card(self): # grab values from self.window, # and put them in the model.card self.card.x, self.card.y = self.window.canvas_coords() self.card.w, self.card.h = self.window.winfo_width( ), self.window.winfo_height() self.geometry_callback() # here so it gets called after resizing self.gpfile.commit() def add_geom_signal(self, fn): return self.geom_slot.add(fn) def remove_geom_signal(self, handle): self.geom_slot.remove(handle) def add_deletion_signal(self, fn): return self.deletion_slot.add(fn) def remove_deletion_signal(self, handle): self.deletion_slot.remove(handle) def geometry_callback(self): x, y = self.canvas_coords() w, h = self.window.winfo_width(), self.window.winfo_height() self.geom_slot.signal(self, x, y, w, h) def highlight(self): self.text.config(background='#ffffa2') def unhighlight(self): self.text.config(background='white')
class LogFrame: def __init__(self, root, options, main_logger): self.root = root self.options = options self.main_logger = main_logger self.frame = tk.Frame(self.root) self.frame.columnconfigure(0, weight=1) # first row doesn't expoands self.frame.rowconfigure(0, weight=0) # let the second row grow self.frame.rowconfigure(1, weight=1) self.log_commands_frame = tk.LabelFrame(self.frame, text="Controls", padx=5, pady=5) self.log_commands_frame.grid(row=0, column=0, sticky=tk.NSEW, padx=4, pady=5) self.log_messages_frame = tk.Frame(self.frame) self.log_messages_frame.grid(row=1, column=0, sticky=tk.NSEW) # let the SIP trace growing self.log_messages_frame.columnconfigure(0, weight=1) self.log_messages_frame.rowconfigure(0, weight=1) self.log_messages = ScrolledText(self.log_messages_frame) self.log_messages.grid(row=0, column=0, sticky=tk.NSEW) # Log Messages frame row = 0 self.log_messages_clear_button = tk.Button( self.log_commands_frame, text="Clear", command=self.clear_log_messages) self.log_messages_clear_button.grid(row=row, column=0, sticky=tk.N) self.log_messages_pause_button = tk.Button( self.log_commands_frame, text="Pause", command=self.pause_log_messages) self.log_messages_pause_button.grid(row=row, column=1, sticky=tk.N) row = row + 1 def get_frame(self): return self.frame def clear_log_messages(self): self.log_messages.config(state='normal') self.log_messages.delete(0.0, tk.END) self.log_messages.config(state='disabled') def pause_log_messages(self): if self.log_messages_alarm is not None: self.log_messages.after_cancel(self.log_messages_alarm) self.log_messages_pause_button.configure( text="Resume", command=self.start_log_messages) self.log_messages_alarm = None def start_log_messages(self): self.update_log_messages_widget() self.log_messages_pause_button.configure( text="Pause", command=self.pause_log_messages) def update_log_messages_widget(self): self.update_widget(self.log_messages, self.log_queue) self.log_messages_alarm = self.log_messages.after( 20, self.update_log_messages_widget) def update_widget(self, widget, queue): widget.config(state='normal') while not queue.empty(): line = queue.get() widget.insert(tk.END, line) widget.see(tk.END) # Scroll to the bottom widget.update_idletasks() widget.config(state='disabled')
endRoll.config(font='bold') startRoll.config(font='bold') LendRoll.config(font='bold') LstartRoll.config(font='bold') urlDigit.config(font='bold') startRoll.grid(row=5, column=1) endRoll.grid(row=5, column=3) LstartRoll.grid(row=7, column=1) LendRoll.grid(row=7, column=3) urlDigit.grid(row=4, column=2) exportPath.grid(row=18, column=2) listBox = ScrolledText(app, height=15, width=114, font=('Times New Roman', 9)) listBox.grid(row=10, column=2) listBox.config(state=DISABLED) gen = Button(app,command = getList, text = 'Get Student List', font = ('Times New Roman',16,'bold'), bg = 'navyblue', \ fg = 'white', activeforeground = 'white',activebackground = '#D1FFBD', relief = RAISED) gen.grid(row=15, column=2) genRank = Button(app,command = getRank, text = 'Generate Ranks', font = ('Times New Roman',16,'bold'), bg = 'white', \ fg = 'gray', activeforeground = 'gray', relief = RAISED, state = DISABLED) genRank.grid(row=16, column=2) genGrade = Button(app,command = getGrade, text = 'Generate Grades', font = ('Times New Roman',16,'bold'), bg = 'white', \ fg = 'gray', activeforeground = 'gray', relief = RAISED, state = DISABLED) genGrade.grid(row=17, column=2) editFile = Button(app,command = ModFile, text = 'Modify File', font = ('Times New Roman',14), bg = 'white', \
class facades_main(Tkinter.Tk): def __init__(self, parent): Tkinter.Tk.__init__(self, parent) self.parent = parent self.initialize() self.clock_tick() def update_val_from_entry(self): global G_RUN_STATUS global G_SHUTDOWN_DELAY global G_WAKEUP_AFTER global G_LOOP_NUMBER global G_LONGRUN_ACTION G_SHUTDOWN_DELAY = int(self.entry_second.get(), base=10) G_WAKEUP_AFTER = int(self.entry_wakeafter.get(), base=10) G_LOOP_NUMBER = int(self.entry_loop.get(), base=10) G_LONGRUN_ACTION = self.var_action.get() def reset_rtcdata(self): efiapi = WinApiEfiVariables() rtcdata = efiapi.read(UEFI_VAR_NAME, UEFI_VAR_GUID) data = RtcWakeData(*struct.unpack_from(RTC_WAKE_DATA_FORMAT, rtcdata)) #just reset to not wake up data2 = data._replace(Alarm_Wake=3,Alarm_Week=0, \ RtcWakeTime_Hour= 0, \ RtcWakeTime_Minute= 0, \ RtcWakeTime_Second= 0 ) rtcdata = data2.packstring() efiapi.write(UEFI_VAR_NAME, UEFI_VAR_GUID, rtcdata) def func_shutdown(self): global G_CURRENT_LOOPNUM G_CURRENT_LOOPNUM += 1 self.confighandle.set_config('run_status', 'True') self.confighandle.set_config('current_loop', str(G_CURRENT_LOOPNUM)) self.confighandle.update_file() if (G_LONGRUN_ACTION == 4): print "reboot" Hour = int(time.strftime("%H"), 10) Minute = int(time.strftime("%M"), 10) Second = int(time.strftime("%S"), 10) self.logger.info("reboot time: %d:%d:%d" %(Hour, Minute, Second)) os.system('shutdown /r /f /t 0') while(1): pass efiapi = WinApiEfiVariables() rtcdata = efiapi.read(UEFI_VAR_NAME, UEFI_VAR_GUID) data = RtcWakeData(*struct.unpack_from(RTC_WAKE_DATA_FORMAT, rtcdata)) (Hour, Minute, Second) = self.CalAlarmTimer() data2 = data._replace(Alarm_Wake=1,Alarm_Week=0, \ RtcWakeTime_Hour= Hour, \ RtcWakeTime_Minute= Minute, \ RtcWakeTime_Second= Second ) rtcdata = data2.packstring() efiapi.write(UEFI_VAR_NAME, UEFI_VAR_GUID, rtcdata) if (G_LONGRUN_ACTION == 3): print "shutdown" os.system('shutdown /s /f /t 0') if (G_LONGRUN_ACTION == 2): print "suspend" os.system('rundll32.exe PowrProf.dll,SetSuspendState') if (G_LONGRUN_ACTION == 1): print "sleep" os.system('rundll32.exe powrprof.dll,SetSuspendState 0,1,0') def CalAlarmTimer(self): Hour = int(time.strftime("%H"), 10) Minute = int(time.strftime("%M"), 10) Second = int(time.strftime("%S"), 10) print "current time:", Hour, Minute, Second print "wake after:", G_WAKEUP_AFTER self.logger.info("current time: %d:%d:%d" %(Hour, Minute, Second)) # total_secs = Hour*3600 + Minute*60 + Second total_secs += G_WAKEUP_AFTER total_secs += G_SHUTDOWN_DELAY # Hour = total_secs / 3600 Minute = (total_secs % 3600) / 60 Second = (total_secs % 3600) % 60 if Hour >= 24: Hour = 0 print "wake time: %d:%d:%d" %(Hour, Minute, Second) self.logger.info("wake time: %d:%d:%d" %(Hour, Minute, Second)) return (Hour,Minute,Second) def clock_tick(self): now = time.strftime("%H:%M:%S") self.label_ticker.configure(text=now) self.label_ticker.after(200, self.clock_tick) def clock_timeout(self): count = self.entry_second.get() #print count count = int(count, 10) print count if (G_RUN_STATUS): if (count > 0): self.count_second.set(count - 1) self._job = self.entry_second.after(1000, self.clock_timeout) if (count == 0): print "function to action!" self.func_shutdown() def initialize(self): global G_RUN_STATUS global G_SHUTDOWN_DELAY global G_WAKEUP_AFTER global G_LOOP_NUMBER global G_CURRENT_LOOPNUM global G_LONGRUN_ACTION self.geometry("400x450+300+100") self.minsize(350,250) self.grid() self._job = None self.confighandle = lrConfigParser(configfn) self.count_second = Tkinter.IntVar() self.str_action = Tkinter.StringVar() self.var_action = Tkinter.IntVar() self.loop_number = Tkinter.IntVar() self.current_loop = Tkinter.IntVar() self.wake_after = Tkinter.IntVar() self.str_start = Tkinter.StringVar() self.var_action.set(G_LONGRUN_ACTION ) self.count_second.set(G_SHUTDOWN_DELAY) self.loop_number.set(G_LOOP_NUMBER) self.current_loop.set(G_CURRENT_LOOPNUM) self.wake_after.set(G_WAKEUP_AFTER) if (G_LONGRUN_ACTION == 4): self.str_action.set("reboot ") if (G_LONGRUN_ACTION == 3): self.str_action.set("Shutdown") self.log_queue = Queue.Queue() self.label_blank = Tkinter.Label(self, text='') self.label_ticker = Tkinter.Label(self, text="test",anchor='e',font=('times', 20, 'bold'), bg='green') self.entry_second = Tkinter.Entry(self, text=self.count_second, font=('times', 20, 'bold'),width=5) self.label_str1 = Tkinter.Label(self, text='seconds to',font=('times', 20, 'bold')) self.label_str2 = Tkinter.Label(self, text='Loop',font=('times', 20, 'bold')) self.label_str3 = Tkinter.Label(self, text='seconds to',font=('times', 20, 'bold')) self.label_str4 = Tkinter.Label(self, text='wakeup', font=('times', 20, 'bold')) self.entry_wakeafter = Tkinter.Entry(self, text=self.wake_after, font=('times', 20, 'bold'),width=5) self.label_str_action = Tkinter.Label(self, textvariable=self.str_action, font=('times', 20, 'bold')) self.radiobtn_s3 = Tkinter.Radiobutton(self, text='S3',variable=self.var_action, value=1, command=self.radiobtn_callback, state='disabled') self.radiobtn_s4 = Tkinter.Radiobutton(self, text='S4',variable=self.var_action, value=2, command=self.radiobtn_callback, state='disabled') self.radiobtn_s5 = Tkinter.Radiobutton(self, text='S5',variable=self.var_action, value=3, command=self.radiobtn_callback) self.radiobtn_reboot = Tkinter.Radiobutton(self, text='reboot',variable=self.var_action, value=4, command=self.radiobtn_callback) self.entry_loop = Tkinter.Entry(self, text=self.loop_number, font=('times', 20, 'bold'),width=5) self.btn_start = Tkinter.Button(self, text="Start",bg="green",font=('times', 20, 'bold'), command=self.btn_start_callback) self.btn_edit = Tkinter.Button(self, text="Edit", font=('times', 20, 'bold'), state="disabled", command=self.btn_edit_callback) self.label_current_loop = Tkinter.Label(self, textvariable=self.current_loop, font=('times', 20, 'bold')) self.btn_clrlog = Tkinter.Button(self, text="Clear Log",font=('times', 15, 'bold'), command=self.btn_clearlog_callback) self.log_widget = ScrolledText(self, width = 50, heigh = 15) self.label_blank.grid(row=0,column=0,ipadx=20) self.label_ticker.grid(row=0,column=2,sticky='w') self.entry_second.grid(row=1,column=0) self.label_str1.grid(row=1,column=1,sticky='w') self.label_str_action.grid(row=1,column=2,sticky='w') self.entry_loop.grid(row=2,column=0) self.label_str2.grid(row=2, column=1,sticky='w') self.radiobtn_s3.grid(row=2,column=2,sticky='w') self.radiobtn_s4.grid(row=2,column=2,sticky='w', padx=40) self.radiobtn_s5.grid(row=2,column=2,sticky='w', padx=80) self.radiobtn_reboot.grid(row=2,column=2,sticky='w',padx=120) self.entry_wakeafter.grid(row=3, column=0) self.label_str3.grid(row=3, column=1) self.label_str4.grid(row=3, column=2,sticky='w') self.label_blank.grid(row=4,column=0) self.btn_start.grid(row=5, column=0) self.btn_edit.grid(row=5, column=1) self.btn_clrlog.grid(row=5,column=2,sticky='w') self.label_current_loop.grid(row=5, column=2,sticky='w',padx=120) self.log_widget.grid(row=6, column=0, columnspan=3, sticky='w') #init log queue self.logger = logging.getLogger(logfn) self.logger.setLevel(logging.INFO) logformat = logging.Formatter(LOG_FORMAT) hl = QueueLogger(queue=self.log_queue) hl.setFormatter(logformat) self.logger.addHandler(hl) self.start_logwidget() if G_CURRENT_LOOPNUM <= G_LOOP_NUMBER: if G_RUN_STATUS: print "auto run loop %d" %(G_CURRENT_LOOPNUM) self.logger.info("\ncurrent loop: %d" %(G_CURRENT_LOOPNUM)) self.btn_start_callback() else: print "loop pass!" self.current_loop.set(G_CURRENT_LOOPNUM-1) if G_RUN_STATUS: print "reset run status here" G_RUN_STATUS = False G_CURRENT_LOOPNUM -= 1 self.current_loop.set(str(G_CURRENT_LOOPNUM)) self.confighandle.set_config('current_loop', str(G_CURRENT_LOOPNUM)) self.confighandle.update_file() self.reset_rtcdata() def radiobtn_callback(self): global G_LONGRUN_ACTION seltmp = self.var_action.get() G_LONGRUN_ACTION = seltmp if (seltmp == 4): self.str_action.set("reboot") if (seltmp == 3): self.str_action.set("Shutdown") if (seltmp == 2): self.str_action.set("Suspend ") if (seltmp == 1): self.str_action.set("Sleep ") def btn_clearlog_callback(self): global G_CURRENT_LOOPNUM self.log_widget.config(state='normal') self.log_widget.delete(0.0, Tkinter.END) self.log_widget.config(state='disabled') if os.path.isfile(logfn): with open(logfn, 'w'): pass #reset current loop to zero if G_CURRENT_LOOPNUM != 0: G_CURRENT_LOOPNUM = 0 self.confighandle.set_config('current_loop', str(G_CURRENT_LOOPNUM)) self.confighandle.update_file() self.current_loop.set(G_CURRENT_LOOPNUM) def btn_start_callback(self): global G_RUN_STATUS global G_EDITABLE if G_EDITABLE: G_EDITABLE = False print "set get from entry" self.update_val_from_entry() self.confighandle.set_config('shutdown_delay', str(G_SHUTDOWN_DELAY)) self.confighandle.set_config('loop_number', str(G_LOOP_NUMBER)) self.confighandle.set_config('wake_after', str(G_WAKEUP_AFTER)) self.confighandle.set_config('longrun_action', str(G_LONGRUN_ACTION)) self.confighandle.update_file() self.btn_start.config(text='Stop ', bg = "red", command=self.btn_stop_callback) self.entry_second.config(state='disabled') self.entry_loop.config(state='disabled') self.btn_edit.config(state='disabled') self.entry_wakeafter.config(state='disabled') G_EDITABLE = False if not G_RUN_STATUS: G_RUN_STATUS = True self.clock_timeout() def btn_stop_callback(self): global G_RUN_STATUS G_RUN_STATUS = False self.btn_start.config(text="Start", bg = "green", command=self.btn_start_callback) self.btn_edit.config(state='normal') self.confighandle.set_config('run_status', str(G_RUN_STATUS)) self.confighandle.update_file() self.reset_rtcdata() def btn_edit_callback(self): global G_EDITABLE print "edit callback, to enable change variables" self.btn_edit.config(text="Apply", command=self.btn_apply_callback) self.entry_second.config(state='normal') self.entry_loop.config(state='normal') self.entry_wakeafter.config(state='normal') G_EDITABLE = True def btn_apply_callback(self): global G_EDITABLE print "apply callback, save changes to cfg file after edit" self.btn_edit.config(text="Edit", command=self.btn_edit_callback) self.entry_second.config(state='disabled') self.entry_loop.config(state='disabled') self.entry_wakeafter.config(state='disabled') G_EDITABLE = False self.update_val_from_entry() ##update into cfg file self.confighandle.set_config('shutdown_delay', str(G_SHUTDOWN_DELAY)) self.confighandle.set_config('loop_number', str(G_LOOP_NUMBER)) self.confighandle.set_config('wake_after', str(G_WAKEUP_AFTER)) self.confighandle.set_config('longrun_action', str(G_LONGRUN_ACTION)) self.confighandle.update_file() def start_logwidget(self): if os.path.isfile(logfn): self.log_widget.config(state='normal') print "read log file into log widget" with open(logfn) as fin: for line in fin: self.log_widget.insert(Tkinter.END, line) self.log_widget.see(Tkinter.END) self.log_widget.update_idletasks() self.log_widget.config(state='disabled') self.update_logwidget(self.log_widget, self.log_queue) def update_logwidget(self, widget, queue): widget.config(state='normal') while not queue.empty(): line = queue.get() widget.insert(Tkinter.END, line) widget.see(Tkinter.END) widget.update_idletasks() widget.config(state='disabled') self.logger_alarm = widget.after(10, self.update_logwidget, widget, queue)
class Application: def __init__(self, parent): self.parent = parent self.frames() self.f_saved = True #Sampled data saved root.protocol("WM_DELETE_WINDOW", self.on_closing) def on_closing(self): if (self.f_saved==False): if tkMessageBox.askokcancel("Quit", "Sampled data not saved. Do you wanto to quit?"): root.destroy() else: root.destroy() def frames(self): frame1 = Tk.Frame(root, bd=5, relief='raised', borderwidth=1) frame2 = Tk.Frame(root, bd=5, relief='raised') note = ttk.Notebook(frame2) self.tab1 = ttk.Frame(note) self.tab2 = ttk.Frame(note) note.add(self.tab1, text = "Frquency") note.add(self.tab2, text = "Time") # Positioning frame1.pack(side='left', fill='both', padx=5, pady=5) frame2.pack(side='right', fill='both', expand='true') boton_open = Tk.Button(frame1, text ="Open file", command=self.open_file) boton_save = Tk.Button(frame1, text ="Save to file", command=self.save_file) boton_scan = Tk.Button(frame1, text="Scan serial ports", command=self.scan_ports) boton_read = Tk.Button(frame1, text="Read serial data", command=self.read_serial) label1 = Tk.Label(frame1, text="Select Serial Port:") self.sel_puerto = ttk.Combobox(frame1, textvariable='', state="readonly") portnames = scan_serial() self.sel_puerto['values'] = portnames if (portnames != []): self.sel_puerto.current(0) self.text_message = ScrolledText(frame1, height=10, width=20) self.window_var = Tk.IntVar() self.window_var.set(1) #Option rectangular window radio_button1 = Tk.Radiobutton(frame1, text="Rectangular Window", variable=self.window_var, value=1, command=self.win_sel) radio_button2 = Tk.Radiobutton(frame1, text="Hann Window", variable=self.window_var, value=2, command=self.win_sel) radio_button3 = Tk.Radiobutton(frame1, text="Flattop Window", variable=self.window_var, value=3, command=self.win_sel) # Grid boton_open.grid(row=1, column=0, padx=5, pady=5) boton_save.grid(row=2, column=0, padx=5, pady=5) boton_scan.grid(row=3, column=0, padx=5, pady=5) label1.grid(row=4, column=0, padx=5, pady=5) self.sel_puerto.grid(row=5, column=0, padx=5, pady=5) boton_read.grid(row=6, column=0, padx=5, pady=5) self.text_message.grid(row=7, column=0, padx=5, pady=5) radio_button1.grid(row=8, column=0, sticky="W") radio_button2.grid(row=9, column=0, sticky="W") radio_button3.grid(row=10, column=0, sticky="W") #note.grid(row = 0, column=0) note.pack(side='top', fill='both', padx=5, pady=5) #Figure 1 fig1 = Figure(figsize=(10,7)) fig1.suptitle('Sampled signal - Acceleration') ax_11 = fig1.add_subplot(2,1,1) ax_11.hold(False) ax_11.set_title("Channel X") ax_11.set_ylabel('g') ax_11.grid() #Shows grid. ax_12 = fig1.add_subplot(2,1,2) ax_12.hold(False) ax_12.set_title("Channel Y") ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. #Figure 2 fig2 = Figure(figsize=(10,7)) fig2.suptitle('FFT spectrum') ax_21 = fig2.add_subplot(2,1,1) ax_21.hold(False) ax_21.set_title("Channel X") ax_21.set_ylabel('g') ax_21.set_xlim(xmax=max_freq) ax_21.grid() ax_22 = fig2.add_subplot(2,1,2) ax_22.hold(False) ax_22.set_title("Channel Y") ax_22.set_xlabel('Hz') ax_22.set_xlim(xmax=max_freq) ax_22.set_ylabel('g') ax_22.grid() # Canvas self.canvas2 = FigureCanvasTkAgg(fig1, master=self.tab2) self.canvas2.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar2 = NavigationToolbar2TkAgg(self.canvas2, self.tab2) self.toolbar2.update() self.canvas2._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas1 = FigureCanvasTkAgg(fig2, master=self.tab1) self.canvas1.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.toolbar1 = NavigationToolbar2TkAgg(self.canvas1, self.tab1) self.toolbar1.update() self.canvas1._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def read_serial(self): puerto = self.sel_puerto.get() print(puerto) message_string = "Port: {0} \n".format(puerto) self.show_message(self.text_message, message_string) estado_serial = False try: serial_avr = serial.Serial(port=puerto, baudrate=500000, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0) time.sleep(2) # waiting the initialization... print("Initializing") message_string = "Initializing... \n" self.show_message(self.text_message, message_string) if (serial_avr.isOpen() == True): estado_serial = True else: estado_serial = False except (serial.SerialException, ValueError) as ex: #print "Can´t open serial port: " + str(ex) tkMessageBox.showerror( "Result", "Can't open serial port: " + str(ex)) if (estado_serial == True): global g_canal_1, g_canal_2, datos_a_leer canal_1 = [] canal_2 = [] buffer = '' paquete = '' valores = [] serial_avr.flushInput() serial_avr.flushOutput() valores_decod = [] conta_datos_rx = 0; #Received samples counter. print("Sending INI") message_string = "Sending INI \n" self.show_message(self.text_message, message_string) serial_avr.write('INI') #Start data sampling command. #serial_avr.write(chr(0x22)) #CRC 'INI'. Not used. serial_avr.write(chr(0x7E)) #End of packet. while conta_datos_rx < datos_a_leer: if serial_avr.inWaiting(): lectura = serial_avr.read(serial_avr.inWaiting()) buffer = buffer + lectura valores = [] if len(buffer) > 10: i = buffer.find(chr(0x7E)) if i >= 0: paquete = buffer[:i] buffer = buffer[i+1:] #print("Paquete: %s" % (paquete)) valores=[ord(i) for i in paquete] paquete = '' x = 0 while x < len(valores): if valores[x] == 0x7D: valores_decod.append(valores[x+1] ^ 0x20) x = x + 1 else: valores_decod.append(valores[x]) x = x + 1 canal1 = (valores_decod[0] * 256) + valores_decod[1] canal2 = (valores_decod[2] * 256) + valores_decod[3] canal_1.append(canal1) canal_2.append(canal2) #print("Canal 1: %s Canal2: %s " % (canal1, canal2)) valores = [] valores_decod = [] conta_datos_rx += 1 ; #print("conta_datos_rx = %s" %conta_datos_rx) #time.sleep(0.001) #Sin esta línea, el programa consume 90% de recursos CPU #Cuando la velocidad del puerto serial es alta y se recibe una gran cantidad #de datos, time.sleep() impone un tiempo demasiado largo. print("Sending PAR") self.text_message.config(state=Tk.NORMAL) #Enable to modify self.text_message.insert(Tk.END, "Sending PAR \n") self.text_message.config(state=Tk.DISABLED) #Disable - Read only root.update_idletasks() #Needed to make message visible serial_avr.write('PAR') #Stop data sampling. serial_avr.write(chr(0x7E)) #End of packet. serial_avr.close() #Close serial port. print("Amount of samples channel 1: %s" %len(canal_1)) print("Amount of samples channel 2: %s" %len(canal_2)) message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1)) message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2)) self.show_message(self.text_message, message_string) #Keep a copy of the original values g_canal_1 = canal_1[:] #Copy list by value not by reference g_canal_2 = canal_2[:] self.f_saved = False #Sampled data not saved self.window_var.set(1) #Option rectangular window self.plot(self.tab1, self.tab2, canal_1, canal_2, win_var=1) def show_message(self, text_message, message_string): """Shows messages on a scrollable textbox""" text_message.config(state=Tk.NORMAL) #Enable to modify text_message.insert(Tk.END, message_string) text_message.config(state=Tk.DISABLED) #Disable - Read only text_message.see("end") #Show the "end" of text root.update_idletasks() #Needed to make message visible def scan_ports(self): portnames = [] portnames = scan_serial() self.sel_puerto['values'] = portnames if (portnames != []): self.sel_puerto.current(0) def plot(self, tab1, tab2, canal_1, canal_2, win_var=1): num_datos = len(canal_1) X = range(0, num_datos, 1) # Scale the signal in g's for indice in X: canal_1[indice] *= g_scale canal_2[indice] *= g_scale # Calculates medium value for each channel. vdc_canal_1 = 0 vdc_canal_2 = 0 for indice in X: vdc_canal_1 += canal_1[indice] vdc_canal_2 += canal_2[indice] vdc_canal_1 = vdc_canal_1 / num_datos vdc_canal_2 = vdc_canal_2 / num_datos #print("Vdc Channel 1: {0}, Vdc Channel 2: {1}".format(vdc_canal_1, vdc_canal_2)) # Substract DC offset for indice in X: canal_1[indice] -= vdc_canal_1 canal_2[indice] -= vdc_canal_2 #----------------- Plotting ---------- X1 = np.linspace(0, num_datos/5, num=num_datos) # X axis, 5000 sps, 1/5 ms. # Figure 1. Sampled signals. #Channel X ax_11, ax_12 = self.canvas2.figure.get_axes() ax_11.clear() ax_11.plot(X1,canal_1) ax_11.set_title("Channel X") ax_11.set_ylabel('g') ax_11.grid() #Shows grid. #Channel Y ax_12.clear() ax_12.plot(X1,canal_2) ax_12.set_title("Channel Y") ax_12.set_xlabel('ms') ax_12.set_ylabel('g') ax_12.grid() #Shows grid. # Figure 2. FFT from signals. #Channel X canal_fft = [] canal_fft = canal_1 N = len(canal_fft) # length of the signal #Window function if(win_var == 2): w = signal.hann(N, sym=False) #Hann (Hanning) window elif(win_var == 3): w = signal.flattop(N, sym=False) #Flattop window else: w = 1 #Rectangular window T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_21, ax_22 = self.canvas1.figure.get_axes() ax_21.clear() ax_21.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_21.grid() ax_21.set_title("Channel X") ax_21.set_ylabel('g') ax_21.set_xlim(xmax=max_freq) #Channel Y canal_fft = [] canal_fft = canal_2 N = len(canal_fft) # length of the signal T = 1.0 / sample_rate y = canal_fft yf = fftpack.fft(y*w) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) ax_22.clear() ax_22.plot(xf, 2.0/N * np.abs(yf[:N/2])) ax_22.grid() ax_22.set_title("Channel Y") ax_22.set_xlabel('Hz') ax_22.set_xlim(xmax=max_freq) ax_22.set_ylabel('g') self.canvas1.draw() self.canvas2.draw() def win_sel(self): """Window selection. Every time a window is selected, the FFT spectrum is calculated, applying the selected window function""" global g_canal_1, g_canal_2 canal_1 = g_canal_1[:] #Copy list by value not by reference canal_2 = g_canal_2[:] win_var = self.window_var.get() if(len(canal_1) != 0): #Apply only if data available self.plot(self.tab1, self.tab2, canal_1, canal_2, win_var) def open_file(self): """Opens dialog to select a file, reads data from file and plots the data""" ftypes = [('Text files', '*.txt'), ('All files', '*')] dlg = tkFileDialog.Open(root, filetypes = ftypes) fl = dlg.show() if fl != '': # Open file for reading arch = open(fl, "r") datos_arch = arch.read() # Searches for every channel, delimited by L1 and L2 tags. canal_1 = extraer_int_tag(datos_arch, 'L1') canal_2 = extraer_int_tag(datos_arch, 'L2') print("Amount of samples in channel 1: %s" %len(canal_1)) print("Amount of samples on channel 2: %s" %len(canal_2)) message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1)) message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2)) self.show_message(self.text_message, message_string) global g_canal_1, g_canal_2 #Keep a copy of the original values g_canal_1 = canal_1[:] #Copy list by value not by reference g_canal_2 = canal_2[:] self.window_var.set(1) #Option rectangular window self.plot(self.tab1, self.tab2, canal_1, canal_2, win_var=1) def save_file(self): ftypes = [('Text files', '*.txt'), ('All files', '*')] dlg = tkFileDialog.SaveAs(root, filetypes = ftypes) fl = dlg.show() if fl != '': global g_canal_1, g_canal_2 if (len(g_canal_1) > 0): grabar(g_canal_1, g_canal_2, fl) self.f_saved = True #Sampled data saved else: print("No samled data to save") message_string = "No samled data to save\n" self.show_message(self.text_message, message_string)
class app(): def __init__(self): self.root = Tk() self.root.title("WebScan") self.root.resizable(False, False) self.rr = IntVar() #self.root.geometry("1000x800") self.creat_weaget() ##varible to paues the scan## self.aa = IntVar() self.aa = False self.tt = StringVar self.va = StringVar ###left frame### self.left = Frame(self.root) self.left.grid(row=0, column=0, sticky=W) self.creat_left_weget() ###right frame## self.right = Frame(self.root) self.right.grid(row=0, column=1, sticky=E) self.creat_right_weget() ##progressbar text## self.style = ttk.Style(self.root) self.style.layout('text.Horizontal.TProgressbar', [('Horizontal.Progressbar.trough', { 'children': [('Horizontal.Progressbar.pbar', { 'side': 'left', 'sticky': 'ns' })], 'sticky': 'nswe' }), ('Horizontal.Progressbar.label', { 'sticky': '' })]) self.style.configure('text.Horizontal.TProgressbar', text='') def creat_weaget(self): ##top menu## self.menu_bar = Menu(self.root) self.root.config(menu=self.menu_bar) file_menu = Menu(self.menu_bar, tearoff=0) file_menu.add_command(label="About", command=self.he) self.menu_bar.add_cascade(label="Help", menu=file_menu) conf_menu = Menu(self.menu_bar, tearoff=0) conf_menu.add_command(label="User Agent Spoofing", command=self.con) self.menu_bar.add_cascade(label="Setting", menu=conf_menu) pass def creat_left_weget(self): ###label## label = Label(self.left, text="Entre the target Address") label.grid(row=0, column=0, pady=10, sticky=N) ##entry## self.entry = Entry(self.left) self.entry.grid(row=1, column=0, padx=10, pady=5, sticky=W + E) self.entry.focus() ##radio box## self.r = IntVar() ba_1 = Radiobutton(self.left, variable=self.r, value=1, text="Scan ") ba_1.grid(row=2, column=0, sticky=W) tt.create_ToolTip(ba_1, 'Only Scant the target Site') ba_2 = Radiobutton(self.left, variable=self.r, value=2, text="Spider") ba_2.grid(row=2, column=0, sticky=E) tt.create_ToolTip(ba_2, 'Spider the target site') ##submit batton## self.submit = Button(self.left, text="Start Scan", command=self.th) self.submit.grid(row=3, column=0, padx=10, pady=5, sticky=W) ##paus button## self.stop = Button(self.left, text="Pause Scan", command=self.st) self.stop.grid(row=4, column=0, padx=10, pady=5, sticky=W + E) self.stop.config(state='disabled') ##exit button## self.exit = Button(self.left, text="Exit", command=self.exe) self.exit.grid(row=3, column=0, padx=10, pady=5, sticky=E) ##progress bar## self.progre = ttk.Progressbar(self.left, style='text.Horizontal.TProgressbar', length=200, mode='determinate') self.progre.grid(row=5, column=0, padx=10) self.progre["maximum"] = 100 self.progre["value"] = 0 ##scrollbar## self.scroll = Scrollbar(self.left) self.scroll.grid(row=6, column=0, rowspan=5, sticky=N + E + S) xscrollbar = Scrollbar(self.left, orient=HORIZONTAL) xscrollbar.grid(row=13, column=0, sticky=E + W) ###listbox## self.list = Listbox(self.left, width=10, height=20, yscrollcommand=self.scroll.set, xscrollcommand=xscrollbar.set) self.list.grid(row=6, column=0, sticky=W + E + N + S, columnspan=1, rowspan=5, pady=5, padx=10) xscrollbar.config(command=self.list.xview) pass def creat_right_weget(self): ##textpt## self.script = Button(self.right, text="Scrip", command=self.script) self.script.grid(row=1, column=1, pady=5, sticky=W + E) tt.create_ToolTip(self.script, 'Search for scripts in Seleted Site') self.script.config(state='disabled') ##comments## self.comments = Button(self.right, text="Comments", command=self.comment) self.comments.grid(row=1, column=2, pady=5, sticky=W + E) self.comments.config(state='disabled') tt.create_ToolTip(self.comments, 'Search for Comments in Seleted Site') ##Vulnerabilites## self.vul = Button(self.right, text="Vulnerabilites", command=self.vul_2) self.vul.grid(row=1, column=3, pady=5, sticky=W + E) self.vul.config(state='disabled') tt.create_ToolTip(self.vul, 'Scan passively for Vulnerabilites in Seleted Site') ##response header## self.response = Button(self.right, text="Response", command=self.head_2) self.response.grid(row=1, column=4, pady=5, sticky=W + E) self.response.config(state='disabled') tt.create_ToolTip(self.response, 'Print Response header for Seleted Site') ##request header## self.request = Button(self.right, text="Request", command=self.req_2) self.request.grid(row=1, column=5, pady=5, sticky=W + E) self.request.config(state='disabled') tt.create_ToolTip(self.request, 'Print Request header for textpts in Seleted Site') ##scrolltest## xscrollbar = Scrollbar(self.right, orient=HORIZONTAL) xscrollbar.grid(row=3, column=1, columnspan=6, sticky=E + W) self.text = ScrolledText(self.right, height=30, state='disabled', wrap=NONE, xscrollcommand=xscrollbar.set) self.text.grid(row=2, column=1, columnspan=6, padx=10, pady=5, sticky=W + E) xscrollbar.config(command=self.text.xview) pass def st(self): if self.aa == False: self.aa = True self.stop.config(text="resume scan") elif self.aa == True: self.aa = False self.stop.config(text="pause scan") def th(self): if self.entry.get(): if self.r.get(): print self.r.get() self.t1 = threading.Thread(target=self.rev, args=[]) self.t1.setDaemon(True) self.t1.start() #self.t2 = threading.Thread(target=self.status, args=[]) #self.t2.start() else: messagebox.showerror("Error", "First Select the Attack Mode") else: messagebox.showerror("Error", "First Entre the target site") ##callback function for exit button## def exe(self): self.root.destroy() ##callback function for help menu## def he(self): help = mes.message() self.text.config(state='normal') #help="This is python based tool which crowl the target web site and print scripts and comments present at the target web page. " self.text.insert(END, help) self.text.config(state='disabled') ##call back function for seting menu bar## def con(self): self.top = Toplevel() self.top.title("User Agents") self.top.geometry("200x150") self.top.resizable(False, False) ba_1 = Radiobutton(self.top, variable=self.rr, value=1, text="Chrome on Windows 8.1") ba_1.grid(row=0, column=0, sticky=W) tt.create_ToolTip( ba_1, 'User-Agent : Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36' ) ba_2 = Radiobutton(self.top, variable=self.rr, value=2, text="Safari on iOS") ba_2.grid(row=1, column=0, sticky=W) tt.create_ToolTip( ba_2, 'User-Agent : Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4' ) ba_3 = Radiobutton(self.top, variable=self.rr, value=3, text="IE6 on Windows XP") ba_3.grid(row=2, column=0, sticky=W) tt.create_ToolTip( ba_3, 'User-Agent : Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)' ) ba_4 = Radiobutton(self.top, variable=self.rr, value=4, text="Googlebot") ba_4.grid(row=3, column=0, sticky=W) tt.create_ToolTip( ba_4, 'User-Agent : Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' ) bb = Button(self.top, text="Exit", command=self.top.destroy) bb.grid(row=4, column=0) ##callback function for submitt button## def _mess(self): messagebox.showerror("Error", "First Select the target from listbox") ##print the textpts## def comment(self): click_item = self.list.curselection() self.text.config(state='normal') if click_item: self.text.delete(1.0, END) t = self.list.get(click_item) tt = str(comm[t]) self.text.insert(END, tt) else: self._mess() self.text.config(state='disabled') def script(self): click_item = self.list.curselection() self.text.config(state='normal') if click_item: self.text.delete(1.0, END) t = self.list.get(click_item) self.tt = (sc[t]) self.text.insert(END, self.tt) else: self._mess() self.text.config(state='disabled') ##print the request headers## def req_2(self): click_item = self.list.curselection() self.text.config(state='normal') if click_item: self.text.delete(1.0, END) self.text.insert(END, "GET\t") self.text.insert(END, self.list.get(click_item)) t = self.list.get(click_item) tt = req[t] for ta in tt: pa = ta + "\t\t" + ":" + tt[ta] + "\n" self.text.insert(END, pa, 'rehead') else: self._mess() self.text.config(state='disabled') self.text.tag_config('rehead', foreground='red') ##print the response## def head_2(self): click_item = self.list.curselection() self.text.config(state='normal') if click_item: self.text.delete(1.0, END) statue = str(resp[self.list.get(click_item)]) + "\n" self.text.insert(END, statue, 'statue') t = self.list.get(click_item) tt = head[t] for ta in tt: pa = ta + "\t\t" + ":" + tt[ta] + "\n" self.text.insert(END, pa, 'head') self.text.insert(END, "\n") la = res[self.list.get(click_item)] #print la self.text.insert(END, la, 'body') else: self._mess() self.text.tag_config('statue', foreground='blue') self.text.tag_config('head', foreground='red') self.text.tag_config('body', foreground='green') self.text.config(state='disabled') ##scan for vulnerabilites## def vul_2(self): click_item = self.list.curselection() self.text.config(state='normal') if click_item: self.text.delete(1.0, END) t = self.list.get(click_item) tt = head[t] try: xssprotect = tt['X-XSS-Protection'] if xssprotect != '1; mode=block': self.text.insert( END, '\nX-XSS-Protection not set properly, XSS may be possible:' ) except: self.text.insert( END, '\nX-XSS-Protection not set, XSS may be possible') try: contenttype = tt['X-Content-Type-Options'] if contenttype != 'nosniff': self.text.insert( END, '\nX-Content-Type-Options not set properly:') except: self.text.insert(END, '\nX-Content-Type-Options not set') try: hsts = tt['Strict-Transport-Security'] except: self.text.insert( END, '\nHSTS header not set, MITM attacks may be possible') try: csp = tt['Content-Security-Policy'] self.text.insert(END, '\nContent-Security-Policy set:') except: self.text.insert(END, '\nContent-Security-Policy missing') try: click = tt['x-frame-options'] except: self.text.insert( END, "\nX-Frame-Options Header is not set, Clickjacking may be possible\n" ) self.text.insert(END, "\nCookie Information\n", 'title') self.text.tag_config('title', foreground='blue') for cookie in sop[t].cookies: name = str(cookie.name) self.text.insert(END, 'Name :', 'nam') self.text.insert(END, name + '\n', 'value') self.text.insert(END, 'Value :', 'nam') self.text.insert(END, cookie.value + '\n', 'value') if not cookie.secure: cookie.secure = "False" self.text.insert(END, 'Secure :', 'nam') self.text.insert(END, cookie.secure + '\n', 'value') if 'httponly' in cookie._rest.keys(): cookie.httponly = 'True' else: cookie.httponly = 'False' self.text.insert(END, 'HTTPOnly :', 'nam') self.text.insert(END, cookie.httponly + '\n', 'value') if cookie.domain_initial_dot: cookie.domain_initial_dot = 'True' self.text.insert(END, 'Cookie Scope to parent domain :', 'nam') self.text.insert(END, str(cookie.domain_initial_dot) + '\n', 'value') self.text.insert(END, "-------------------------------\n", 'new') self.text.tag_config('nam', foreground='red') self.text.tag_config('value', foreground='green') self.text.tag_config('new', foreground='orange') else: self._mess() self.text.config(state='disabled') def rev(self): self.text.config(state='normal') self.text.delete(1.0, END) self.text.config(state='disabled') self.menu_bar.entryconfig("Help", state='disabled') self.menu_bar.entryconfig("Setting", state='disabled') self.script.config(state='normal') self.comments.config(state='normal') self.request.config(state='normal') self.response.config(state='normal') self.vul.config(state='normal') self.stop.config(state='normal') self.submit.config(state='disabled') self.entry.config(state='disabled') if self.rr.get() == 1: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36' } elif self.rr.get() == 2: headers = { 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4' } elif self.rr.get() == 3: headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)' } elif self.rr.get() == 4: headers = { 'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } else: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36' } print "user agent" + str(self.rr.get()) content = self.entry.get() if (content[:4] == "http") or (content[:5] == "https"): L.put(content) else: content = "https://" + content L.put(content) print self.entry.get() while (L.qsize()): ##start progress bar## self.progre.start() self.style.configure("text.Horizontal.TProgressbar", text="Scan is running") ##pause the scan## print self.aa while (self.aa): self.progre.stop() self.style.configure("text.Horizontal.TProgressbar", text="Scan Paused") #print("scan stop") trurl = L.get() ##check target is previsely scaned or not## if trurl in duplic: continue else: duplic.add(str(trurl)) ## check target address is correct or not## try: response = requests.get(trurl, headers=headers) except: self.text.delete(1.0, END) self.progre.stop() #self.text.insert(END,"Please Entre Valid Address") messagebox.showerror("Error", "Please Entre Valid Address") break ##insert the scaned links in the list box## self.list.insert(END, trurl) resp[trurl] = response head[trurl] = response.headers # storing response the headers req[trurl] = response.request.headers #storing request headers com = " " sc[trurl] = com ##finding the scripts## soup = BeautifulSoup(response.content, "lxml") for line in soup.find_all('script'): for r in line.text.split(">"): #print r+"\n" sc[trurl] += (r) + "\n" ##finding the comments## aa = re.compile("\n") a = aa.sub(" ", response.text) comments = re.findall(r'[^>]<!--(.*?)-->', a) sop[trurl] = response if comments: com = " " comm[trurl] = com for c in comments: comm[trurl] += "\n" + com + str(c) else: comm[trurl] = "Comments not avaliable" #tt=str(sc[click_item] #print soup.prettify() res[trurl] = soup.prettify() #response.text #storing response if (self.r.get() == 2): for line in soup.find_all('a'): newline = line.get('href') print newline try: if newline[:4] == "http" or newline[:5] == "https": #count up to four digits if trurl in newline: L.put(newline) #print L.qsize() elif newline[:1] == "/": combine = trurl + newline L.put(combine) #print L.qsize() #print combine elif newline[:1] != "/": combine = trurl + "/" + newline L.put(combine) except: print "Error" elif (self.r.get() == 1): L.empty() self.progre.stop() self.style.configure("text.Horizontal.TProgressbar", text="Scan is completed") self.progre['value'] = 200 self.submit.config(state='normal') self.entry.config(state='normal') self.entry.delete(0, 'end') self.stop.config(state='disabled') self.menu_bar.entryconfig("Help", state='normal') self.menu_bar.entryconfig("Setting", state='normal')
class Window(ttk.Frame): def __init__(self, parent): self.tab_delim = "\n=====++++++=====\n" self.tabs = [] self.dirty = False ttk.Frame.__init__(self, parent) self.parent = parent self.parent.title("Very Secret Things") self.style = ttk.Style() self.style.theme_use("default") self.pack(fill=tk.BOTH, expand=1) self.nb = ttk.Notebook(self) self.nb.pack(fill=tk.BOTH, expand=1) self.saveButton = ttk.Button(self, text="Close", command=self.save) self.saveButton.pack(side=tk.RIGHT, padx=5, pady=5) # I don't feel like making a rekey dialog atm #~ rekeyButton = ttk.Button(self, text="Re-Key", command=self.rekey) #~ rekeyButton.pack(side=tk.RIGHT, padx=5, pady=5) addButton = ttk.Button(self, text="Add Tab", command=self.add_tab) addButton.pack(side=tk.LEFT, padx=5, pady=5) delButton = ttk.Button(self, text="Delete Tab", command=self.rem_tab) delButton.pack(side=tk.LEFT, padx=5, pady=5) #add search tab f = ttk.Frame(self.nb) self.search = ttk.Entry(f) self.search.focus() self.search.pack(fill=tk.BOTH) self.search.bind("<KeyRelease>", self.search_key_press) self.search_result = ScrolledText(f, relief=tk.RAISED, wrap=tk.WORD, state=tk.DISABLED) self.search_result.pack(fill=tk.BOTH, expand=1) self.nb.add(f, text='search') #add other tabs for text in self.parent.secret.split(self.tab_delim): self.add_tab(text, dirty=False) self.nb.select(self.nb.tabs()[0]) #select search tab def search_key_press(self, key): '''if search key is found displays that line and all lines below it until an empty line is reached.''' search = self.search.get() found = [] state = None for line in self.parent.secret.splitlines(): if state is None: if search in line.lower(): state = line else: if line.strip() == "": found.append(state) state = None else: state += "\n" + line if state is not None: found.append(state) self.search_result.config(state=tk.NORMAL) self.search_result.delete("0.0", tk.END) self.search_result.insert(tk.INSERT, "\n\n".join(found)) self.search_result.config(state=tk.DISABLED) def save(self): if self.dirty: #file changed self.update(dirty=False) save(self.parent.secret, self.parent.key, self.parent.geometry()) self.quit() def rem_tab(self): tabid = self.nb.select() if self.nb.index(tabid) > 0: #index minus 1 to account for search tab del self.tabs[self.nb.index(tabid) - 1] self.nb.forget(tabid) self.update() def add_tab(self, text='new', dirty=True): f = ttk.Frame(self.nb) # see http://stackoverflow.com/questions/13832720/how-to-attach-a-scrollbar-to-a-text-widget t = ScrolledText(f, relief=tk.RAISED, wrap=tk.WORD) t.insert(tk.INSERT, text) t.pack(fill=tk.BOTH, expand=1) t.bind("<KeyRelease>", self.update) self.nb.add(f) self.tabs.append(t) self.nb.select(self.nb.tabs()[-1]) self.update(dirty=dirty) def update(self, key=None, dirty=True): if dirty and not self.dirty: self.dirty = True self.saveButton.config(text="Save&Close") data = [tab.get('0.0', tk.END).rstrip() for tab in self.tabs] self.parent.secret = self.tab_delim.join(data) #update tab title tabid = self.nb.select() name = data[self.nb.index(tabid) - 1].rstrip().split('\n', 1)[0].strip() self.nb.tab(tabid, text=name or "empty")
class App: def __init__(self, master): class IORedirector(object): def __init__(self, stext): self.stext = stext class StdoutRedirector(IORedirector): def write(self, str): self.stext.insert(END, str) self.skip_apnx = BooleanVar() self.is_azw = BooleanVar() self.is_log = BooleanVar() self.nac = IntVar() self.is_overwrite_pdoc_thumbs = BooleanVar() self.is_overwrite_amzn_thumbs = BooleanVar() self.is_overwrite_apnx = BooleanVar() self.kindlepath = StringVar() self.status = StringVar() self.days = StringVar() self.frame = Frame(master, borderwidth=5) self.frame.pack(side=TOP, anchor=W) self.chk_button = Button(self.frame, text="Choose Kindle", command=self.askdirectory, width=15) self.chk_button.pack(side=LEFT) self.kindle_label = Label(self.frame, textvariable=self.kindlepath) self.kindle_label.pack(side=LEFT) self.frame2 = Frame(master, borderwidth=5) self.frame2.pack(side=TOP, pady=5) self.frame3 = Frame( self.frame2, ) self.frame3.pack(side=TOP, anchor=W) self.days_entry = Entry( self.frame3, width=4, textvariable=self.days, state=DISABLED ) self.days_entry.pack(side=RIGHT, anchor=NW) self.days_checkbox = Checkbutton( self.frame3, text="Process only younger files than days provided: ", variable=self.nac, command=self.naccheck ) self.days_checkbox.deselect() self.days_checkbox.pack(side=TOP, anchor=NW) self.log_checkbox = Checkbutton( self.frame2, text="Write less informations in Message Window?", variable=self.is_log ) self.log_checkbox.deselect() self.log_checkbox.pack(side=TOP, anchor=NW) self.apnx_checkbox = Checkbutton( self.frame2, text="Skip generating book page numbers " "(APNX files)?", variable=self.skip_apnx ) self.apnx_checkbox.deselect() self.apnx_checkbox.pack(side=TOP, anchor=NW) self.labelframe = LabelFrame( self.frame2, text=" For special needs. Use with caution! ", padx=5, pady=5 ) self.labelframe.pack(fill="both", expand="yes", pady=10) self.over_pdoc_thumbs_checkbox = Checkbutton( self.labelframe, text="Overwrite existing personal documents (PDOC) covers?", variable=self.is_overwrite_pdoc_thumbs ) self.over_pdoc_thumbs_checkbox.deselect() self.over_pdoc_thumbs_checkbox.pack(side=TOP, anchor=NW) self.over_amzn_thumbs_checkbox = Checkbutton( self.labelframe, text="Overwrite existing amzn book (EBOK) and book sample (EBSP) " "covers?", variable=self.is_overwrite_amzn_thumbs ) self.over_amzn_thumbs_checkbox.deselect() self.over_amzn_thumbs_checkbox.pack(side=TOP, anchor=NW) self.over_apnx_checkbox = Checkbutton( self.labelframe, text="Overwrite existing book page numbers (APNX files)?", variable=self.is_overwrite_apnx ) self.over_apnx_checkbox.deselect() self.over_apnx_checkbox.pack(side=TOP, anchor=NW) self.azw_checkbox = Checkbutton( self.labelframe, text="Extract covers from AZW files?", variable=self.is_azw ) self.azw_checkbox.deselect() self.azw_checkbox.pack(side=TOP, anchor=NW) self.frame3 = Frame(master, borderwidth=5) self.frame3.pack(side=TOP, anchor=W) self.run_button = Button(self.frame3, text="Start", command=self.run, width=15) self.run_button.pack(side=LEFT) self.status_label = Label(self.frame3, textvariable=self.status) self.status_label.pack(side=LEFT, pady=5) self.frame4 = Frame(master, borderwidth=5) self.frame4.pack(side=TOP) self.msg1 = 'Message Window: \n' self.stext = ScrolledText(self.frame4, bd=1, wrap=WORD, height=25, width=100, relief=RIDGE) if sys.platform == 'win32': self.stext.config(font=('Courier', 9, 'normal')) self.stext.pack() self.stext.insert(END, self.msg1) sys.stdout = StdoutRedirector(self.stext) def naccheck(self): if self.nac.get() == 0: self.days_entry.delete(0, END) self.days_entry.configure(state='disabled') else: self.days_entry.configure(state='normal') def run(self): self.docs = os.path.join(self.kindlepath.get(), 'documents') self.stext.delete(1.0, END) self.status.set('Start processing your books...') tkMessageBox.showwarning( 'Starting...', 'Process is starting. Click OK button and wait for ' + 'finish confirmation...', icon='question', parent=root ) self.frame.update_idletasks() if self.days.get() == '': ec = extract_cover_thumbs( self.is_log.get(), self.is_overwrite_pdoc_thumbs.get(), self.is_overwrite_amzn_thumbs.get(), self.is_overwrite_apnx.get(), self.skip_apnx.get(), self.kindlepath.get(), self.docs, self.is_azw, None ) else: ec = extract_cover_thumbs( self.is_log.get(), self.is_overwrite_pdoc_thumbs.get(), self.is_overwrite_amzn_thumbs.get(), self.is_overwrite_apnx.get(), self.skip_apnx.get(), self.kindlepath.get(), self.docs, self.is_azw, self.days.get() ) if ec == 0: self.status.set('Process finished.') tkMessageBox.showwarning( 'Finished...', 'Process finished. Check Message Window for details...', icon='info', parent=root ) elif ec == 1: self.status.set('Process finished with PROBLEMS!') tkMessageBox.showwarning( 'Finished...', 'Process finished with PROBLEMS! ' + 'Check Message Window for details...', icon='warning', parent=root ) def askdirectory(self): if sys.platform == 'win32': a = tkFileDialog.askdirectory(initialdir="c:/") else: a = tkFileDialog.askdirectory(initialdir="/") self.kindlepath.set(str(a.encode(sys.getfilesystemencoding())))
class main: def __init__(self): # Start Tkinter and set Title self.root = tk.Tk() self.collections = [] self.root.title('Aluizium 2.1') # Audio Configuration self.CHUNK = 3024 self.FORMAT = pyaudio.paInt16 self.CHANNELS = 2 self.RATE = 44100 self.p = pyaudio.PyAudio() self.frames = [] self.st = 1 self.stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) # Set Frames objects = tk.Frame(self.root, padx=120, pady=20) # Pack Frame objects.pack(fill=tk.BOTH) self.title = tk.Label(objects, text="Speaker recognition software Aluizium 2.1") self.button_new_speaker = tk.Button( objects, width=30, padx=10, pady=5, text="Register new speaker", command=lambda: self.create_window1()) self.button_train = tk.Button(objects, width=30, padx=10, pady=5, text="Train", command=lambda: self.train()) self.button_recognize_speaker = tk.Button( objects, width=30, padx=10, pady=5, text="Recognize speaker", command=lambda: self.create_window2()) self.button_exit = tk.Button(objects, width=30, padx=10, pady=5, text='Exit', command=lambda: self.root.destroy()) self.title.grid(row=0, column=0, padx=5, pady=(10, 30)) self.button_new_speaker.grid(row=1, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_train.grid(row=2, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_recognize_speaker.grid(row=3, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_exit.grid(row=4, column=0, columnspan=1, padx=0, pady=(0, 10)) tk.mainloop() def gettext(self, text): print text.get() def play(self, file_name): if file_name == 'temp': audio = AudioSegment.from_wav(file_name + '.wav') else: audio = AudioSegment.from_wav('trainset/' + file_name + '.wav') play(audio) def start_record(self, file_name): self.st = 1 self.frames = [] stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK) start_time = datetime.now() seconds_before = -1 print('\n') while self.st == 1: data = stream.read(self.CHUNK) self.frames.append(data) self.root.update() time_delta = datetime.now() - start_time if time_delta.seconds != seconds_before: print('Recording... ' + str(time_delta.seconds) + 's') seconds_before = time_delta.seconds stream.close() file_name += '.wav' if file_name != 'temp.wav': file_name = 'trainset/' + file_name print('Saved as ' + '\'' + file_name + '\'') wf = wave.open(file_name, 'wb') wf.setnchannels(self.CHANNELS) wf.setsampwidth(self.p.get_sample_size(self.FORMAT)) wf.setframerate(self.RATE) wf.writeframes(b''.join(self.frames)) wf.close() def stop(self): self.st = 0 #pega os atributos MFCC de um audio para ser usado no GMM def get_MFCC(self, sr, audio): #especifica o tamanho do frame, overlap e quantidade de atributos features = mfcc.mfcc(audio, sr, 0.025, 0.01, 13, appendEnergy=False) feat = np.asarray(()) for i in range(features.shape[0]): temp = features[i] #nan é atributo nao numerico if np.isnan(np.min(temp)): continue else: if feat.size == 0: feat = temp else: feat = np.vstack((feat, temp)) features = feat features = preprocessing.scale(features) return features def get_FFT(self, audio): # x , sr = librosa.load(audio) x, sr = librosa.load(audio, sr=16000) zero_crossings = librosa.zero_crossings(x, pad=False) spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0] spectral_rolloff = librosa.feature.spectral_rolloff(x, sr=sr)[0] contrast = librosa.feature.spectral_contrast(x, sr=sr) bandwidth = librosa.feature.spectral_bandwidth(x, sr=sr) result = np.array([ np.average(zero_crossings), np.average(spectral_centroids), np.average(spectral_rolloff), np.average(contrast), np.average(bandwidth) ]) return result def train(self): global gmm global names global tr global trainFTT gmm = [] tr = [] names = [] trainFFT = [] qty = len(fnmatch.filter(os.listdir('trainset/'), '*.wav')) #cria for i in range(0, qty): gmm.append(GMM(n_components=8, covariance_type='diag', n_init=3)) arr = [] print("\n") parent_dir = r'trainset/' for wav_file in glob.glob(os.path.join(parent_dir, '*.wav')): print('Trainning with ' + wav_file) # MFCC (rate, sig) = wav.read(wav_file) # FTT tr.append(self.get_FFT(wav_file)) wav_file = re.sub('\.wav$', '', wav_file) names.append(wav_file) trainset = self.get_MFCC(rate, sig) arr.append(trainset) trainMFCC = np.array(arr) trainFTT = np.array(tr) for i in range(len(gmm)): gmm[i].fit( trainMFCC[i] ) #coloca informações pra dentro do gmm, utilizado para treinar print(names) def test(self): global gmm global names aux = np.zeros(len(names)) score = np.zeros(len(names)) print('\n') (rate, sig) = wav.read("temp.wav") temp = self.get_MFCC(rate, sig) test = np.array([temp]) for i in range(len(names)): scores = np.array(gmm[i].score(test[0])) aux[i] = scores.sum() print("Speaker recognized (MFCC): " + names[np.argmax(aux)]) test = self.get_FFT('temp.wav') test = np.array([test]) neigh = KNeighborsClassifier(n_neighbors=1) neigh.fit(trainFTT, names) print("Speaker recognized (TFF):"), print(neigh.predict(test[0].reshape(1, -1))) def recognize_speaker(self, file_name): print(file_name) def create_window1(self): window1 = tk.Toplevel(padx=120, pady=20) self.label_speaker_name = tk.Label(window1, text="Enter new speaker's name:") v = tk.StringVar(window1) self.entry_speaker_name = tk.Entry(window1, textvariable=v) self.button_record = tk.Button( window1, width=30, padx=10, pady=5, text='Record', command=lambda: self.start_record(file_name=self.entry_speaker_name .get())) self.button_stop = tk.Button(window1, width=30, padx=10, pady=5, text='Stop', command=lambda: self.stop()) self.button_play = tk.Button( window1, width=30, padx=10, pady=5, text='Play', command=lambda: self.play(file_name=self.entry_speaker_name.get())) self.label_text_to_read = tk.Label(window1, text="Text to read: ") with open('text.txt', 'r') as file: text = file.read() self.scrolled_text = ScrolledText(window1, height=10, width=80) self.scrolled_text.config(wrap="word") self.scrolled_text.insert(tk.END, text) self.label_speaker_name.grid(row=0, column=0, padx=5) self.entry_speaker_name.grid(row=1, column=0, columnspan=2, padx=0, pady=(0, 10)) self.button_record.grid(row=2, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_stop.grid(row=3, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_play.grid(row=4, column=0, columnspan=1, padx=0, pady=(0, 10)) self.label_text_to_read.grid(row=5, column=0, padx=5, sticky='w', pady=(30, 5)) self.scrolled_text.grid(row=6, column=0, columnspan=1, padx=0, pady=(0, 10)) def create_window2(self): window2 = tk.Toplevel(padx=120, pady=20) self.button_record2 = tk.Button( window2, width=30, padx=10, pady=5, text='Record', command=lambda: self.start_record(file_name='temp')) self.button_stop2 = tk.Button(window2, width=30, padx=10, pady=5, text='Stop', command=lambda: self.stop()) self.button_play2 = tk.Button( window2, width=30, padx=10, pady=5, text='Play', command=lambda: self.play(file_name='temp')) self.button_test = tk.Button(window2, width=30, padx=10, pady=5, text='Test', command=lambda: self.test()) self.button_record2.grid(row=0, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_stop2.grid(row=1, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_play2.grid(row=2, column=0, columnspan=1, padx=0, pady=(0, 10)) self.button_test.grid(row=3, column=0, columnspan=1, padx=0, pady=(0, 10))
class App: def __init__(self, master): self.master = master self.file = 'grid.csv' self.ownZepName = "Jack" self.updatingFlag = False self.btnUpPressed = False self.btnDownPressed = False self.btnLeftPressed = False self.btnRightPressed = False self.btnPlusPressed = False self.btnMinusPressed = False #keyListener aanzetten master.bind("<Key>", self.keyPressed) master.bind("<KeyRelease>", self.keyReleased) labelFont = tkFont.Font(size = 16) leftFrame = Frame(master, width = 200, height = 640) leftFrame.grid(row = 0, column = 0) debugFrame = Frame(leftFrame, width = 200, height = 400) debugFrame.grid(row = 0, column = 0) controlFrame = Frame(leftFrame, width = 200, height = 200) controlFrame.grid(row = 1, column = 0, pady = 20) rasterFrame = Frame(master, width = 600, height = 640) rasterFrame.grid(row = 0, column = 1) #Scrolledtext in leftTopFrame self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=65) self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10) #Buttons #hoogte self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(100.0)) self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte: ", anchor = "w") self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20) self.lblGemetenHoogte.grid(row=0, column=2) self.lblGemetenHoogteVar.grid(row=0, column=3) #autopilot TODO string self.automaticFlag = False self.btnAutomaticPilot = Button(controlFrame, text = "Auto-pilot", width = 14, bg = 'gray85', command = lambda: self.toggleAutomaticPilot()) self.btnAutomaticPilot.grid(row = 1, column = 2) self.btnTest = Button(controlFrame, text = "Update", width = 14, bg = 'gray85', command = lambda: self.fetchPhoto()) self.btnTest.grid(row = 3, column = 2) self.automaticString = StringVar() self.automaticString.set("Niet Actief") self.lblAutomatic = Label(controlFrame, textvariable = self.automaticString, font = tkFont.Font(size = 14)) self.lblAutomatic.grid(row = 1, column = 3) #verbinding self.connected = False; self.btnConnect = Button(controlFrame, text = "Verbind", width = 14, bg = 'gray85', command = lambda: self.createClient()) self.btnConnect.grid(row = 2, column = 2) self.connectedString = StringVar() self.connectedString.set("Niet Verbonden") self.lblConnected = Label(controlFrame, textvariable = self.connectedString, font = tkFont.Font(size = 14)) self.lblConnected.grid(row = 2, column = 3) #motorinfo self.lblmotorUpString = Label(controlFrame, text = "MOTOR U: ", fg = "red", font = labelFont) self.lblmotorUpString.grid(row = 0, column = 0) self.lblmotorLeftString = Label(controlFrame, text = "MOTOR L: ", fg = "red", font = labelFont) self.lblmotorLeftString.grid(row = 1, column = 0) self.lblmotorRightString = Label(controlFrame, text = "MOTOR R: ", fg = "red", font = labelFont) self.lblmotorRightString.grid(row = 2, column = 0) self.lblmotorPWMString = Label(controlFrame, text = "PWM U: ", font = labelFont) self.lblmotorPWMString.grid(row = 3, column = 0) self.motorLeftString = StringVar() self.motorLeftString.set("S") self.motorRightString = StringVar() self.motorRightString.set("S") self.motorUpString = StringVar() self.motorUpString.set("S") self.motorPWMString = StringVar() self.motorPWMString.set("100") self.lblmotorUpStringValue = Label(controlFrame, textvariable = self.motorUpString, width = 5, fg = "red", font = labelFont) self.lblmotorUpStringValue.grid(row = 0, column = 1) self.lblmotorLeftStringValue = Label(controlFrame, textvariable = self.motorLeftString, width = 5, fg = "red", font = labelFont) self.lblmotorLeftStringValue.grid(row = 1, column = 1) self.lblmotorRightStringValue = Label(controlFrame, textvariable = self.motorRightString, width = 5, fg = "red", font = labelFont) self.lblmotorRightStringValue.grid(row = 2, column = 1) self.motorPWMStringValue = Label(controlFrame, textvariable = self.motorPWMString, width = 5, font = labelFont) self.motorPWMStringValue.grid(row = 3, column = 1) #self.createClient() #images self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0) self.display.grid(row=0, column = 0, sticky=W+E+N+S) #goal original = Image.open('goalPin.png') resized = original.resize((60,60),Image.ANTIALIAS) self.goalImage = ImageTk.PhotoImage(resized) self.makeBackground() self.initZeppelins() #kan interactief gebeuren met invoer als namen en bron in debugvenster typen self.paintCanvas() def initZeppelins(self): self.zeppelins = [] self.goal = (100,100) #self.zeppelins.append(AbstractZeppelin('green', 'Weppelin', self, randomSimu.randomSimulator(self, 'Weppelin', self.goal[0], self.goal[1]))) def requestUpdate(self, n): for z in self.zeppelins: if z.name == n: z.updateInfo() def convToPixelCoords(self, pos): cmHeight = 34.6410162 cmWidth = 40.0 xcm, ycm = pos x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth y = self.yStart + (ycm/cmHeight)*self.triangleHeight result = (x,y) return result def makeBackground(self): #rooster inlezen: f = open("../positioning/"+ str(self.file), 'r') shapesText = f.read() lofl = map(lambda l: l.split(","), shapesText.split("\n")) self.raster = [val.strip() for subl in lofl for val in subl] f.close() nrows = len(lofl) ncol = len(lofl[0]) tempWidth1 = 600/ncol tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0)) tempHeight2 = 570/nrows+2 tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0)) #raster self.resizedRaster = Image.new("RGB", (600,570), (240,240,240)) #vormpjes self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS'] self.shapeImages = [] for i in range(20): imgFile = "vormpjes/" + self.allShapes[i] + ".png" original = Image.open(imgFile) self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS)) self.xlen = ncol self.ylen = nrows self.triangleWidth = min(tempWidth1, tempWidth2) self.triangleHeight = min(tempHeight1, tempHeight2) self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4 self.oddXStart = self.evenXStart + self.triangleWidth/2 self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4 draw = ImageDraw.Draw(self.resizedRaster) #grid tekenen for y in range(self.ylen): for x in range(self.xlen): ycoord = self.yStart + y*self.triangleHeight zelf = self.raster[y*self.xlen + x] != "XX" if y>0: boven = self.raster[(y-1)*self.xlen + x] != "XX" if y<self.ylen-1: onder = self.raster[(y+1)*self.xlen + x] != "XX" if y>0 and x < self.xlen-1: oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX" if y<self.ylen-1 and x < self.xlen-1: oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX" if x<self.xlen-1: naast = self.raster[y*self.xlen + x+1] != "XX" if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and onder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and boven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) else: xcoord = self.oddXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and x < self.xlen-1 and oddboven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) del draw #vormpjes tekenen for y in range(self.ylen): for x in range(self.xlen): index = y*self.xlen + x if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth else: xcoord = self.oddXStart + x*self.triangleWidth ycoord = self.yStart + y*self.triangleHeight shape = self.raster[index] if shape != 'XX': image = self.shapeImages[self.allShapes.index(shape)] self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) def updatePath(self): self.rasterBackup = self.rasterImage draw = ImageDraw.Draw(self.resizedRaster) for z in self.zeppelins: length = len(z.locations) if length > 1: prev = self.convToPixelCoords(z.locations[length-2]) current = self.convToPixelCoords(z.locations[length-1]) draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) del draw def paintCanvas(self): #clear the canvas #self.display.delete('all') #rooster tekenen self.updatePath() self.display.create_image(0, 0, image=self.rasterImage, anchor=NW) #Testcode voor zeppelin locatie for z in self.zeppelins: point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20)) point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20)) point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20)) point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20)) point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation)) point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation)) self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color) arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y] self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1) self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER) #tekst weergeven in debug venster def debugPrint(self, tekst): self.scrDebug.config(state = "normal") self.scrDebug.insert(END, ">> " + tekst + "\n") self.scrDebug.config(state = "disabled") self.scrDebug.yview_pickplace("end") def toggleAutomaticPilot(self): if not self.connected: return self.debugPrint("Automatische piloot toggle aangevraagd") self.client.toggleAutomaticPilot() def createClient(self): try: if self.connected == False: self.client = cl(self, self.ownZepName) self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client)) self.connected = True self.connectedString.set("Verbonden") self.lblConnected.config(fg = "green") self.debugPrint("Verbonden met Raspberry Pi") else: self.debugPrint("Al verbonden") except: self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n -Staat de Raspberry Pi aan?\n -Staat de server aan?\n -Zit deze computer op de ad-hoc?") def disconnect(self): self.connected = False self.connectedString.set("Niet verbonden") self.lblConnected.config(fg = "red") def fetchPhoto(self): if not self.connected or self.automaticFlag: return self.client.updateInformation() def moveForward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Voorwaarts vliegen aangevraagd") self.client.flyForward() def moveBackward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Achterwaarts vliegen aangevraagd") self.client.flyBackward() def moveLeft(self): if not self.connected or self.automaticFlag: return self.debugPrint("Links draaien aangevraagd") self.client.turnLeft() def moveRight(self): if not self.connected or self.automaticFlag: return self.debugPrint("Rechts draaien aangevraagd") self.client.turnRight() def moveUp(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omhoog vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpBackward() def moveDown(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omlaag vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpForward() def horizontalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Horizontale motors stoppen aangevraagd") self.client.stopHorizontalMotors() def verticalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Verticale motor stoppen aangevraagd") self.client.motorUpStop() #toetsenbord invoer def keyPressed(self, event): k = event.keysym if k == 'Up': if not self.btnUpPressed: self.btnUpPressed = True self.moveForward() elif k == 'Down': if not self.btnDownPressed: self.btnDownPressed = True self.moveBackward() elif k == 'Left': if not self.btnLeftPressed: self.btnLeftPressed = True self.moveLeft() elif k == 'Right': if not self.btnRightPressed: self.btnRightPressed = True self.moveRight() elif k == 'plus': if not self.btnPlusPressed: self.btnPlusPressed = True self.moveUp() elif k == 'minus': if not self.btnMinusPressed: self.btnMinusPressed = True self.moveDown() def keyReleased(self, event): k = event.keysym if k == 'Up': self.btnUpPressed = False self.horizontalOff() elif k == 'Down': self.btnDownPressed = False self.horizontalOff() elif k == 'Left': self.btnLeftPressed = False self.horizontalOff() elif k == 'Right': self.btnRightPressed = False self.horizontalOff() elif k == 'plus': self.btnPlusPressed = False self.verticalOff() elif k == 'minus': self.btnMinusPressed = False self.verticalOff() def updateAutomatic(self, info): if info[0]: self.debugPrint(str(info[4])) def updateInfo(self, info): global realHeight if info[0] != -1: self.gemetenHoogteString.set(str(info[0])) self.motorUpString.set(info[1]) if info[1] == "V" or info[1] == "A": self.lblmotorUpString.config(fg = "green") self.lblmotorUpStringValue.config(fg = "green") else: self.lblmotorUpString.config(fg = "red") self.lblmotorUpStringValue.config(fg = "red") self.motorLeftString.set(info[2]) if info[2] == "V" or info[2] == "A": self.lblmotorLeftString.config(fg = "green") self.lblmotorLeftStringValue.config(fg = "green") else: self.lblmotorLeftString.config(fg = "red") self.lblmotorLeftStringValue.config(fg = "red") self.motorRightString.set(info[3]) if info[3] == "V" or info[3] == "A": self.lblmotorRightString.config(fg = "green") self.lblmotorRightStringValue.config(fg = "green") else: self.lblmotorRightString.config(fg = "red") self.lblmotorRightStringValue.config(fg = "red") self.motorPWMString.set(str(math.ceil(info[4]))) self.automaticFlag = info[6] if(not self.automaticFlag): self.automaticString = "Niet Actief" else: self.automaticString = "Actief"
class SigBridgeUI(Tk): server = None server_thread = None def __init__(self): Tk.__init__(self) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) # 2 rows: firts with settings, second with registrar data self.main_frame = Frame(self) # Commands row doesn't expands self.main_frame.rowconfigure(0, weight=0) # Logs row will grow self.main_frame.rowconfigure(1, weight=1) # Main frame can enlarge self.main_frame.columnconfigure(0, weight=1) self.main_frame.columnconfigure(1, weight=1) self.main_frame.grid(row=0, column=0) # Run/Stop button self.server_button = Button(self.main_frame, text="Connect", command=self.start_server) self.server_button.grid(row=0, column=0) # Clear button self.clear_button = Button(self.main_frame, text="Clear Log", command=self.clear_log) self.clear_button.grid(row=0, column=1) # Logs Widget self.log_widget = ScrolledText(self.main_frame) self.log_widget.grid(row=1, column=0, columnspan=2) # made not editable self.log_widget.config(state='disabled') # Queue where the logging handler will write self.log_queue = Queue.Queue() # Setup the logger self.uilogger = logging.getLogger('SigBridgeUI') self.uilogger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') # Use the QueueLogger as Handler hl = QueueLogger(queue=self.log_queue) hl.setFormatter(formatter) self.uilogger.addHandler(hl) # self.log_widget.update_idletasks() self.set_geometry() # Setup the update_widget callback reading logs from the queue self.start_log() def clear_log(self): self.log_widget.config(state='normal') self.log_widget.delete(0.0, END) self.log_widget.config(state='disabled') def start_log(self): self.uilogger.info("SigBridge Started.") self.update_widget() # self.control_log_button.configure(text="Pause Log", command=self.stop_log) def update_widget(self): self.log_widget.config(state='normal') # Read from the Queue and add to the log widger while not self.log_queue.empty(): line = self.log_queue.get() tag = "error" if " ERROR " in line else 'info' self.log_widget.insert(END, line, tag) self.log_widget.see(END) # Scroll to the bottom self.log_widget.update_idletasks() self.log_widget.tag_config('error', foreground="red") self.log_widget.config(state='disabled') self.log_widget.after(10, self.update_widget) def set_geometry(self): # set position in window w = 600 # width for the Tk h = 300 # height for the Tk # get screen width and height ws = self.winfo_screenwidth() # width of the screen hs = self.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk window x = (ws/2) - (w/2) y = (hs/2) - (h/2) # set the dimensions of the screen # and where it is placed self.geometry('%dx%d+%d+%d' % (w, h, x, y)) def start_server(self): try: self.server = SigServer(('0.0.0.0', 25), None, self.uilogger) self.server_thread = threading.Thread(name='server', target=self.server.run) self.server_thread.daemon = True self.server_thread.start() self.server_button.configure(text="Disconnect", command=self.stop_server) except Exception as err: self.uilogger("Cannot start the server: %s" % err.message) # self.label_variable.set(self.entry_variable.get()+"(Started Signal Server)") # self.entry.focus_set() # self.entry.selection_range(0, END) def stop_server(self): self.server.shutdown() self.server_button.configure(text="Connect", command=self.start_server) self.server = None
class App: ''' Class that defines the PokemonGo Forensics Application. ''' def __init__(self): ''' Initalize the Application GUI. ''' self.root = Tk() self.root.title("Pokemon GO: Forensic Analysis Tool") self.root.minsize(width=1500, height=900) self.root.protocol("WM_DELETE_WINDOW", self.on_closing) #Menu Bar self.menubar = Menu(self.root) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="Capture PokemonGo Backup", command=self.capture_backup) self.filemenu.add_command(label="Capture Full Backup", command= lambda: self.capture_backup(True)) self.filemenu.add_command(label="Create New Analysis from Backup", command=self.create_case_backup) self.filemenu.add_command(label="Open Case Folder", command=self.open_case_folder) self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.on_closing) self.menubar.add_cascade(label="File", menu=self.filemenu) #add menu bar to root window self.root.config(menu=self.menubar) #Create Main Paned Window self.m1 = PanedWindow(self.root) self.m1.pack(fill=BOTH, expand=1, padx=2, pady=3) #Create Left Pane For Treeview self.fileTree = ttk.Treeview(self.m1) self.fileTree["columns"]=("date_modified", "size") self.fileTree.column("#0", width=300) self.fileTree.column("date_modified", width=150) self.fileTree.column("size", width=150) self.fileTree.heading("#0", text="Name") self.fileTree.heading("date_modified", text="Date Modified") self.fileTree.heading("size", text="Size") #Bind double click option self.fileTree.bind("<Double-1>", self.FileTreeDoubleClick) #add file tree to paned window self.m1.add(self.fileTree) #Create Right Pane Window - Split self.m2 = PanedWindow(self.m1, orient=VERTICAL) self.m1.add(self.m2) #Create Notebook view for file information self.nb = cnb.CustomNotebook(self.m2, name="nb_View") self.nb.enable_traversal() #Frame for Welcome Tab self.welcomeFrame = Frame(self.nb, name="welcome") self.welcomeFrame.grid(row=0, column=0, columnspan=2, sticky='new') self.welcomeFrame.rowconfigure(1, weight=1) self.welcomeFrame.columnconfigure(1, weight=1) #Welcome Tab Text self.WelcomeMsgLbl = Label(self.welcomeFrame, text='Welcome!', font='TkDefaultFont 12 bold') self.WelcomeMsgLbl.grid(row=0, column=0, columnspan=2, sticky='new', pady=5, padx=5) self.OverviewMsgLbl = Label(self.welcomeFrame, text='Overview: ', font='TkDefaultFont 10 bold') self.OverviewMsgLbl.grid(row=1, column=0, sticky='nw', padx=2, pady=2) self.ExplainMsgLbl = Label(self.welcomeFrame, text='This application parses the session information from the Upsight Logs of the PokemonGo Application from an Android Backup File. Using this information an investigator is '+ 'able to determine the start and end time of the last time the game was actively played. Active game play is determined by when the game is '+ 'run in the foreground of the mobile device. Therefore, the session end time will reflect the time at which the application was terminated, '+ 'or backgrounded. If a backgrounded application is later terminated, the session end time will not be affected provided the application was ' + 'not brought to the forground before being terminated. The use of a PokemonGo Plus device with the mobile application will not affect this ' + 'session information. Gameplay can also be inferred by examining the timestamps of certian files within the mobile application. In particular ' + 'the files contained within the "ef/bundles" directory which contain Unity 3D models for different assets within the game, and are dynmically downloaded '+ 'during gameplay. \n\n'+ 'The application is capable retrieving and mapping the relative geolocation information of the user at the end of the last active session. These location cordinates are '+ 'rounded to two decimal places when stored by the application. Therefore, the cordinates can be two to three blocks off from the user\'s true position. '+ 'Applications installed before July 31, 2017 may contain crittercism log files. These log files may contain additional geolocation information.', font='TkDefaultFont 10', justify='left', wraplength=1000) self.ExplainMsgLbl.grid(row=2, column=0, columnspan=2, sticky='new', pady=2, padx=2) self.GettingStartedMsgLbl = Label(self.welcomeFrame, text='Getting Started:', font='TkDefaultFont 10 bold') self.GettingStartedMsgLbl.grid(row=3, column=0, sticky='nw', padx=2, pady=2) self.GSTxtLbl = Label(self.welcomeFrame, text='File>Capture PokemonGo Backup: Captures a backup of the PokemonGo Application from the target device.\n' + 'File>Capture Full Backup: Captures a full backup of the target device.\n'+ 'File>Create New Analysis from Backup: Creates a new case folder in the current working directory named after the selected Android backup file. \n' + ' The selected Android backup file is extracted to this directory, and the Upsight logs are parsed.\n'+ 'File>Open Case Folder: Opens a case folder containing an extracted Android backup file, and parses the Upsight logs.\n'+ '\nAfter a case has been opened, an Overview Tab will be created that contains all of the information contained within the Upsight logs. The application will '+ 'also generate a file tree of all the files contained within the mobile application, and their last modified timestamps. Double-Clicking on a file will '+ 'open the file in a hex viewer. The application will also provide an investigator the option to map the GPS cordinates found within the Upsight database. '+ 'If the application detects the presence of the Crittercism Log files, an option to parse, and map this location information will also be provided. ', font='TkDefaultFont 10', justify='left', wraplength=1000) self.GSTxtLbl.grid(row=4, column=0, sticky='nw', padx=2, pady=2) self.CrittercismMsgLbl = Label(self.welcomeFrame, text='Crittercism Logs:', font='TkDefaultFont 10 bold') self.CrittercismMsgLbl.grid(row=5, column=0, sticky='nw', padx=2, pady=2) self.CrittercismTxtLbl = Label(self.welcomeFrame, text='In order to parse the Crittercism log files, the Google S2 Geometry Library must be installed. This library is available at the following link: '+ 'https://github.com/micolous/s2-geometry-library\n\n' + 'The most accurate location information derived from these logs comes from enteries where an Cell ID encounter identifier was updated. These entries are represented by a blue marker on the map. '+ 'Log entries that indicate that a Cell ID was removed are shown in red. These appear to occur at the edges of the user\'s location. \n\n\n\n\n\n', font='TkDefaultFont 10', justify='left', wraplength=1000) self.CrittercismTxtLbl.grid(row=6, column=0, sticky='nw', padx=2, pady=2) self.nb.add(self.welcomeFrame, text="Welcome") self.m2.add(self.nb) #Create Event Viewer Window self.logViewText = ScrolledText(self.m2, height=10) self.logViewText.grid(row=0, column=0, sticky='nsew') self.m2.add(self.logViewText) #Create Event Viewer Object self.evtLogger = el.EventLogger(self, logfile) #Check if S2 Library Exists if not s2Lib: #if no record it in the log self.evtLogger.logEvent(self, "S2 Library Not Found!!", True) #Set default zoom levels self.zoomLvl = 15 self.cbcsZoomLvl = 15 self.pbcsZoomLvl = 15 #Successfully Initialized the application self.evtLogger.logEvent(self, "Application Initialized!") #Enter the mainloop self.root.mainloop() def capture_backup(self, full=False): ''' Capture a backup of the target (attached) device using Andriod Debug Bridge. @full: Capture Full backup of device (True), or Capture only PokemonGo (False) ''' #Get path to save capture as saveas = tkFileDialog.asksaveasfilename(defaultextension='.ab') try: #run adb devices command to check if device is recognized and adb is installed self.evtLogger.logEvent(self, "\n"+subprocess.check_output(['adb', 'devices'])) try: self.evtLogger.logEvent(self, 'Started Backup Process') #Determine if taking a full or partial back up if not full: output = subprocess.check_output(['adb', 'backup', 'com.nianticlabs.pokemongo', '-f', saveas], stderr=subprocess.STDOUT) else: output = subprocess.check_output(['adb', 'backup', '-all', '-f', saveas], stderr=subprocess.STDOUT) self.evtLogger.logEvent(self, output) self.evtLogger.logEvent(self, 'Completed Capture: '+saveas) except: #Problem Creating back up self.evtLogger.logEvent(self, 'An error occurred!!', True) except: #ADB Not found!! self.evtLogger.logEvent(self, 'Android Debug Bridge Not Found!', True) def on_closing(self): ''' Perform these actions when the application is closed. ''' #Log application termination self.evtLogger.logEvent(self, "Terminating Application!") #close the application self.root.destroy() def FileTreeDoubleClick(self, event): ''' Event Listener for Double Click on a File Tree Item. This method will display the hexdump of the clicked item in a new notebook tab. ''' item = self.fileTree.selection()[0] #check that clicked item is a file if os.path.isfile(item): self.evtLogger.logEvent(self, "Open Hexview of file: "+item) #create new frame self.fileViewFrame = Frame(self.nb) self.fileViewFrame.grid(row=0, column=0, columnspan=2, sticky='new') #create scrolled text box to display hex dump self.fileViewText = ScrolledText(self.fileViewFrame, height=40) self.fileViewText.grid(row=0, column=0, sticky='nsew', pady=5, padx=5) #read in contents of selected item with open(item, 'rb') as f: content = f.read() text = u.hexdump(content) #display contents in new scrolled text box self.fileViewText.insert(END, text) self.fileViewText.config(state=DISABLED) #add Frame to notebook self.nb.add(self.fileViewFrame, text=self.fileTree.item(item, "text")) #select newly added tab self.selectCurrentTab() def add_item(self, dirname, parentName=None, top=True): ''' Recursive function to add items to the File Tree Viewer. @dirname: current directory being parsed @parentName: Name of the parent item in tree @top: Specifies if a top level directory ''' dirs = os.listdir(dirname) if top is True: for name in dirs: path = os.path.join(dirname, name) #get metadata information timestamp = u.get_timestamp(path) fs = u.get_fileSize(path) self.fileTree.insert("", 0, path, text=name, values=(timestamp, fs)) if os.path.isdir(path) is True: self.add_item(path, path, False) else: for name in dirs: path = os.path.join(dirname, name) #get metadata information timestamp = u.get_timestamp(path) fs = u.get_fileSize(path) self.fileTree.insert(parentName, 0, path, text=name, values=(timestamp, fs)) if os.path.isdir(path) is True: self.add_item(path, path, False) def selectCurrentTab(self): ''' Function to select the top most tab in the notebook view. ''' self.nb.select(len(self.nb.tabs())-1) def parseCrittercismLogs(self, path, name): ''' Function to parse all files within the crittercism logs. This function searches for log entries that contain Cell ID information. The function converts Cell ID information into GPS Cordinates, and passes this information to the StaticMaps function to generate a map. The function will also return a list containing the raw text of each log entry that contains Cell ID information. @path: The path to the log files. @name: The name of the logs being searched (current_bcs|previous_bcs). This is passed to the StaticMaps function to name the map. ''' #obtain list of files in directory files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] #compile regular expression -> THis is more effecient cellRE = re.compile('(.*[C|c][e][l]{2}\s)([0-9]{19})(.*)') cordsRE= re.compile('[\[]([-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)[\,][\s]([-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?).*') cords = [] logText = [] for log in files: with open(os.path.join(path, log)) as f: content = f.read() result = cellRE.match(content) #check if log contains Cell ID information if result is not None: #append contents of log to list logText.append(result.group(0)) #Convert to GPS location information hexv = str(hex(int(result.group(2)))) cord = str(s2.S2CellId_FromToken(hexv[2:-1]).ToLatLng()) cre = cordsRE.findall(cord) #determine if Updating Cell Encounter or Removing Cell ID for x in cre: if result.group(1)[2:6] == 'Cell': cords.append((str(x[0]), str(x[4]), True)) else: cords.append((str(x[0]), str(x[4]), False)) if name == 'current_bcs': #Get Map of Current_BCS self.sm.getMap(str(self.cbcsZoomLvl), cords, name+str(self.cbcsZoomLvl)+'.gif' ) else: #Get Map of Previous_BCS self.sm.getMap(str(self.pbcsZoomLvl), cords, name+str(self.pbcsZoomLvl)+'.gif') #return raw text of each entry return logText def cbcsZoomIn(self): ''' Function to increase the zoom level of the current_bcs map. ''' #check zoom level if self.cbcsZoomLvl < 20: #increase zoom level self.cbcsZoomLvl = self.cbcsZoomLvl+1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', 'current_bcs'+str(self.cbcsZoomLvl)+'.gif')): self.evtLogger.logEvent(self, 'Increase Current_BCS Map Zoom Level: '+str(self.cbcsZoomLvl)) else: self.evtLogger.logEvent(self, "Download New Current_BCS Map Zoom Level: "+str(self.cbcsZoomLvl)) self.parseCrittercismLogs(os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'current_bcs'), 'current_bcs') #add image to frame self.current_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'current_bcs'+str(self.cbcsZoomLvl)+".gif")) self.current_bcsLogMapImageLbl = Label(self.current_bcsLogMapFrame, image=self.current_bcsLogMapImage) self.current_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Max Zoom!", True) def cbcsZoomOut(self): ''' Function to decrease the zoom level of the current_bcs map. ''' #check zoom level if self.cbcsZoomLvl > 1: #decrease zoom level self.cbcsZoomLvl = self.cbcsZoomLvl-1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', 'current_bcs'+str(self.cbcsZoomLvl)+'.gif')): self.evtLogger.logEvent(self, 'Decrease Current_BCS Map Zoom Level: '+str(self.cbcsZoomLvl)) else: self.evtLogger.logEvent(self, "Download New Current_BCS Map Zoom Level: "+str(self.cbcsZoomLvl)) self.parseCrittercismLogs(os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'current_bcs'), 'current_bcs') #add image to frame self.current_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'current_bcs'+str(self.cbcsZoomLvl)+".gif")) self.current_bcsLogMapImageLbl = Label(self.current_bcsLogMapFrame, image=self.current_bcsLogMapImage) self.current_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Min Zoom!", True) def pbcsZoomIn(self): ''' Function to increase the zoom level of the previous_bcs map. ''' #check zoom level if self.pbcsZoomLvl < 20: #increase zoom level self.pbcsZoomLvl = self.pbcsZoomLvl+1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', 'previous_bcs'+str(self.pbcsZoomLvl)+'.gif')): self.evtLogger.logEvent(self, 'Increase Previous_BCS Map Zoom Level: '+str(self.pbcsZoomLvl)) else: self.evtLogger.logEvent(self, "Download New Previous_BCS Map Zoom Level: "+str(self.pbcsZoomLvl)) self.parseCrittercismLogs(os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'previous_bcs'), 'previous_bcs') #add image to frame self.previous_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'previous_bcs'+str(self.pbcsZoomLvl)+".gif")) self.previous_bcsLogMapImageLbl = Label(self.previous_bcsLogMapFrame, image=self.previous_bcsLogMapImage) self.previous_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Max Zoom!", True) def pbcsZoomOut(self): ''' Function to decrease the zoom level of the previous_bcs map. ''' #check zoom level if self.pbcsZoomLvl > 1: #decrease zoom level self.pbcsZoomLvl = self.pbcsZoomLvl-1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', 'previous_bcs'+str(self.pbcsZoomLvl)+'.gif')): self.evtLogger.logEvent(self, 'Decrease Previous_BCS Map Zoom Level: '+str(self.pbcsZoomLvl)) else: self.evtLogger.logEvent(self, "Download New Previous_BCS Map Zoom Level: "+str(self.pbcsZoomLvl)) self.parseCrittercismLogs(os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'previous_bcs'), 'previous_bcs') #add image to frame self.previous_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'previous_bcs'+str(self.pbcsZoomLvl)+".gif")) self.previous_bcsLogMapImageLbl = Label(self.previous_bcsLogMapFrame, image=self.previous_bcsLogMapImage) self.previous_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Min Zoom!", True) def mapCrittercismLogs(self): ''' Function that generates the frames to display the current_bcs and previous_bcs maps. This function calls parseCrittercismLogs to parse the log files. ''' #check if S2 library is present if s2Lib: #parse files in current_bcs current_bcs = os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'current_bcs') if os.path.exists(current_bcs): #parse current_bcs log files logText = self.parseCrittercismLogs(current_bcs, 'current_bcs') #create frame to hold map self.current_bcsLogMapFrame = Frame(self.nb) self.current_bcsLogMapFrame.grid(row=0, column=0, sticky='nsew') #add image to frame self.current_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'current_bcs'+str(self.cbcsZoomLvl)+'.gif')) self.current_bcsLogMapImageLbl = Label(self.current_bcsLogMapFrame, image=self.current_bcsLogMapImage) self.current_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') #add Raw log file text to frame self.mapCurrent_BCSLogText = ScrolledText(self.current_bcsLogMapFrame, height=15, width=32) self.mapCurrent_BCSLogText.grid(row=0, column=2, columnspan=2, sticky='nsew') text = '' label = 'A' for x in logText: text = text + label+': '+x+'\n\n' label = chr(ord(label)+1) self.mapCurrent_BCSLogText.insert(END, text) self.mapCurrent_BCSLogText.config(state=DISABLED) #add zoom controls to frame self.mapCurrent_BCSZoomInBtn = Button(self.current_bcsLogMapFrame, text='Zoom In', command=self.cbcsZoomIn) self.mapCurrent_BCSZoomInBtn.grid(row=1, column=2, sticky='sew') self.mapCurrent_BCSZoomOutBtn = Button(self.current_bcsLogMapFrame, text='Zoom Out', command=self.cbcsZoomOut) self.mapCurrent_BCSZoomOutBtn.grid(row=2, column=2, sticky='new') #add frame to notebook view self.nb.add(self.current_bcsLogMapFrame, text='Current_BCS Map') #select recently added frame self.selectCurrentTab() else: #could not find current_bcs logs self.evtLogger.logEvent(self, 'Current_bcs logs not found!', True) #parse files in previous_bcs previous_bcs = os.path.join(self.caseDir, 'apps', 'com.nianticlabs.pokemongo', 'f', 'com.crittercism', 'previous_bcs') if os.path.exists(current_bcs): #parse previous_bcs log files logText = self.parseCrittercismLogs(previous_bcs, 'previous_bcs') #create frame to hold map self.previous_bcsLogMapFrame = Frame(self.nb) self.previous_bcsLogMapFrame.grid(row=0, column=0, sticky='nsew') #add image to frame self.previous_bcsLogMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', 'previous_bcs'+str(self.pbcsZoomLvl)+'.gif')) self.previous_bcsLogMapImageLbl = Label(self.previous_bcsLogMapFrame, image=self.previous_bcsLogMapImage) self.previous_bcsLogMapImageLbl.grid(row=0, column=0, rowspan=4, columnspan=2, sticky='nsew') #add raw log file text to frame self.mapPrevious_BCSLogText = ScrolledText(self.previous_bcsLogMapFrame, height=15, width=32) self.mapPrevious_BCSLogText.grid(row=0, column=2, columnspan=2, sticky='nsew') text = '' label = 'A' for x in logText: text = text + label+': '+x+'\n\n' label = chr(ord(label)+1) self.mapPrevious_BCSLogText.insert(END, text) self.mapPrevious_BCSLogText.config(state=DISABLED) #add zoom controls to frame self.mapPrevious_BCSZoomInBtn = Button(self.previous_bcsLogMapFrame, text='Zoom In', command=self.pbcsZoomIn) self.mapPrevious_BCSZoomInBtn.grid(row=1, column=2, sticky='sew') self.mapPrevious_BCSZoomOutBtn = Button(self.previous_bcsLogMapFrame, text='Zoom Out', command=self.pbcsZoomOut) self.mapPrevious_BCSZoomOutBtn.grid(row=2, column=2, sticky='new') #add frame to notebook view self.nb.add(self.previous_bcsLogMapFrame, text='Previous_BCS Map') #select recently added frame self.selectCurrentTab() else: #could not find previous_bcs self.evtLogger.logEvent(self, 'Previous_bcs logs not found!', True) else: #S2 Library not found self.evtLogger.logEvent(self, 'S2 Library not found!', True) def onClickMapCords(self, latitude, longitude): ''' Event Listener for displaying upsight map cordinates. @latitude: Latitude of marker. @longitude: Longitude of marker. ''' cords = [(str(latitude), str(longitude), False)] #check if map already exists if not os.path.isfile(os.path.join(self.caseDir, 'maps', 'upsightMap'+str(self.zoomLvl)+'.gif')): self.sm.getMap(str(self.zoomLvl), cords, "upsightMap"+str(self.zoomLvl)+".gif") #Create Frame to hold map self.upsightMapFrame = Frame(self.nb) self.upsightMapFrame.grid(row=0, column=0, sticky='nsew') #add image to frame self.upsightMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', "upsightMap"+str(self.zoomLvl)+".gif")) self.upsightMapImageLbl = Label(self.upsightMapFrame, image=self.upsightMapImage) self.upsightMapImageLbl.grid(row=0, column=0, rowspan=2, columnspan=2, sticky='nsew') self.evtLogger.logEvent(self, "Download New Upsight Map Zoom Level: "+str(self.zoomLvl)) #add zoom buttons to frame self.upsightMapZoomIn = Button(self.upsightMapFrame, text="Zoom In ", command= lambda: self.MapZoomIn('upsightMap', cords)) self.upsightMapZoomIn.grid(row=0, column=3, sticky='sew') self.upsightMapZoomOut = Button(self.upsightMapFrame, text='Zoom Out', command= lambda: self.MapZoomOut('upsightMap', cords)) self.upsightMapZoomOut.grid(row=1, column=3, sticky='new') self.upsightZoomSpacer = Label(self.upsightMapFrame) self.upsightZoomSpacer.grid(row=0, column=2) #add frame to notebook self.nb.add(self.upsightMapFrame, text="Upsight Cords") #select current frame self.selectCurrentTab() def MapZoomIn(self, name, cords): ''' Function to increase zoom level of upsight map. @name: name of the map image @cords: cordinates of map image marker ''' #check zoom level if self.zoomLvl < 20: #increase zoom level self.zoomLvl = self.zoomLvl + 1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', name+str(self.zoomLvl)+'.gif')): self.evtLogger.logEvent(self, "Increase Upsight Map Zoom Level: "+str(self.zoomLvl)) else: self.evtLogger.logEvent(self, "Download New Upsight Map Zoom Level: "+str(self.zoomLvl)) self.sm.getMap(str(self.zoomLvl), cords, "upsightMap"+str(self.zoomLvl)+".gif") #add image to frame self.upsightMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', "upsightMap"+str(self.zoomLvl)+".gif")) self.upsightMapImageLbl = Label(self.upsightMapFrame, image=self.upsightMapImage) self.upsightMapImageLbl.grid(row=0, column=0, rowspan=2, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Max Zoom!", True) def MapZoomOut(self, name, cords): ''' Function to decrease zoom level of upsight map. @name: name of the map image @cords: cordinates of the map image marker ''' #check zoom level if self.zoomLvl > 1: #decrease zoom level self.zoomLvl = self.zoomLvl - 1 #check if already downloaded if os.path.isfile(os.path.join(self.caseDir, 'maps', name+str(self.zoomLvl)+'.gif')): self.evtLogger.logEvent(self, "Decrease Upsight Map Zoom Level: "+str(self.zoomLvl)) else: self.evtLogger.logEvent(self, "Download New Upsight Map Zoom Level: "+str(self.zoomLvl)) self.sm.getMap(str(self.zoomLvl), cords, "upsightMap"+str(self.zoomLvl)+".gif") #add image to frame self.upsightMapImage = PhotoImage(file=os.path.join(self.caseDir, 'maps', "upsightMap"+str(self.zoomLvl)+".gif")) self.upsightMapImageLbl = Label(self.upsightMapFrame, image=self.upsightMapImage) self.upsightMapImageLbl.grid(row=0, column=0, rowspan=2, columnspan=2, sticky='nsew') else: self.evtLogger.logEvent(self, "Already at Min Zoom!", True) def create_case_backup(self): ''' Function to create a new case folder from an Android backup. ''' #get path to Andriod Backup file filename = tkFileDialog.askopenfilename(title='Create Case from Android Backup') #check that file was selected if filename != '': self.evtLogger.logEvent(self, "Creating A New Case from Backup: "+filename) #Get backup filename and current working directory name = u.getFileNameFromPath(filename) cwd = os.getcwd() #path to case directory caseDir = os.path.join(cwd, name[:-3]) #check if case directory exists if not os.path.exists(caseDir): #if not create directory and extract backup os.makedirs(caseDir) self.evtLogger.logEvent(self, "Creating New Case Folder: "+caseDir) #Path of extracted backup exBackup = os.path.join(caseDir, name[:-3]+'.tar') #extract the backup abePath = os.path.join(cwd, 'tools', 'abe', 'abe.jar') subprocess.call(['java', '-jar', abePath, 'unpack', filename, exBackup]) self.evtLogger.logEvent(self, "Extracting Andriod Backup: "+exBackup) #extract the tar file u.extractTarFile(exBackup, caseDir) self.evtLogger.logEvent(self, 'Extracting Archive... ') #Generate Case Information self.create_case(caseDir) self.evtLogger.logEvent(self, 'Successfully Created New Case') else: #Case exists. Use Open Case Folder instead... self.evtLogger.logEvent(self, 'Case Already Exists!! Open Case Folder Instead!', True) def open_case_folder(self): ''' Function to open case from an already extracted Andriod backup. User must point application to Case Directory. ''' #get the directory path to the case directory dirname = tkFileDialog.askdirectory(initialdir=os.getcwd(), title="Select the Case Folder you wish to open.") #check that directory was specified if dirname != '': self.evtLogger.logEvent(self, "Opening Case Folder: "+dirname) #Generate Case Information self.create_case(dirname) self.evtLogger.logEvent(self, 'Successfully Opened Case') def create_case(self, dirname): ''' Function to parse the upsight information from an extracted Andriod backup. @dirname: Path to the case directory. ''' #Initalize the StaticMaps Object self.caseDir = dirname self.sm = sm.StaticMaps(googleAPI, os.path.join(self.caseDir, 'maps'), '1200x1000', '1', 'gif') dirname = os.path.join(dirname, 'apps', 'com.nianticlabs.pokemongo') #check if PokemonGo exists if os.path.isdir(dirname) is not True: self.evtLogger.logEvent(self, "PokemonGo Application not detected!", True) else: #Build File Tree View self.add_item(dirname) #Basic Processing -> need to parse information from upsight.xml and update overview tab upsight = os.path.join(dirname, 'sp', 'upsight.xml') if os.path.isfile(upsight): tree = ET.parse(upsight) root = tree.getroot() sessInfo = {} for child in root: if child.tag != 'string': sessInfo[child.attrib['name']] = child.attrib['value'] #collect information from sqlite database upsightDB = os.path.join(dirname, 'db', 'upsight.db') if os.path.isfile(upsightDB): conn = sqlite3.connect(upsightDB) c = conn.cursor() c.execute("SELECT data FROM models WHERE type = 'upsight.model.location'") data = c.fetchone() if data != None: j = json.loads(data[0]) sessInfo['latitude'] = j['latitude'] sessInfo['longitude'] = j['longitude'] else: self.evtLogger.logEvent(self, "No GPS information within Upsight Database Found!", True) sessInfo['latitude'] = None conn.close() else: sessInfo['latitude'] = None self.evtLogger.logEvent(self, "com.nianticlabs.pokemongo\\db\\upsight.db Not Found!", True) else: self.evtLogger.logEvent(self, "com.nianticlabs.pokemongo\\sp\\upsight.xml Not Found!", True) self.ovrViewFrame = Frame(self.nb, name="overview") ########################################## # Display Last Known Session Information # ########################################## self.LastKnownSessionLbl = Label(self.ovrViewFrame, text="Last Known Session Information", font="TkDefaultFont 12 bold") self.LastKnownSessionLbl.grid(row=0, column=0, columnspan=3, sticky='nw', pady=2, padx=2) #Session Number self.SessionNumLbl = Label(self.ovrViewFrame, text="Session Number: ", font="TkDefaultFont 10 bold") self.SessionNumLbl.grid(row=1, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.SessionNumVal = Label(self.ovrViewFrame, text=sessInfo['session_num'], font="TkDefaultFont 10") self.SessionNumVal.grid(row=1, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Current Session Duration self.SessionDurLbl = Label(self.ovrViewFrame, text="Session Duration: ", font="TkDefaultFont 10 bold") self.SessionDurLbl.grid(row=2, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.SessionDurVal = Label(self.ovrViewFrame, text=sessInfo['current_session_duration'], font="TkDefaultFont 10") self.SessionDurVal.grid(row=2, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Session Start Time self.SessionStartLbl = Label(self.ovrViewFrame, text="Session Start Time: ", font="TkDefaultFont 10 bold") self.SessionStartLbl.grid(row=3, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.SessionStartVal = Label(self.ovrViewFrame, text=time.strftime('%m-%d-%Y %H:%M:%S', time.localtime(float(sessInfo['session_start_ts']))), font="TkDefaultFont 10" ) self.SessionStartVal.grid(row=3, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Session End Time self.SessionEndLbl = Label(self.ovrViewFrame, text="Session End Time: ", font="TkDefaultFont 10 bold") self.SessionEndLbl.grid(row=4, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.SessionEndVal = Label(self.ovrViewFrame, text=time.strftime('%m-%d-%Y %H:%M:%S', time.localtime(float(sessInfo['last_known_session_time']))), font="TkDefaultFont 10") self.SessionEndVal.grid(row=4, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Past Session Time self.PastSessTimeLbl = Label(self.ovrViewFrame, text="Past Session Time: ", font="TkDefaultFont 10 bold") self.PastSessTimeLbl.grid(row=5, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.PastSessTimeVal = Label(self.ovrViewFrame, text=sessInfo['past_session_time'], font="TkDefaultFont 10") self.PastSessTimeVal.grid(row=5, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Sequence ID self.SeqIDLbl = Label(self.ovrViewFrame, text="Sequence ID: ", font="TkDefaultFont 10 bold") self.SeqIDLbl.grid(row=6, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.SeqIDVal = Label(self.ovrViewFrame, text=sessInfo['seq_id'], font="TkDefaultFont 10") self.SeqIDVal.grid(row=6, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Install Timestampe self.InstallTSLbl = Label(self.ovrViewFrame, text="Install Time: ", font="TkDefaultFont 10 bold") self.InstallTSLbl.grid(row=7, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.InstallTSVal = Label(self.ovrViewFrame, text=time.strftime('%m-%d-%Y %H:%M:%S', time.localtime(float(sessInfo['install_ts']))), font="TkDefaultFont 10" ) self.InstallTSVal.grid(row=7, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Player XP self.PlayerXPLbl = Label(self.ovrViewFrame, text="Player XP: ", font='TkDefaultFont 10 bold') self.PlayerXPLbl.grid(row=8, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.PlayerXPVal = Label(self.ovrViewFrame, text=sessInfo['com.upsight.user_attribute.player_xp'], font='TkDefaultFont 10') self.PlayerXPVal.grid(row=8, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Player Avatar self.PlayerAvatarLbl = Label(self.ovrViewFrame, text="Player Avatar: ", font='TkDefaultFont 10 bold') self.PlayerAvatarLbl.grid(row=9, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.PlayerAvatarVal = Label(self.ovrViewFrame, text=sessInfo['com.upsight.user_attribute.player_avatar'], font='TkDefaultFont 10') self.PlayerAvatarVal.grid(row=9, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Item count self.ItemCntLbl = Label(self.ovrViewFrame, text="Item Count: ", font='TkDefaultFont 10 bold') self.ItemCntLbl.grid(row=10, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.ItemCntVal = Label(self.ovrViewFrame, text=sessInfo['com.upsight.user_attribute.item_count'], font='TkDefaultFont 10') self.ItemCntVal.grid(row=10, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Pokemon Count self.PokemonCntLbl = Label(self.ovrViewFrame, text="Pokemon Count: ", font='TkDefaultFont 10 bold') self.PokemonCntLbl.grid(row=11, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.PokemonCntVal = Label(self.ovrViewFrame, text=sessInfo['com.upsight.user_attribute.pokemon_count'], font='TkDefaultFont 10') self.PokemonCntVal.grid(row=11, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #Player Level self.PlayerLevelLbl = Label(self.ovrViewFrame, text="Player Level: ", font='TkDefaultFont 10 bold') self.PlayerLevelLbl.grid(row=12, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.PlayerLevelVal = Label(self.ovrViewFrame, text=sessInfo['com.upsight.user_attribute.player_level'], font='TkDefaultFont 10') self.PlayerLevelVal.grid(row=12, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #lastPushTokenRegistrationTime #check to see if file exists registration = os.path.join(dirname, 'sp', 'com.upsight.android.googleadvertisingid.internal.registration.xml') if os.path.isfile(registration): tree = ET.parse(registration) root = tree.getroot() for child in root: if child.tag != 'string': sessInfo[child.attrib['name']] = child.attrib['value'] self.evtLogger.logEvent(self, 'Found lastPushTokenRegistrationTime.') #Display results self.LastPushLbl = Label(self.ovrViewFrame, text="lastPushTokenRegistrationTime: ", font='TkDefaultFont 10 bold') self.LastPushLbl.grid(row=13, column=0, columnspan=2, sticky='nw', pady=2, padx=2) self.LastPushVal = Label(self.ovrViewFrame, text=time.strftime('%m-%d-%Y %H:%M:%S', time.localtime(float(sessInfo['lastPushTokenRegistrationTime']))), font="TkDefaultFont 10" ) self.LastPushVal.grid(row=13, column=2, columnspan=2, sticky='nw', pady=2, padx=2) else: self.evtLogger.logEvent(self, registration+' not found!', True) #Upsight.db Cords self.GPSCordsLbl = Label(self.ovrViewFrame, text="Relative GPS Cords: ", font='TkDefaultFont 10 bold') self.GPSCordsLbl.grid(row=14, column=0, columnspan=2, sticky='nw', pady=2, padx=2) #check if upsight cords were found if sessInfo['latitude'] == None: self.GPSCordsVal = Label(self.ovrViewFrame, text='') else: self.GPSCordsVal = Label(self.ovrViewFrame, text="("+str(sessInfo['latitude'])+", "+str(sessInfo['longitude'])+")", font='TkDefaultFont 10') #Create Button to display cords on a map. self.DisplayCordsBtn = Button(self.ovrViewFrame, text="Map Cords", command= lambda: self.onClickMapCords(sessInfo['latitude'], sessInfo['longitude'])) self.DisplayCordsBtn.grid(row=14, column=5, sticky='nsew', pady=2, padx=2) self.GPSCordsVal.grid(row=14, column=2, columnspan=2, sticky='nw', pady=2, padx=2) #check if crittercism logs exist if os.path.exists(os.path.join(dirname, 'f', 'com.crittercism')): #Crittercism Logs Label self.CrittercismLogsLbl = Label(self.ovrViewFrame, text='Crittercism Logs Detected', font='TkDefaultFont 10 bold') self.CrittercismLogsLbl.grid(row=15, column=0, columnspan=2, sticky='nw', pady=2, padx=2) #Crittercism Logs Button self.CrittercismLogsBtn = Button(self.ovrViewFrame, text='Map Logs', command=self.mapCrittercismLogs) self.CrittercismLogsBtn.grid(row=15, column=2, columnspan=2, sticky='nw', pady=2, padx=2) else: self.evtLogger.logEvent(self, 'Crittercism Logs not detected.') #Account Name prefs = os.path.join(dirname, 'sp', 'com.nianticlabs.pokemongo.PREFS.xml') if os.path.isfile(prefs): tree = ET.parse(prefs) root = tree.getroot() for child in root: if child.attrib['name'] == 'accountName': sessInfo['accountName'] = child.text #display results self.AccountNameLbl = Label(self.ovrViewFrame, text='Account Name: ', font='TkDefaultFont 10 bold') self.AccountNameLbl.grid(row=19, column=0, columnspan=2, sticky='nw', padx=2, pady=2) self.AccountNameVal = Label(self.ovrViewFrame, text=sessInfo['accountName'], font='TkDefaultFont 10') self.AccountNameVal.grid(row=19, column=2, columnspan=2, sticky='nw', padx=2, pady=2) self.evtLogger.logEvent(self, 'Found Account Name!') else: self.evtLogger.logEvent(self, prefs+' not found!', True) self.ovrViewFrame.grid(row=5, column=0, columnspan=2, sticky='new') #add overview frame to notebook view self.nb.add(self.ovrViewFrame, text="Overview") #select current tab self.selectCurrentTab()
class Note(Toplevel): """ Display select Note """ def __init__(self, window=None): Toplevel.__init__(self, window=None) self.background = PhotoImage(file='Image/note_bg1.gif') self.image = PhotoImage(file='Image/favorite2.gif') self.window = window def my_note(self, title): """Main UI for note""" data = get_data()[title] data = get_data()[title] self.bg = Label(self, image=self.background) self.title = Label(self, text=title, fg='#f46b2f', bg='#efe9dc', font=('AngsanaUPC', 18, 'bold')) self.txt = ScrolledText(self, width=44, height=13, bg='#efe9dc',\ font=('AngsanaUPC', 14), relief=FLAT) self.txt.insert('1.0', data[0]) self.txt.config(state='disable') self.ok = Button(self, text='Ok', bg='white', relief=FLAT, width=13, font=('Arial', 10, 'bold'), command=lambda title=title: self.check_edit(title), activebackground='#3FBB06') self.delete = Button(self, text='Delete', bg='white', relief=FLAT, width=13, font=('Arial', 10, 'bold'), activebackground='#C62F2F', command=lambda title=title: self.delete_select(title)) self.edit = Button(self, text='Edit', bg='white', font=('Arial', 10, 'bold'), activebackground='#747474', command=self.make_edit, relief=FLAT, width=14) self.ok.bind("<Enter>", self.button_ok1) self.ok.bind("<Leave>", self.button_ok2) self.delete.bind("<Enter>", self.button_delete1) self.delete.bind("<Leave>", self.button_delete2) self.edit.bind("<Enter>", self.button_edit1) self.edit.bind("<Leave>", self.button_edit2) self.bg.place(x=-2, y=0) self.title.place(x=30, y=50) self.ok.place(x=236, y=472) self.delete.place(x=0, y=472) self.txt.place(x=25, y=100) self.edit.place(x=114, y=472) if data[2] == '1': self.favor = Label(self, image=self.image, bg='#efe9dc') self.favor.place(x=266, y=40) def delete_select(self, title): """Delete data and destroy current window""" ask = tkMessageBox.askquestion("Delete", "Are you sure?", icon="warning") if ask == 'yes': delete_data(title) self.destroy() if self.window != None: self.window.destroy() note_store = NoteStorage() note_store.geometry('450x600+450+90') note_store.title('Note Storage') note_store.resizable(width=False, height=False) note_store.all_note() def check_edit(self, title): """replace text if text have change else destroy current page""" old = get_data()[title][0].splitlines() new = self.txt.get('1.0', END).splitlines() star = get_data()[title][2] for i in new: if i == '': new.remove(i) if new != old: tkMessageBox.showinfo('Status', 'Complete') add_data(title, self.txt.get('1.0', END), date(), star) self.destroy() if self.window != None: self.window.destroy() note_store = NoteStorage() note_store.geometry('450x600+450+90') note_store.title('Note Storage') note_store.resizable(width=False, height=False) note_store.all_note() else: self.destroy() def button_ok1(self, event): """Event button when press""" self.ok.config(relief=GROOVE, bg='#44D002') self.edit.config(bg='#44D002') self.delete.config(bg='#44D002') def button_ok2(self, event): """Event button when release""" self.ok.config(relief=FLAT, bg='white') self.edit.config(bg='white') self.delete.config(bg='white') def button_delete1(self, event): """Event ok button when press""" self.delete.config(relief=GROOVE, bg='#FF2828') self.ok.config(bg='#FF2828') self.edit.config(bg='#FF2828') def button_delete2(self, event): """Event button when release""" self.delete.config(relief=FLAT, bg='white') self.ok.config(bg='white') self.edit.config(bg='white') def button_edit1(self, event): """Event ok button when press""" self.delete.config(bg='#AFAFAF') self.ok.config(bg='#AFAFAF') self.edit.config(bg='#AFAFAF', relief=GROOVE) def button_edit2(self, event): """Event button when release""" self.delete.config(bg='white') self.ok.config(bg='white') self.edit.config(relief=FLAT, bg='white') def make_edit(self): """config text widget""" self.txt.config(state='normal')
class ViewportCard(object): """ Manages the graphical representation of a card in a Tkinter canvas. Creates and destroys items as necessary, facilitates editing, and so on and so forth. Members: * card: model.Card * viewport: GPViewport * gpfile: gpfile.GraphPaperFile, contains model.graph() * canvas: TKinter canvas we get drawn on * editing: bool, text is being edited * moving: bool, being dragged * moving_edgescroll_id: callback id to scroll periodically when hovering near edge of screen * resize_state: {} * resize_edgescroll_id: as moving_edgescroll_id * slot: calls callbacks whenever geometry changes * new_edge: if an edge is being dragged out from a handle, this is it. * card_after_new_edge: bool, if we should make a new card when edge is dropped. """ def __init__(self, viewport, gpfile, card): self.card = card self.viewport = viewport self.gpfile = gpfile self.canvas = viewport.canvas self.draw() self.editing = False self.moving = False self.moving_edgescroll_id = None self.resize_state = None self.resize_edgescroll_id = None # slot triggered when geometry (pos/size) changes # fn args: (self, x, y, w, h) self.geom_slot = Slot() self.deletion_slot = Slot() self.new_edge = None def draw(self): self.frame_thickness = 5 self.window = ResizableCanvasFrame( self.canvas, self.card.x, self.card.y, self.card.w, self.card.h, min_width=MIN_CARD_SIZE, min_height=MIN_CARD_SIZE, ) self.text = ScrolledText(self.window, wrap=WORD) self.text.pack(expand=1, fill="both") # set up text for editing, dragging, deleting self.text.bind("<Button-1>", self.mousedown) self.text.bind("<Shift-Button-1>", self.shiftmousedown) self.text.bind("<Double-Button-1>", self.doubleclick) self.text.bind("<B1-Motion>", self.mousemove) self.text.bind("<ButtonRelease-1>", self.mouseup) self.text.bind("<FocusIn>", self.focusin) self.text.bind("<FocusOut>", self.focusout) self.text.bind("<Control-Delete>", self.ctrldelete) self.text.insert(END, self.card.text) # set up frame for resizing self.window.bind("<Configure>", self.configure) self.window.save_callback = self.save_card # draw edge handles self.edge_handles = None # self.redraw_edge_handles() def redraw_edge_handles(self): """ Either creates or modifies the edge handles, little circles poking out the side of the card, based on the current position and width. self.edge_handles is a list of itemids of the circles in (top, right, bottom, left) order. """ def create_circle(bbox): # create circle suitable for edge-handle use new = self.canvas.create_oval(bbox[0], bbox[1], bbox[2], bbox[3], fill="green", outline="") self.canvas.addtag_withtag("card_handle_tag", new) # for z-ordering self.canvas.tag_bind(new, "<Button-1>", self.handle_click) self.canvas.tag_bind(new, "<Shift-Button-1>", self.handle_shift_click) self.canvas.tag_bind(new, "<B1-Motion>", self.handle_mousemove) self.canvas.tag_bind(new, "<ButtonRelease-1>", self.handle_mouseup) return new x, y = self.window.canvas_coords() w, h = self.window.winfo_width(), self.window.winfo_height() # 2*radius should be < MIN_CARD_SIZE, and offset < radius radius = 30 offset = 19 # offset of center of circle from card edge left_coords = (x + offset, y + h / 2) right_coords = (x + w - offset, y + h / 2) top_coords = (x + w / 2, y + offset) bottom_coords = (x + w / 2, y + h - offset) all_coords = (top_coords, right_coords, bottom_coords, left_coords) bboxes = [(x - radius, y - radius, x + radius, y + radius) for x, y in all_coords] if self.edge_handles: # move the edge handles for i, box in enumerate(bboxes): # self.canvas.coords(handle, box[0], box[1], box[2], box[3]) self.canvas.delete(self.edge_handles[i]) self.edge_handles[i] = create_circle(box) # self.canvas.itemconfig(handle, bbox = box) else: # create new ones self.edge_handles = [create_circle(b) for b in bboxes] # have to do this every time, every time we recreate the edge handles self.viewport.fix_z_order() def get_text(self): "gets the text from the actual editor, which may not be saved yet" return self.text.get("0.0", END) def save_text(self): # get text from window text = self.get_text() if text != self.card.text: self.card.text = text self.gpfile.commit() def canvas_coords(self): return self.window.canvas_coords() def start_moving(self, event): # set up state for a drag self.moving = True self.foocoords = (event.x, event.y) self.set_moving_edgescroll_callback() def edge_scroll(self): # if any edges are too close to the edge, move and scroll the canvas canvas_coords = self.canvas_coords() relative_mouse_pos = self.foocoords canvas_mouse_coords = ( canvas_coords[0] + relative_mouse_pos[0] + self.frame_thickness, canvas_coords[1] + relative_mouse_pos[1] + self.frame_thickness, ) scroll_x, scroll_y = self.viewport.edge_scroll(canvas_mouse_coords) # move the opposite direction the viewport scrolled scroll_x, scroll_y = -scroll_x, -scroll_y # print 'card.edgescroll x y', scroll_x, scroll_y, 'relative_mouse_pos', relative_mouse_pos self.window.move(scroll_x, scroll_y) self.viewport.reset_scroll_region() self.set_moving_edgescroll_callback() def set_moving_edgescroll_callback(self): self.moving_edgescroll_id = self.text.after(10, self.edge_scroll) def cancel_moving_edgescroll_callback(self): self.text.after_cancel(self.moving_edgescroll_id) self.moving_edgescroll_id = None def mousedown(self, event): self.window.lift() def doubleclick(self, event): self.start_moving(event) return "break" def shiftmousedown(self, event): self.mousedown(event) self.start_moving(event) return "break" def mousemove(self, event): if self.moving: # coords are relative to card, not canvas if self.foocoords: delta = (event.x - self.foocoords[0], event.y - self.foocoords[1]) else: delta = (event.x, event.y) self.window.move(delta[0], delta[1]) self.geometry_callback() self.viewport.reset_scroll_region() return "break" def mouseup(self, event): if self.moving: self.moving = False new_coords = self.canvas_coords() self.card.x, self.card.y = new_coords[0], new_coords[1] self.gpfile.commit() self.cancel_moving_edgescroll_callback() self.geometry_callback() # next several functions are bound to the circular edge handles def handle_click(self, event): # create new edge self.new_edge = ViewportEdge(self.viewport, self.gpfile, None, self, None) self.new_edge.mousemove(event) # give it a real start pos def handle_shift_click(self, event): self.handle_click(event) self.new_edge.make_new_card = True def handle_mousemove(self, event): if self.new_edge: self.new_edge.mousemove(event) def handle_mouseup(self, event): if self.new_edge: self.new_edge.mouseup(event) self.new_edge = None def configure(self, event): self.redraw_edge_handles() def focusin(self, event): self.editing = True def focusout(self, event): self.editing = False self.save_text() def ctrldelete(self, event): title_sample = self.get_text().split("\n", 1)[0] if len(title_sample) > 20: title_sample = title_sample[:20] + "..." # delete the card if tkMessageBox.askokcancel("Delete?", 'Delete card "%s" and all its edges?' % title_sample): for handle in self.edge_handles: self.canvas.delete(handle) self.deletion_slot.signal() self.viewport.remove_card(self) self.card.delete() self.window.destroy() self.gpfile.commit() return "break" def save_card(self): # grab values from self.window, # and put them in the model.card self.card.x, self.card.y = self.window.canvas_coords() self.card.w, self.card.h = self.window.winfo_width(), self.window.winfo_height() self.geometry_callback() # here so it gets called after resizing self.gpfile.commit() def add_geom_signal(self, fn): return self.geom_slot.add(fn) def remove_geom_signal(self, handle): self.geom_slot.remove(handle) def add_deletion_signal(self, fn): return self.deletion_slot.add(fn) def remove_deletion_signal(self, handle): self.deletion_slot.remove(handle) def geometry_callback(self): x, y = self.canvas_coords() w, h = self.window.winfo_width(), self.window.winfo_height() self.geom_slot.signal(self, x, y, w, h) def highlight(self): self.text.config(background="#ffffa2") def unhighlight(self): self.text.config(background="white")
text.insert(INSERT,results) text.configure(state="disabled") root = Tk() root.configure(background='teal') root.title("Syntactic Textual Similarity") root.resizable(width=False, height=False) note = Notebook(root) frame = Frame(root) queryvar = StringVar() ql = StringVar() frame.grid(row=4,column=0,rowspan=12,columnspan=3,pady=20) text = ScrolledText(frame,wrap="word") text.grid(row=4) text.config(font=("Courier", 12)) text.configure(background='black',foreground='green') directory = StringVar() filename = StringVar() sent1 = StringVar() sent2 = StringVar() status = StringVar() modelnum = StringVar() status.set("") filename.set("") Label(root,textvariable=status,bg='teal',foreground='white').grid(row=0,column=1,padx=(20),pady=(20),columnspan=6) Label(root,text="Directory:",bg='teal',foreground='white').grid(row=2,column=0,padx=(10),pady=(10)) Entry(root,text=directory,bd=2,bg='#cfacaf',width='75').grid(row=2,column=1) Button(root,command=browseDestDir,text='Browse').grid(row=2,column=2,padx=20)
class App: def __init__(self, master): self.master = master self.btnUpPressed = False self.btnDownPressed = False self.btnLeftPressed = False self.btnRightPressed = False self.btnPlusPressed = False self.btnMinusPressed = False #keyListener aanzetten master.bind("<Key>", self.keyPressed) master.bind("<KeyRelease>", self.keyReleased) labelFont = tkFont.Font(size = 16) #TOPFRAME: 800x400 topFrame = Frame(master, width=800,height=400, bg = "blue") topFrame.pack(padx=10, pady=10, side = TOP) leftTopFrame = Frame(topFrame, bg = "blue") leftTopFrame.grid(row = 0, column = 0) rightTopFrame = Frame(topFrame, bg = "blue") rightTopFrame.grid(row = 0, column = 2) middleTopFrame = Frame(topFrame, bg = "blue") middleTopFrame.grid(row = 0, column = 1, padx = 10) #BOTTOMFRAME: 800X200 bottomFrame = Frame(master, width=800,height=200, bg = "blue") bottomFrame.pack(padx=20, pady=10, side = BOTTOM) leftBottomFrame = Frame(bottomFrame, bg = "blue") leftBottomFrame.pack(side = LEFT) rightBottomFrame = Frame(bottomFrame, bg = "blue") rightBottomFrame.pack(side = RIGHT) leftRightBottomFrame = Frame(rightBottomFrame, bg = "blue") leftRightBottomFrame.pack(padx = 30, side = LEFT) rightRightBottomFrame = Frame(rightBottomFrame, bg = "blue") rightRightBottomFrame.pack(side = RIGHT) """ topFrame decoreren """ #Scrolledtext in leftTopFrame self.scrDebug = ScrolledText(leftTopFrame, wrap = WORD, state = "disabled", fg = "green", width=65) self.scrDebug.pack(fill=NONE, expand=False) #Tekst in rightTopFrame self.lblLaatstGenomen = Label(rightTopFrame, text="Laatst genomen foto:", bg = "gray55", fg = "white") self.lblLaatstGenomen.pack() #Image in rightTopFrame self.location = "../latestPicture.gif" self.laatstGenomen = PhotoImage(file="../default.gif") self.lblFotoLaatstGenomen = Label(rightTopFrame, image=self.laatstGenomen) #self.lblFotoLaatstGenomen.image = self.laatstGenomen self.lblFotoLaatstGenomen.pack(fill = BOTH, expand = "yes") #Vertaling in rightTopFrame self.vertalingString = StringVar() self.vertalingString.set("Vertaling QR-code: ") self.lblVertaling = Label(rightTopFrame, textvariable = self.vertalingString, bg = "gray55", fg = "white") self.lblVertaling.pack() self.btnMaakFoto = Button(rightTopFrame, text = "Maak Foto", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = self.makePicture) self.btnMaakFoto.pack() #motor info in middleTopFrame self.lblmotorUpString = Label(middleTopFrame, text = "MOTOR U: " , bg = "blue", fg = "red", font = labelFont) self.lblmotorUpString.grid(row = 0, column = 0) self.lblmotorLeftString = Label(middleTopFrame, text = "MOTOR L: " , bg = "blue", fg = "red", font = labelFont) self.lblmotorLeftString.grid(row = 1, column = 0) self.lblmotorRightString = Label(middleTopFrame, text = "MOTOR R: " , bg = "blue", fg = "red", font = labelFont) self.lblmotorRightString.grid(row = 2, column = 0) self.lblmotorPWMString = Label(middleTopFrame, text = "PWM U: " , bg = "blue", fg = "white", font = labelFont) self.lblmotorPWMString.grid(row = 3, column = 0) self.motorLeftString = StringVar() self.motorLeftString.set("S") self.motorRightString = StringVar() self.motorRightString.set("S") self.motorUpString = StringVar() self.motorUpString.set("S") self.motorPWMString = StringVar() self.motorPWMString.set("100") self.lblmotorUpStringValue = Label(middleTopFrame, textvariable = self.motorUpString, fg = "red", bg = "blue", width = 5, font = labelFont) self.lblmotorUpStringValue.grid(row = 0, column = 1) self.lblmotorLeftStringValue = Label(middleTopFrame, textvariable = self.motorLeftString, fg = "red", bg = "blue", width = 5, font = labelFont) self.lblmotorLeftStringValue.grid(row = 1, column = 1) self.lblmotorRightStringValue = Label(middleTopFrame, textvariable = self.motorRightString, fg = "red", bg = "blue", width = 5, font = labelFont) self.lblmotorRightStringValue.grid(row = 2, column = 1) self.motorPWMStringValue = Label(middleTopFrame, textvariable = self.motorPWMString, fg = "white", bg = "blue", width = 5, font = labelFont) self.motorPWMStringValue.grid(row = 3, column = 1) """ bottomFrame decoreren to do: enum """ #Besturingsknoppen draaien in leftBottomFrame self.btnLeft = Button(leftBottomFrame, text="Links", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveLeft()) self.btnLeft.grid(row=1, column=0) self.btnRight = Button(leftBottomFrame, text="Rechts", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveRight()) self.btnRight.grid(row=1, column=2) self.btnForward = Button(leftBottomFrame, text="Vooruit", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveForward()) self.btnForward.grid(row=0, column=1) self.btnBackward = Button(leftBottomFrame, text="Achteruit", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveBackward()) self.btnBackward.grid(row=1, column=1) #Besturingsknoppen stijgen en dalen in middleBottomFrame self.btnUp = Button(leftRightBottomFrame, text="Omhoog", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveUp()) self.btnUp.grid(row=0, column=0) self.btnDown = Button(leftRightBottomFrame, text="Omlaag", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", height=3, width=10, command = lambda: self.moveDown()) self.btnDown.grid(row=1, column=0) self.lastCommandoString = "" #Hoogte informatie in RightBottomFrame self.gewensteHoogteString = StringVar() self.gewensteHoogteString.set(str(neededHeight)) self.lblGewensteHoogte = Label(rightRightBottomFrame, text = "Gewenste Hoogte: ", anchor = "w", bg = "gray55", fg = "white") self.lblGewensteHoogteVar = Label(rightRightBottomFrame, textvariable = self.gewensteHoogteString, width = 20, fg = "green") self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(realHeight)) self.lblGemetenHoogte = Label(rightRightBottomFrame, text="Gemeten Hoogte: ", anchor = "w", bg = "gray55", fg = "white") self.lblGemetenHoogteVar = Label(rightRightBottomFrame, textvariable = self.gemetenHoogteString, width = 20, fg = "green") self.lblGewensteHoogte.grid(row=1, column=0) self.lblGewensteHoogteVar.grid(row=1, column=1) self.lblGemetenHoogte.grid(row=0, column=0) self.lblGemetenHoogteVar.grid(row=0, column=1) self.btnHeight = Button(rightRightBottomFrame, text="Kies hoogte", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.setGewensteHoogte()) self.btnHeight.grid(row=2,column=0) self.txtHeight = Entry(rightRightBottomFrame, width=24, fg = "green") self.txtHeight.grid(row=2, column=1) self.txtHeight.bind('<Return>', self.setGewensteHoogte) self.btnPWM = Button(rightRightBottomFrame, text="Kies PWM", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.setPWM()) self.btnPWM.grid(row=2,column=2) self.txtPWM = Entry(rightRightBottomFrame, width = 24, fg = "green") self.txtPWM.grid(row=2, column = 3) self.txtPWM.bind('<Return>', self.setPWM) self.btnLand = Button(rightRightBottomFrame, text = "Landen", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", width = 14, command = self.landen) self.btnLand.grid(pady=5,row=3, column = 0) self.btnHorizontalOff = Button(rightRightBottomFrame, text = "Horizontale motors af", bg = "green", fg = "white", activebackground = "orange red", activeforeground = "white", command = self.horizontalOff) self.btnHorizontalOff.grid(pady=5,row=3, column = 1) self.correctieFlag = False self.automaticFlag = False self.btnAutomaticPilot = Button(rightRightBottomFrame, text = "Auto-pilot", bg = "green", fg = "white",activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.toggleAutomaticPilot()) self.btnAutomaticPilot.grid(row = 0, column = 2) self.btnCorrectie = Button(rightRightBottomFrame, text ="Hoogte correctie", bg ="green", fg ="white", activebackground = "orange red", activeforeground = "white", width = 14, command = lambda: self.toggleHeightCorrection()) self.btnCorrectie.grid(row = 1, column = 2) self.btnConnect = Button(rightRightBottomFrame, text = "Verbind", bg = "green", fg = "white", activebackground = "orange red", width = 14, activeforeground = "white", command = lambda: self.createClient()) self.btnConnect.grid(row = 3, column = 2) self.connectedString = StringVar() self.connectedString.set("Niet verbonden") self.lblConnected = Label(rightRightBottomFrame, textvariable = self.connectedString, fg = "red", bg = "blue", font = tkFont.Font(size = 14)) self.lblConnected.grid(row = 3, column = 3) self.createClient() #gewenste hoogte aanpassen def setGewensteHoogte(self, event = None): x = self.txtHeight.get() self.txtHeight.delete(0, END) self.master.focus() try: x = float(x) except: return if isinstance(x, float) and x > 0.0 and x < 1000.0: global neededHeight neededHeight = x message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd" self.debugPrint(message) self.gewensteHoogteString.set(str(neededHeight)) self.client.setHeight(x) if not self.correctieFlag: self.toggleHeightCorrection() def toggleAutomaticPilot(self): if not self.connected: return self.debugPrint("Automatische piloot toggle aangevraagd") self.client.toggleAutomaticPilot() def createClient(self): try: self.client = cl(self) self.connected = True self.connectedString.set("Verbonden") self.lblConnected.config(fg = "green") self.debugPrint("Verbonden met Raspberry Pi") except: self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n -Staat de Raspberry Pi aan?\n -Staat de server aan?\n -Zit deze computer op de ad-hoc?") def disconnect(self): self.connected = False self.connectedString.set("Niet verbonden") self.lblConnected.config(fg = "red") #PWM aanpassen def setPWM(self, event = None): x = self.txtPWM.get() self.txtPWM.delete(0, END) self.master.focus() try: x = int(x) except: return try: if not self.connected: return message = "PWM instellen op " + str(x) + " aangevraagd" self.debugPrint(message) self.client.setPower(x) except TypeError: return #automatische hooogte correctie toggelen def toggleHeightCorrection(self): if not self.connected or self.automaticFlag: return self.debugPrint("Automatische hoogte regeling toggle aangevraagd") self.client.toggleHeightCorrection() # #make picture # def makePicture(self): # if not self.connected: # return # decodation = self.client.fetchImage(self.location) # self.laatstGenomen2 = PhotoImage(file=self.location) # self.lblFotoLaatstGenomen.configure(image = self.laatstGenomen2) # self.vertalingString.set("VERTALING: " + str(decodation)) #make picture def makePicture(self): if not self.connected: return decodation = self.client.fetchImage("latestPicture.jpg") #tekst weergeven in debug venster def debugPrint(self, tekst): self.scrDebug.config(state = "normal") self.scrDebug.insert(END, ">> " + tekst + "\n") self.scrDebug.config(state = "disabled") self.scrDebug.yview_pickplace("end") def moveForward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Voorwaarts vliegen aangevraagd") self.client.flyForward() def moveBackward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Achterwaarts vliegen aangevraagd") self.client.flyBackward() def moveLeft(self): if not self.connected or self.automaticFlag: return self.debugPrint("Links draaien aangevraagd") self.client.turnLeft() def moveRight(self): if not self.connected or self.automaticFlag: return self.debugPrint("Rechts draaien aangevraagd") self.client.turnRight() def moveUp(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omhoog vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpBackward() def moveDown(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omlaag vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpForward() def landen(self): if not self.connected or self.automaticFlag: return self.debugPrint("Landen aangevraagd") self.client.stopAllMotors() def horizontalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Horizontale motors stoppen aangevraagd") self.client.stopHorizontalMotors() def verticalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Verticale motor stoppen aangevraagd") self.client.motorUpStop() #toetsenbord invoer def keyPressed(self, event): k = event.keysym if k == 'Up': if not self.btnUpPressed: self.btnUpPressed = True self.btnForward.config(bg = "orange red") self.btnForward.invoke() elif k == 'Down': if not self.btnDownPressed: self.btnDownPressed = True self.btnBackward.config(bg = "orange red") self.btnBackward.invoke() elif k == 'Left': if not self.btnLeftPressed: self.btnLeftPressed = True self.btnLeft.config(bg = "orange red") self.btnLeft.invoke() elif k == 'Right': if not self.btnRightPressed: self.btnRightPressed = True self.btnRight.config(bg = "orange red") self.btnRight.invoke() elif k == 'plus': if not self.btnPlusPressed: self.btnPlusPressed = True self.btnUp.config(bg = "orange red") self.btnUp.invoke() elif k == 'minus': if not self.btnMinusPressed: self.btnMinusPressed = True self.btnDown.config(bg = "orange red") self.btnDown.invoke() def keyReleased(self, event): k = event.keysym if k == 'Up': self.btnUpPressed = False self.btnForward.config(bg = "green") self.horizontalOff() elif k == 'Down': self.btnDownPressed = False self.btnBackward.config(bg = "green") self.horizontalOff() elif k == 'Left': self.btnLeftPressed = False self.btnLeft.config(bg = "green") self.horizontalOff() elif k == 'Right': self.btnRightPressed = False self.btnRight.config(bg = "green") self.horizontalOff() elif k == 'plus': self.btnPlusPressed = False self.btnUp.config(bg = "green") self.verticalOff() elif k == 'minus': self.btnMinusPressed = False self.btnDown.config(bg = "green") self.verticalOff() def updateAutomatic(self, info): if info[0]: if not info[1] == "": if not info[1] == self.lastCommandoString: self.lastCommandoString = info[1] self.debugPrint(info[1]) self.vertalingString.set("VERTALING: " + info[2]) with open(self.location, "wb") as handle: handle.write(info[3].data) self.laatstGenomen2 = PhotoImage(file=self.location) self.lblFotoLaatstGenomen.configure(image = self.laatstGenomen2) def updateInfo(self, info): global realHeight if info[0] != -1: self.gemetenHoogteString.set(str(info[0])) self.motorUpString.set(info[1]) if info[1] == "V" or info[1] == "A": self.lblmotorUpString.config(fg = "green") self.lblmotorUpStringValue.config(fg = "green") else: self.lblmotorUpString.config(fg = "red") self.lblmotorUpStringValue.config(fg = "red") self.motorLeftString.set(info[2]) if info[2] == "V" or info[2] == "A": self.lblmotorLeftString.config(fg = "green") self.lblmotorLeftStringValue.config(fg = "green") else: self.lblmotorLeftString.config(fg = "red") self.lblmotorLeftStringValue.config(fg = "red") self.motorRightString.set(info[3]) if info[3] == "V" or info[3] == "A": self.lblmotorRightString.config(fg = "green") self.lblmotorRightStringValue.config(fg = "green") else: self.lblmotorRightString.config(fg = "red") self.lblmotorRightStringValue.config(fg = "red") self.motorPWMString.set(str(math.ceil(info[4]))) self.correctieFlag = info[5] if(not self.correctieFlag): self.btnCorrectie.config(bg = "green") else: self.btnCorrectie.config(bg = "dark green") self.automaticFlag = info[6] if(not self.automaticFlag): self.btnAutomaticPilot.config(bg = "green") else: self.btnAutomaticPilot.config(bg = "dark green")
class LicenseFrame(Frame): """Shows the license agreement and asks the user to accept it in order to proceed. Attributes: parent: A pointer to the parent frame. license_area: The text area that will hold the license. accept_var: This variable contains the integer code that corresponds to the state of the accept_button. accept_button: The Checkbutton used to accept the license terms. next_button: Button to proceed in the installion to the next frame. back_button: Button to return to the WelcomeFrame. """ def __init__(self, parent): Frame.__init__(self, parent) """Inits the frame.""" self.parent = parent self.parent.title("FLE - KA Lite Setup - License") self.loadImages() self.configureLayout() self.drawLayout() def loadImages(self): """Loads the images. The size must be the exact size of the image.""" self.kaliteleaf_photo = PhotoImage(file="images/kaliteleaf.gif", width=16, height=16) def configureLayout(self): """Configures the frame and the components that belong to this frame.""" self.top_frame = Frame(self, relief=RAISED, borderwidth=1) self.tip_label = Label(self.top_frame, text="Please read the license carefully.") self.kaliteleaf_label = Label(self.top_frame, image=self.kaliteleaf_photo, width=16, height=16) self.kaliteleaf_label.image = self.kaliteleaf_photo self.license_area = ScrolledText(self, width=4, height=4, wrap=WORD) self.license_area.insert(INSERT, LICENSE) self.license_area.config(state=DISABLED) self.license_area.focus() self.accept_var = IntVar() self.accept_button = Checkbutton(self, text="I accept the license terms.", variable=self.accept_var, command=self.onCheck) self.next_button = Button(self, text="Next", width=15, height=2, command=self.showServerConfigurationFrame, state=DISABLED) self.back_button = Button(self, text="Back", width=15, height=2, command=self.showWelcomeFrame) def drawLayout(self): """Draws the frame with all the components that were previously configured.""" self.top_frame.pack(fill=X) self.tip_label.pack(fill=X, side=LEFT, padx=5, pady=5) self.kaliteleaf_label.pack(fill=X, side=RIGHT, padx=5, pady=5) self.pack(fill=BOTH, expand=True) self.license_area.pack(fill=BOTH, expand=True) self.accept_button.pack(side=LEFT) self.next_button.pack(side=RIGHT, padx=5, pady=5) self.back_button.pack(side=RIGHT) def onCheck(self): """Enables and disables the button to continue.""" if self.accept_var.get() == 1: self.next_button.config(state=NORMAL) else: self.next_button.config(state=DISABLED) def showWelcomeFrame(self): """Changes the frame to the welcome frame.""" self.pack_forget() self.destroy() WelcomeFrame(self.parent) def showServerConfigurationFrame(self): """Changes to the server configuration frame.""" self.pack_forget() self.destroy() ServerConfigurationFrame(self.parent)
class Interactive(object): def __init__(self): self.printQueue = Queue() # Tkinter components: self.root = Tk() self.root.title = "PGF API App" self.text_box = ScrolledText(self.root) self.runPrintQueue = True self.is_running = False self.prompt_var = StringVar() self.user_input = StringVar() self.of = RediOrderFactory() self.google_sheet = None def gui_start(self): printer_thread = Thread(target=self.queue_printer) printer_thread.daemon = True printer_thread.start() # start printer_thread self.text_box.pack() self.text_box.config(state=DISABLED) user_prompt_entry = Entry(self.root, textvariable=self.prompt_var) user_prompt_entry.pack(fill=BOTH) entry_var = StringVar() entry_box = Entry(self.root, textvariable=entry_var) def enter_pressed(event): print event self.user_input = entry_box.get() self.print_user_input(self.user_input) request_thread = Thread(target=self.process_user_input, args=[entry_box.get()]) # self.process_user_input(entry_box.get()) request_thread.start() entry_box.delete(0, 'end') entry_box.bind("<Return>", enter_pressed) entry_box.pack(fill=BOTH) entry_box.focus_set() self.user_input.set('') mainloop() self.runPrintQueue = False def queue_printer(self): while True: item = self.printQueue.get() self.text_box.config(state=NORMAL) self.text_box.insert(END, item) if isinstance(item, basestring): self.text_box.insert(END, '\n') if isinstance(item, ListType): self.text_box.insert(END, '\n') self.text_box.config(state=DISABLED) self.text_box.see('end') if not self.runPrintQueue: break time.sleep(.1) self.printQueue.task_done() def print_user_input(self, item): self.text_box.config(state=NORMAL) self.text_box.tag_config("b", foreground="blue") self.text_box.insert(END, item, "b") self.text_box.insert(END, '\n') self.text_box.config(state=DISABLED) self.text_box.see('end') def print2(self, txt): print txt self.printQueue.put(txt) def process_user_input(self, ui): # build this one function at a time if ui[:4].upper() == 'ECHO': self.print2(ui[4:]) self.prompt_var.set(ui[4:]) elif ui.upper() == 'QUIT' or ui.upper() == 'Q': self.print2('Breaking out of interactive.') sys.stdout.flush() self.root.quit() return -1 elif ui.upper() == 'LOAD SHEET': self.print2('Called Load Sheet') try: self.google_sheet = gs.GoogleSheetDailyTradingProcedure() self.print2('wait a moment . . . ') sys.stdout.flush() self.google_sheet.load_sheet() self.print2('sheet loaded') except E: self.print2('problem loading sheet' + E) elif ui.upper() == 'PRINT SHEET': if self.google_sheet: for row in self.google_sheet.sheet: self.print2(row) else: self.print2('Load sheet first. (cmd = load sheet)') elif ui.upper()[:10] == 'SUBMIT ROW': row = int(ui.split(' ')[2]) - 1 self.submit_row(row) # submit_row_thread = Thread(target=self.submit_row,args=[row]) # submit_row_thread.start() elif ui.upper() == 'SUBMIT ALL': if self.google_sheet.sheet: i = -1 for _ in self.google_sheet.sheet: i += 1 if i < 2: continue a = self.submit_row(i) if a == 'b': break else: pass elif ui.upper() == 'LOAD ADRS': self.google_sheet = gs.GoogleSheetDailyTradingProcedure() sheet_id = '1Z3POIK8N5Vi_CsF_MDLszrJeNviBwrU9BuVFC8h-xgQ' worksheet_range = 'ADRs Test!A1:F' self.print2('wait a moment') sys.stdout.flush() self.google_sheet.load_sheet(sheet_id, worksheet_range) self.print2('adrs loaded') elif ui.upper()[:14] == 'SUBMIT ADR ROW': r = int(ui.split(' ')[3]) self.submit_our_adr_row(r) self.print2('submit adr row') elif ui.upper() == 'SUBMIT ALL ADRS': if self.google_sheet.sheet: i = -1 for _ in self.google_sheet.sheet: i += 1 if i < 2: continue a = self.submit_our_adr_row(i) if a == 'b': break else: pass self.print2('submit adrs') elif ui.upper() == 'SUBMIT ALL MOCS': if self.google_sheet.sheet: i = -1 for _ in self.google_sheet.sheet: i += 1 if i < 2: continue a = self.submit_our_moc_row(i) if a == 'b': break else: pass elif ui.upper()[:14] == 'SUBMIT MOC ROW': r = int(ui.split(' ')[3]) self.submit_our_moc_row(r) self.print2('submit adr row') elif ui.upper()[:8] == 'STOP ROW': stop_tokens = ui.split(' ') row_num = int(stop_tokens[2]) - 1 row = self.google_sheet.sheet[row_num] if len(stop_tokens) == 4: quantity = int(stop_tokens[3]) else: quantity = int(row[4]) side = 'sell' if (row[3].upper() == 'LONG' or row[3].upper() == 'BUY' or row[3].upper() == 'B') else 'buy' if side == 'sell': quantity *= -1 symbol = row[2].split()[0].upper() stop_price = 0 if len(row) >= 13: stop_price = round(float(row[12]), 2) account = row[1].upper() if side == 'sell': stop_limit = round(stop_price * .99, 2) else: stop_limit = round(stop_price * 1.01, 2) self.of.generate_stop_limit_order(quantity, symbol, stop_price, stop_limit, account) elif ui.upper()[:9] == 'PRINT ROW': if self.google_sheet: tokens = ui.split(' ') self.print2(self.google_sheet.sheet[int(tokens[2]) - 1]) else: self.print2('Load sheet first. (cmd = load sheet)') else: if ui != 'y' and ui != 'n' and ui != 'b': self.print2('Command not understood.') def submit_row(self, r, confirm=True): try: if self.google_sheet: row = self.google_sheet.sheet[r] self.print2(row) sys.stdout.flush() account = row[1].upper() symbol = row[2].split()[0].upper() if symbol == '': return if row[4] == '': self.print2( "Row doesn't have quantity. Enter quantity and reload sheet." ) sys.stdout.flush() return quantity = int(row[4]) side = 'buy' if (row[3].upper() == 'LONG' or row[3].upper() == 'BUY' or row[3].upper() == 'B') else 'sell' if side == 'sell': quantity *= -1 o_type = None if len(row) >= 7: o_type = row[6].upper() price = 0 if len(row) >= 8: if row[7] == '': price = 0 else: price = float( row[7][1:]) if row[7][0] == '$' else float(row[7]) trade_date = None if len(row) >= 9: trade_date = row[8] if str(datetime.datetime.now())[:10] != trade_date: self.print2('Date is not today') sys.stdout.flush() return order_string = '{} {} {} {} {} in {}'.format( side, abs(quantity), symbol, price, o_type, account) if confirm: confirm_msg = '{}? (y/n/b)'.format(order_string) self.user_input = '' self.prompt_var.set(confirm_msg) while self.user_input == '': time.sleep(.1) inp = self.user_input self.prompt_var.set('') else: inp = 'y' if inp == 'y': o = False if o_type == 'MOO': o = self.of.generate_opg_market_order( quantity, symbol, account) elif o_type == 'LOO': o = self.of.generate_opg_limit_order( quantity, symbol, price, account) elif o_type == 'LOC': o = self.of.generate_loc_order(quantity, symbol, price, account) elif o_type == 'MOC': o = self.of.generate_moc_order(quantity, symbol, account) elif o_type == 'LIMIT' or o_type == 'LMT': o = self.of.generate_limit_order( quantity, symbol, price, account) time.sleep(.05) if o: return '1' else: return '0' elif inp == 'b': return 'b' # user requested break else: return inp else: self.print2('Load sheet first. (cmd = load sheet)') sys.stdout.flush() return 'b' except Exception as e: self.print2('row {} failed to submit: {}'.format(r + 1, e)) sys.stdout.flush() def submit_our_adr_row(self, r, confirm=False): try: if self.google_sheet: row = self.google_sheet.sheet[r - 1] self.print2(row) sys.stdout.flush() symbol = row[1].split()[0].upper() if symbol == '': return if row[3] == '': self.print2( "Row doesn't have quantity. Enter quantity and reload sheet." ) sys.stdout.flush() return quantity = int(row[3]) if row[2] == '': return side = 'buy' if (row[2].upper() == 'LONG' or row[2].upper() == 'BUY' or row[2].upper() == 'B') else 'sell' if side == 'sell': quantity *= -1 order_type = None if len(row) >= 6: order_type = row[5].upper() price = 0 if len(row) >= 5: if row[4] == '': price = 0 else: price = float( row[4][1:]) if row[4][0] == '$' else float(row[4]) trade_date = None if len(row) >= 1: trade_date = row[0] if str(datetime.datetime.now())[:10] != trade_date: self.print2('Date is not today') sys.stdout.flush() return order_string = '{} {} {} {} {}'.format(side, abs(quantity), symbol, price, order_type) if confirm: sys.stdout.write('{} {} {} {} {}? (y/n/b)'.format( side, abs(quantity), symbol, price, order_type)) sys.stdout.flush() inp = raw_input() else: inp = 'y' if inp == 'y': o = 0 if order_type == 'MOO': o = self.of.generate_opg_market_order(quantity, symbol) elif order_type == 'LOO': o = self.of.generate_opg_limit_order( quantity, symbol, price) elif order_type == 'LOC': o = self.of.generate_loc_order(quantity, symbol, price) elif order_type == 'MOC': o = self.of.generate_moc_order(quantity, symbol) elif order_type == 'LIMIT' or order_type == 'LMT': o = self.of.generate_limit_order( quantity, symbol, price) if o: return '1' else: return '0' if inp == 'b': return 'b' else: self.print2('order not submitted: {}'.format(order_string)) sys.stdout.flush() return '' else: self.print2('Load sheet first. (cmd = load sheet)') sys.stdout.flush() return 'b' except Exception as e: self.print2('row {} failed to submit: {}'.format(r + 1, e)) sys.stdout.flush() def submit_our_moc_row(self, r, confirm=False): try: if self.google_sheet: row = self.google_sheet.sheet[r - 1] self.print2(row) sys.stdout.flush() symbol = row[1].split()[0].upper() if symbol == '': return if row[3] == '': self.print2( "Row doesn't have quantity. Enter quantity and reload sheet." ) sys.stdout.flush() return quantity = int(row[3]) if row[2] == '': return side = 'sell' if (row[2].upper() == 'LONG' or row[2].upper() == 'BUY' or row[2].upper() == 'B') else 'buy' if side == 'sell': quantity *= -1 order_type = 'MOC' price = 0 order_string = '{} {} {} {} {}'.format(side, abs(quantity), symbol, price, order_type) if confirm: sys.stdout.write('{} {} {} {} {}? (y/n/b)'.format( side, abs(quantity), symbol, price, order_type)) sys.stdout.flush() inp = raw_input() else: inp = 'y' if inp == 'y': o = 0 if order_type == 'MOC': o = self.of.generate_moc_order(quantity, symbol) time.sleep(.05) if o: return '1' else: return '0' if inp == 'b': return 'b' else: self.print2('order not submitted: {}'.format(order_string)) sys.stdout.flush() return '' else: self.print2('Load sheet first. (cmd = load sheet)') sys.stdout.flush() return 'b' except Exception as e: self.print2('row {} failed to submit: {}'.format(r + 1, e)) sys.stdout.flush()
class Dialog(ui.Dialog): def __init__(self, frame=None): self.parent_frame = frame # set the parent frame self.confirm_frame = None self.make_change = False self.new_line = u"" self.status_text = u"" self.make_silent = False self.cancel = False # set screen position... x = 0 y = 0 ##x = config.get('status_x',0) ##y = config.get('status_y',0) ##if x and y: ## self.parent_frame.geometry("+%d+%d" % (int(x),int(y))) # create a status message widget and bind it to the parent... # self.status_text = ScrolledText(self.parent_frame, height=20, width=80, state=DISABLED) # self.status_text.pack() self.status_text = ScrolledText(self.parent_frame, wrap=WORD, pady=2, padx=3, state=DISABLED) self.status_text.pack(fill=BOTH, expand=Y) self.parent_frame.protocol("WM_DELETE_WINDOW", self.destroy) self.parent_frame.bind("<Escape>", self.destroy) self.parent_frame.bind("<Configure>", self.save_pos) self.status_text.update() def confirm_change(self, old_line, new_line, old_tuple=(), new_tuple=(), filepath=""): self.confirm_frame = Tkinter.Toplevel(self.parent_frame, padx=10, pady=10) # self.confirm_frame.grid(padx=10,pady=10) self.confirm_frame.protocol("WM_DELETE_WINDOW", self.confirm_decline) # set screen position... ##x = config.get('dialog_x', (self.parent_frame.winfo_rootx() + 50)) ##y = config.get('dialog_y', (self.parent_frame.winfo_rooty() + 50)) x = self.parent_frame.winfo_rootx() + 50 y = self.parent_frame.winfo_rooty() + 50 if x and y: self.confirm_frame.geometry("+%s+%s" % (x, y)) # bind enter to ok and escape to cancel buttons... self.confirm_frame.bind("<Return>", self.confirm_accept) self.confirm_frame.bind("<Escape>", self.confirm_decline) self.confirm_frame.bind("<Configure>", self.save_pos) # make the new dialog a part of the parent... self.confirm_frame.transient(self.parent_frame) # focus onto the dialog... self.confirm_frame.focus_set() label = Tkinter.Label(self.confirm_frame, text=filepath) label.pack() label = Tkinter.Label(self.confirm_frame, text="Change:") # label.grid(row=row_i, column=0, sticky=W) label.pack() # entry = Tkinter.Text(self.confirm_frame, width=75, height=5) # entry = ScrolledText(self.confirm_frame, width=75, height=5) entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3) entry.insert(Tkinter.INSERT, old_line.encode("utf-8")) # highlight the text to be changed... if len(old_tuple) == 2: entry.tag_add("found", "1.%s" % (old_tuple[0]), "1.%s+%sc" % (old_tuple[0], old_tuple[1] - old_tuple[0])) entry.tag_config("found", foreground="red") entry.config(state=DISABLED) entry.pack(fill=BOTH, expand=Y) label = Tkinter.Label(self.confirm_frame, text="To:") label.pack() self.new_entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3) self.new_entry.insert(Tkinter.INSERT, new_line.encode("utf-8")) # highlight the text to be changed... if len(new_tuple) == 2: self.new_entry.tag_add( "found", "1.%s" % (new_tuple[0]), "1.%s+%sc" % (new_tuple[0], new_tuple[1] - new_tuple[0]) ) self.new_entry.tag_config("found", foreground="red") self.new_entry.config(state=DISABLED) self.new_entry.pack(fill=BOTH, expand=Y) btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes", command=self.confirm_accept, default=ACTIVE) # btnDisplay.grid(row=row_i, column=0) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="No", command=self.confirm_decline) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="Cancel", command=self.confirm_cancel) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes to All", command=self.confirm_silence) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) self.confirm_frame.update() try: self.parent_frame.wait_window(self.confirm_frame) except Tkinter.TclError: # sometimes the wait_window fails, I'm not sure why, but it seems to be # safe to just ignore it *shrug* pass self.confirm_frame = None def confirm_silence(self): self.make_change = True self.make_silent = True self.clean_up() def confirm_cancel(self): self.make_change = False self.cancel = True self.clean_up() def confirm_accept(self): # self.new_line = self.new_entry.get(1.0, END) self.make_change = True self.clean_up() def confirm_decline(self): self.make_change = False self.clean_up() def clean_up(self, event=None): self.save_pos() # print self.screen_pos_x,self.screen_pos_y self.parent_frame.focus_set() self.confirm_frame.destroy() def destroy(self, event=None): self.parent_frame.destroy() def save_pos(self, event=None): return ## save the screen position of the dialog box # if self.confirm_frame: # try: # config.add('dialog_x',(self.confirm_frame.winfo_rootx() - 4)) # config.add('dialog_y',(self.confirm_frame.winfo_rooty() - 30)) # except: # pass ## save the status box's position # if self.parent_frame: # try: # config.add('status_x',self.parent_frame.winfo_rootx() - 4) # config.add('status_y',self.parent_frame.winfo_rooty() - 30) # except: # pass def update(self, msg): # if the window no longer exists, its text can't be updated try: self.status_text.config(state=NORMAL) # Add the new message self.status_text.insert(END, msg.encode("utf-8") + os.linesep) # Scroll down to the bottom again self.status_text.see(END) # Make the display uneditable self.status_text.config(state=DISABLED) self.status_text.update() except: pass
def confirm_change(self, old_line, new_line, old_tuple=(), new_tuple=(), filepath=""): self.confirm_frame = Tkinter.Toplevel(self.parent_frame, padx=10, pady=10) # self.confirm_frame.grid(padx=10,pady=10) self.confirm_frame.protocol("WM_DELETE_WINDOW", self.confirm_decline) # set screen position... ##x = config.get('dialog_x', (self.parent_frame.winfo_rootx() + 50)) ##y = config.get('dialog_y', (self.parent_frame.winfo_rooty() + 50)) x = self.parent_frame.winfo_rootx() + 50 y = self.parent_frame.winfo_rooty() + 50 if x and y: self.confirm_frame.geometry("+%s+%s" % (x, y)) # bind enter to ok and escape to cancel buttons... self.confirm_frame.bind("<Return>", self.confirm_accept) self.confirm_frame.bind("<Escape>", self.confirm_decline) self.confirm_frame.bind("<Configure>", self.save_pos) # make the new dialog a part of the parent... self.confirm_frame.transient(self.parent_frame) # focus onto the dialog... self.confirm_frame.focus_set() label = Tkinter.Label(self.confirm_frame, text=filepath) label.pack() label = Tkinter.Label(self.confirm_frame, text="Change:") # label.grid(row=row_i, column=0, sticky=W) label.pack() # entry = Tkinter.Text(self.confirm_frame, width=75, height=5) # entry = ScrolledText(self.confirm_frame, width=75, height=5) entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3) entry.insert(Tkinter.INSERT, old_line.encode("utf-8")) # highlight the text to be changed... if len(old_tuple) == 2: entry.tag_add("found", "1.%s" % (old_tuple[0]), "1.%s+%sc" % (old_tuple[0], old_tuple[1] - old_tuple[0])) entry.tag_config("found", foreground="red") entry.config(state=DISABLED) entry.pack(fill=BOTH, expand=Y) label = Tkinter.Label(self.confirm_frame, text="To:") label.pack() self.new_entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3) self.new_entry.insert(Tkinter.INSERT, new_line.encode("utf-8")) # highlight the text to be changed... if len(new_tuple) == 2: self.new_entry.tag_add( "found", "1.%s" % (new_tuple[0]), "1.%s+%sc" % (new_tuple[0], new_tuple[1] - new_tuple[0]) ) self.new_entry.tag_config("found", foreground="red") self.new_entry.config(state=DISABLED) self.new_entry.pack(fill=BOTH, expand=Y) btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes", command=self.confirm_accept, default=ACTIVE) # btnDisplay.grid(row=row_i, column=0) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="No", command=self.confirm_decline) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="Cancel", command=self.confirm_cancel) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes to All", command=self.confirm_silence) # btnDisplay.grid(row=row_i, column=1) btnDisplay.pack(side=LEFT, padx=5, pady=5) self.confirm_frame.update() try: self.parent_frame.wait_window(self.confirm_frame) except Tkinter.TclError: # sometimes the wait_window fails, I'm not sure why, but it seems to be # safe to just ignore it *shrug* pass self.confirm_frame = None
class App: def __init__(self, master): self.master = master self.file = 'grid.csv' self.ownZepName = "goud" self.updatingFlag = False self.btnUpPressed = False self.btnDownPressed = False self.btnLeftPressed = False self.btnRightPressed = False self.btnPlusPressed = False self.btnMinusPressed = False #keyListener aanzetten master.bind("<Key>", self.keyPressed) master.bind("<KeyRelease>", self.keyReleased) leftFrame = Frame(master, width = 200, height = 640) leftFrame.grid(row = 0, column = 0) debugFrame = Frame(leftFrame, width = 200, height = 400) debugFrame.grid(row = 0, column = 0) controlFrame = Frame(leftFrame, width = 200, height = 200) controlFrame.grid(row = 1, column = 0, pady = 10) rasterFrame = Frame(master, width = 600, height = 640) rasterFrame.grid(row = 0, column = 1) #Scrolledtext in leftTopFrame self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=80) self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10) #Buttons #simulator self.btnToggleSimu = Button(controlFrame, text = "Simulator", width = 14, bg = 'gray85', command = lambda: self.toggleSimulator()) self.btnToggleSimu.grid(row = 3, column = 2) self.btnMoveToSimu = Button(controlFrame, text = "Ga naar (Sim)", width = 14, bg = 'gray85', command = lambda: self.moveTo(Name = "goudsimu")) self.btnMoveToSimu.grid(row = 1, column = 4) self.btnHeightSimu = Button(controlFrame, text = "Kies hoogte (Sim)", width = 14, bg = 'gray85', command = lambda: self.setGewensteHoogte(Name ="goudsimu")) self.btnHeightSimu.grid(row = 2, column = 4) #hoogte self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(0)) self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte: ", anchor = "w") self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20) self.lblGemetenHoogte.grid(row=0, column=2) self.lblGemetenHoogteVar.grid(row=0, column=3) #move to self.btnMoveTo = Button(controlFrame, text="Ga naar (Zep)", bg = 'gray85', width = 14, command = lambda: self.moveTo()) self.btnMoveTo.grid(row=1,column=2) self.txtMoveTo = Entry(controlFrame, width=24) self.txtMoveTo.grid(row=1, column=3) self.txtMoveTo.bind('<Return>', self.moveTo) #hoogte self.btnHeight = Button(controlFrame, text="Kies hoogte (Zep)", bg = 'gray85', width = 14, command = lambda: self.setGewensteHoogte()) self.btnHeight.grid(row=2,column=2) self.txtHeight = Entry(controlFrame, width=24) self.txtHeight.grid(row=2, column=3) self.txtHeight.bind('<Return>', self.setGewensteHoogte) #images self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0) self.display.grid(row=0, column = 0, sticky=W+E+N+S) foundFigures = Label(controlFrame, text = "Herkende figuren:") foundFigures.grid(row = 0, column = 0) self.display2 = Canvas(controlFrame, width = 220, height=165, bd=2, relief = "groove", highlightthickness=0) self.display2.grid(row=1, column = 0, sticky=W+E+N+S, rowspan=12) self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) #goal original = Image.open('goalPin.png') resized = original.resize((60,60),Image.ANTIALIAS) self.goalImage = ImageTk.PhotoImage(resized) self.makeBackground() self.initZeppelins() self.paintCanvas() self.sim = None mq.setGUI(self) def initZeppelins(self): self.zeppelins = [] self.goal = (-100,-100) # self.zeppelins.append(AbstractZeppelin('red', 'simu')) self.zeppelins.append(AbstractZeppelin('#EBB400', self.ownZepName)) def convToPixelCoords(self, pos): cmHeight = 34.6410162 cmWidth = 40.0 xcm, ycm = pos x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth y = self.yStart + (ycm/cmHeight)*self.triangleHeight result = (x,y) return result def createPhoto(self, cvresults): self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) cv = eval(cvresults) width = cv[0] height = cv[1] figures = cv[2] coordinates = cv[3] for i in xrange(0,len(figures)): j = self.allShapes.index(figures[i]) image = self.shapeImages[j] xcoord = int(coordinates[i][0]/(width*1.0)*220) ycoord = int(coordinates[i][1]/(height*1.0)*165) self.latestphoto.paste(image, (xcoord-12, ycoord-12), mask = image) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) def makeBackground(self): #rooster inlezen: f = open("../positioning/"+ str(self.file), 'r') shapesText = f.read() self.raster = [] self.tabletLocations = [] nrows = 0 ncol = 0 for line in shapesText.split("\n"): temp = line.split(",") if not len(temp) == 2: nrows += 1 if ncol == 0: ncol = len(temp) for s in temp: self.raster.append(s.strip()) else: self.tabletLocations.append((int(temp[0]), int(temp[1]))) f.close() tempWidth1 = 600/ncol tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0)) tempHeight2 = 570/nrows+2 tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0)) #raster self.resizedRaster = Image.new("RGB", (600,570), (240,240,240)) #vormpjes self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS'] self.shapeImages = [] for i in range(20): imgFile = "vormpjes/" + self.allShapes[i] + ".png" original = Image.open(imgFile) self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS)) original = Image.open("tablet.png") self.tabletIm = original.resize((40,40),Image.ANTIALIAS) self.xlen = ncol self.ylen = nrows self.triangleWidth = min(tempWidth1, tempWidth2) self.triangleHeight = min(tempHeight1, tempHeight2) self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4 self.oddXStart = self.evenXStart + self.triangleWidth/2 self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4 draw = ImageDraw.Draw(self.resizedRaster) #grid tekenen for y in range(self.ylen): for x in range(self.xlen): ycoord = self.yStart + y*self.triangleHeight zelf = self.raster[y*self.xlen + x] != "XX" if y>0: boven = self.raster[(y-1)*self.xlen + x] != "XX" if y<self.ylen-1: onder = self.raster[(y+1)*self.xlen + x] != "XX" if y>0 and x < self.xlen-1: oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX" if y<self.ylen-1 and x < self.xlen-1: oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX" if x<self.xlen-1: naast = self.raster[y*self.xlen + x+1] != "XX" if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and onder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and boven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) else: xcoord = self.oddXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and x < self.xlen-1 and oddboven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) del draw for loc in self.tabletLocations: conv = self.convToPixelCoords((loc[0]/10, loc[1]/10)) self.resizedRaster.paste(self.tabletIm, (int(conv[0])-20, int(conv[1])-20), mask = self.tabletIm) #vormpjes tekenen for y in range(self.ylen): for x in range(self.xlen): index = y*self.xlen + x if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth else: xcoord = self.oddXStart + x*self.triangleWidth ycoord = self.yStart + y*self.triangleHeight shape = self.raster[index] if shape != 'XX': image = self.shapeImages[self.allShapes.index(shape)] self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) def updatePath(self): self.rasterBackup = self.rasterImage draw = ImageDraw.Draw(self.resizedRaster) for z in self.zeppelins: length = len(z.locations) if length > 1: prev = self.convToPixelCoords(z.locations[length-2]) current = self.convToPixelCoords(z.locations[length-1]) draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) del draw def paintCanvas(self): #clear the canvas #self.display.delete('all') #rooster tekenen self.updatePath() self.display.create_image(0, 0, image=self.rasterImage, anchor=NW) #Testcode voor zeppelin locatie for z in self.zeppelins: if z.orientationFound: point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20)) point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20)) point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20)) point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20)) point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation)) point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation)) arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y] self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1) self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color) self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER) def toggleSimulator(self): if self.sim == None: enemy = "goudsimu" self.zeppelins.append(AbstractZeppelin("red", enemy)) mq.initEnemy(enemy) self.sim = simulator.simulator(100,100, enemy) return self.sim.toggleActive() def updateGoal(self, location, tablet): self.debugPrint("Nieuw doel voor simulator: " + str(tablet) + " " + str(location)) self.goal = self.convToPixelCoords(location) self.paintCanvas() def updateLocation(self, location, n): self.debugPrint("Nieuwe locatie voor " + n + " ontvangen: " + str(location)) for z in self.zeppelins: if z.name == n: z.updateLocation((location[0]/10, location[1]/10)) self.paintCanvas() def updateHeight(self, height, n): self.debugPrint("Nieuwe hoogte voor " + n + " ontvangen: " + str(height)) if self.ownZepName == n: self.gemetenHoogteString.set(str(height)) def updateAngle(self, angle, n): self.debugPrint("Nieuwe orientatie voor " + n + " ontvangen: " + str(angle) + " graden") for z in self.zeppelins: if z.name == n: z.updateAngle(angle) self.paintCanvas() def showCvResults(self, body): self.debugPrint("Nieuwe foto vertaling ontvangen: " + body) self.createPhoto(body) #gewenste hoogte aanpassen def setGewensteHoogte(self, event = None, Name = "goud"): x = self.txtHeight.get() self.txtHeight.delete(0, END) self.master.focus() try: x = int(x) except: return if isinstance(x, int) and x > 0 and x < 8000: global neededHeight neededHeight = x message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd" self.debugPrint(message) mq.elevate(x, Name) #gewenste hoogte aanpassen def moveTo(self, event = None, Name = "goud"): st = self.txtMoveTo.get() self.txtMoveTo.delete(0, END) self.master.focus() try: xst, yst = st.split(',') x = int(xst) y = int(yst) except: return if isinstance(x, int) and isinstance(y, int): message = "Bewegen naar (" + str(x) + "," + str(y) + ") aangevraagd" self.debugPrint(message) self.goal = x/10,y/10 self.paintCanvas() mq.moveTo(x, y, Name) #tekst weergeven in debug venster def debugPrint(self, tekst): self.scrDebug.config(state = "normal") self.scrDebug.insert(END, ">> " + tekst + "\n") self.scrDebug.config(state = "disabled") self.scrDebug.yview_pickplace("end") def toggleAutomaticPilot(self): if not self.connected: return self.debugPrint("Automatische piloot toggle aangevraagd") self.client.toggleAutomaticPilot() def createClient(self): try: self.client = cl(self, self.ownZepName) self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client)) self.connected = True self.connectedString.set("Verbonden") self.lblConnected.config(fg = "green") self.debugPrint("Verbonden met Raspberry Pi") except: self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n -Staat de Raspberry Pi aan?\n -Staat de server aan?\n -Zit deze computer op de ad-hoc?") def moveForward(self): self.debugPrint("Voorwaarts vliegen aangevraagd") mq.setMotor1PWM(100) mq.setMotor2PWM(100) def moveBackward(self): self.debugPrint("Achterwaarts vliegen aangevraagd") mq.setMotor1PWM(-100) mq.setMotor2PWM(-100) def moveLeft(self): self.debugPrint("Links draaien aangevraagd") mq.setMotor1PWM(100) def moveRight(self): self.debugPrint("Rechts draaien aangevraagd") mq.setMotor2PWM(100) def moveUp(self): self.debugPrint("Omhoog vliegen aangevraagd") mq.setMotor3PWM(100) def moveDown(self): self.debugPrint("Omlaag vliegen aangevraagd") mq.setMotor3PWM(-100) def horizontalOff(self): self.debugPrint("Horizontale motors stoppen aangevraagd") mq.setMotor1PWM(0) mq.setMotor2PWM(0) def verticalOff(self): self.debugPrint("Verticale motor stoppen aangevraagd") mq.setMotor3PWM(0) #toetsenbord invoer def keyPressed(self, event): k = event.keysym if k == 'Up': if not self.btnUpPressed: self.btnUpPressed = True self.moveForward() elif k == 'Down': if not self.btnDownPressed: self.btnDownPressed = True self.moveBackward() elif k == 'Left': if not self.btnLeftPressed: self.btnLeftPressed = True self.moveLeft() elif k == 'Right': if not self.btnRightPressed: self.btnRightPressed = True self.moveRight() elif k == 'plus': if not self.btnPlusPressed: self.btnPlusPressed = True self.moveUp() elif k == 'minus': if not self.btnMinusPressed: self.btnMinusPressed = True self.moveDown() def keyReleased(self, event): k = event.keysym if k == 'Up': self.btnUpPressed = False self.horizontalOff() elif k == 'Down': self.btnDownPressed = False self.horizontalOff() elif k == 'Left': self.btnLeftPressed = False self.horizontalOff() elif k == 'Right': self.btnRightPressed = False self.horizontalOff() elif k == 'plus': self.btnPlusPressed = False self.verticalOff() elif k == 'minus': self.btnMinusPressed = False self.verticalOff()
class Window: def __init__(self): self.nickname = "Matti" ''' Create the base window ''' self.root = Tk() self.root.protocol("WM_DELETE_WINDOW", self.stop) self.root.title('pySpellcast') self.frame = Frame(self.root,background="white") self.frame.pack(fill=BOTH,expand=YES) self.frame.grid_rowconfigure(0,weight=1) self.frame.grid_columnconfigure(0,weight=1) ''' Textframe holds the textbox and entry box ''' self.textframe = Frame(self.frame) self.textframe.grid(row=0,column=0,rowspan=3,sticky=N+S+W+E) self.textframe.grid_rowconfigure(0,weight=1) self.textframe.grid_columnconfigure(0,weight=1) ''' Textbox for server output ''' self.text = ScrolledText(self.textframe,width=40,height=20, wrap=WORD, state=DISABLED, background="white",foreground="black") self.text.grid(row=0,column=0,ipadx=10,sticky=N+S+W+E) ''' entrybox for input ''' self.input = StringVar() self.entry = Entry(self.textframe,textvariable=self.input,background="white",foreground="black", state=NORMAL, insertbackground="black") self.entry.grid(row=1,column=0,sticky=W+E) self.entry.bind("<Return>",self.enter) ''' Creating buttons ''' self.sendbutton = Button(self.frame,text="Send") self.spellbutton = Button(self.frame,text="Spells") self.sendbutton.bind('<Button-1>',self.sendmoves) self.spellbutton.bind('<Button-1>',self.showspells) self.sendbutton.grid(row=1,column=1,sticky=W+E) self.spellbutton.grid(row=1,column=2,sticky=W+E) ''' listbox for characters and hitpoints ''' self.list = Listbox(self.frame,height=10,width=40,font="courier") self.list.grid(row=2,column=1,columnspan=8,sticky=N+S+W+E) ''' Loading the icons ''' self.waveR = PhotoImage(file="graphics/wave-right.gif") self.digitR = PhotoImage(file="graphics/digit-right.gif") self.snapR = PhotoImage(file="graphics/snap-right.gif") self.clapR = PhotoImage(file="graphics/clap-right.gif") self.palmR = PhotoImage(file="graphics/palm-right.gif") self.wiggleR = PhotoImage(file="graphics/wiggle-right.gif") self.knifeR = PhotoImage(file="graphics/knife-right.gif") self.waveL = PhotoImage(file="graphics/wave-left.gif") self.digitL = PhotoImage(file="graphics/digit-left.gif") self.snapL = PhotoImage(file="graphics/snap-left.gif") self.clapL = PhotoImage(file="graphics/clap-left.gif") self.palmL = PhotoImage(file="graphics/palm-left.gif") self.wiggleL = PhotoImage(file="graphics/wiggle-left.gif") self.knifeL = PhotoImage(file="graphics/knife-left.gif") self.antispell = PhotoImage(file="graphics/antispell.gif") self.unknown = PhotoImage(file="graphics/unknown.gif") self.empty = PhotoImage(file="graphics/empty.gif") self.spelllist = PhotoImage(file="graphics/spell-list.gif") self.actiondialog = None ''' Setting up player dictionary, contains player name to player class ''' self.players = {} questions = LabelFrame(self.frame,text="Questions") questions.grid(row=4,column=0,columnspan=10,sticky=W+E) question = Label(questions,text="Test") question.pack(anchor=W,fill=BOTH,expand=1) def sortPlayers(self): for i,(name,player) in enumerate(self.players.items()): player.frame.grid_remove() player.frame.grid(row=0,column=1+i,padx=5) def testPlayers(self): self.players = {'White mage':0,'Black mage':0} def updatePlayers(self,players): for player,history in players: if player not in self.players.keys(): self.players[player] = Player(player,self) self.players[player].updateHistory(history) self.sortPlayers() # Todo, remove nonexisting players.. def updatePlayerFrames(self): # TODO: FIIXIXIXIXIXIIXIXXIIXII playerFrames = self.playerFrames[:] self.playerFrames = [] for name,frame in self.players: if frame not in playerFrames: new = Frame(self.root,background="red") else: self.playerFrames.append(frame) #TODO: remove nonexisting players def stop(self): self.root.destroy() reactor.stop() sys.exit(1) def display_line(self,text,timestamp=None): print "Display",text if not timestamp: timestamp = time.time() print "scroll1:",self.text.yview() if self.text.yview()[1] == 1.0: scroll = True else: scroll = False self.text.config(state=NORMAL) asciitime = time.strftime('[%H:%M:%S]', time.localtime(float(timestamp))) #if owner: self.textarea.mark_set(start, END);self.textarea.mark_gravity(start,LEFT #text = self.wrap(text) text = [['black',text]] ts = ('grey',"%s "%(asciitime)) text.insert(0,ts) for piece in text: self.text.insert(END, piece[1],piece[0]) #if owner: self.textarea.mark_set(end, END);self.textarea.mark_gravity(end,LEFT) self.text.insert(END,'\n') print "scroll2",self.text.yview() if scroll: self.text.yview(END) ''' if owner: print "Checking tag.." a,b= self.textarea.tag_ranges(tag) print dir(a) self.textarea.delete(a,b) ''' self.text.config(state=DISABLED) def selected(self,item): myplayer = self.players[self.nickname] if self.select == 'right': myplayer.history[-1][1] = item else: myplayer.history[-1][0] = item myplayer.updateHistory() def enter(self,event): data=unicode(self.input.get()) if len(data) == 0: return self.input.set("") self.client.write("msg %s"%data) def showspells(self,event): spells = SpellDialog(self.root,self) def sendmoves(self,event): if self.stage == 1: myplayer = self.players[self.nickname] moves = myplayer.history[-1] self.client.write("moves %s"%(json.dumps(moves))) def setStage(self,stage): self.stage = stage