Beispiel #1
0
def initializeResponseEntry():
    responseEntry = ScrolledText(width=40, height=6, background=darkSalmon)
    responseEntry.insert(END, 'Type here')
    responseEntry.grid(row=2, sticky=EW, padx=50)
    responseEntry.bind('<KeyRelease>', typing)
    responseEntry.bind('<BackSpace>', blankButtons())
    responseEntry.bind('<Button-1>', clearText)
    return responseEntry
Beispiel #2
0
    def add_new_clip(self):
        '''
         destroy frames and add with new clip added
        '''
        for frame in self.frames:
            frame.destroy()

        self.frames = []
        self.textBoxes = []
        self.no_of_clips = len(utils.clips)

        for clip, i in zip(reversed(utils.clips), range(len(utils.clips))):

            frame = Frame(self.mainFrame,
                          padx=5,
                          pady=5,
                          bg=self.colors[i % 3],
                          width=300)

            Button(frame,
                   text="clip it ",
                   font="Helvetica 12 bold",
                   command=partial(self.copy_to_clipboard, i),
                   relief=RAISED,
                   padx=3,
                   pady=3,
                   highlightbackground='dark violet',
                   bg='dark violet',
                   fg='white',
                   width=8).grid(row=0, column=0, ipady=2)

            Button(frame,
                   text="delete",
                   font="Helvetica 12 bold",
                   command=partial(self.delete_frame,
                                   len(utils.clips) - i - 1),
                   relief=RAISED,
                   padx=3,
                   pady=3,
                   highlightbackground='red',
                   bg='red',
                   fg='white',
                   width=8).grid(row=1, column=0, ipady=2)

            textBox = ScrolledText(frame,
                                   height=4,
                                   width=20,
                                   font="Helvetica 12 bold")
            textBox.insert(END, clip)

            textBox.grid(row=0, column=1, rowspan=2, sticky=E, padx=5)
            self.textBoxes.append(textBox)

            self.no_of_clips = len(utils.clips)

            frame.pack(fill='both', expand=True, pady=5)
            self.frames.append(frame)
Beispiel #3
0
def text(event):
    fn = listbox.get(listbox.curselection())
    str1 = open(fn).read()
    editWindow = Tk()
    editWindow.title(fn)
    editWindow.geometry('+2000+150')
    editText = ScrolledText(editWindow, width=120, height=60)
    editText.grid()
    editText.insert(INSERT, str1)
    editWindow.mainloop()
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 GuiShuffler(shuffle.Shuffler):
    def __init__(self):
        shuffle.Shuffler.__init__(self, 20, 10, 2)

        self.frmMain = Tk()
        self.blockStr = StringVar()
        self.blockSizeStr = StringVar()
        self.groupStr = StringVar()
        self.results = ScrolledText(self.frmMain)

        self.blockStr.set(str(self.blocks))
        self.blockSizeStr.set(str(self.blockSize))
        self.groupStr.set(str(self.groups))

        Label(self.frmMain, text="Blocks").grid(row=0, sticky=E)
        blockEntry = Entry(self.frmMain, textvariable=self.blockStr)
        blockEntry.grid(column=1, row=0)

        Label(self.frmMain, text="Block Size").grid(row=1, sticky=E)
        blockSizeEntry = Entry(self.frmMain, textvariable=self.blockSizeStr)
        blockSizeEntry.grid(column=1, row=1)

        Label(self.frmMain, text="Groups").grid(row=2, sticky=E)
        groupEntry = Entry(self.frmMain, textvariable=self.groupStr)
        groupEntry.grid(column=1, row=2)

        self.results.grid(columnspan=2, row=3, sticky=W+E)

        genBtn = Button(self.frmMain, text="Generate", command=self.generate, anchor=SE)
        genBtn.grid(columnspan=2, row=4, sticky=S)

    def generate(self):
        try:
            self.blocks = int(self.blockStr.get())
            self.blockSize = int(self.blockSizeStr.get())
            self.groups = int(self.groupStr.get())
        except ValueError:
            tkMessageBox.showwarning("Not a Number", "All values must be numbers.\n")
            return

        if not self.is_valid_group_size():
            tkMessageBox.showwarning("Group Size", "Block Size must be evenly divisible by groups to get an even grouping.\n")
        else:
            self.results.delete(1.0, END)       # clear previous entries
            self.print_results(self.results)

    def print_results(self, results):
        for i in  range(self.blocks):
            results.insert(END, ' '.join([str(i) for i in self.shuffle()]))
            results.insert(END, "\n")

    def run(self):
        self.frmMain.mainloop()
Beispiel #6
0
class EmailPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        case_name = entry.get()
        label = tk.Label(self,text=case_name)
        label.pack(side="top", fill="x", pady=10)
    
        sidebar = Frame(self , width=200 , bg='white' , height=500, relief='sunken' , borderwidth=2)
        sidebar.pack(expand=True , fill='y' , side='left' , anchor='nw')
    
        screen = Frame(self, width=200, bg='white', height=500, relief='sunken', borderwidth=2)
        screen.pack(expand=True, fill='y', side='left', anchor='nw')
    
        self.text = ScrolledText(screen, undo=True)
        self.text['font'] = ('consolas', '12')
        self.text.grid(row=0,column=4)
        self.text.pack(expand=True, fill='both',side=RIGHT)
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        button = tk.Button(sidebar, text="Start",command=lambda:self.run_script(),width=20)
        button.pack()

        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        button = tk.Button(sidebar, text="Go Back <<",command=lambda:controller.show_frame("PageTwo"),width=20)
        button.pack()


    def run_script(self):
        
        sys.stdout = self
        tkMessageBox.showinfo('FYI', 'Analyzing...Please Wait')
        import final_spam
        final_spam
        self.que()
    def write(self, txt):
        self.text.insert(INSERT, txt)

    def que(self):
        conn=pymysql.connect(host="localhost",user="******",passwd="1234567890",db="poject")
        cursor = conn.cursor()
        rep=self.text.get('1.0', 'end')
        cursor.execute("SELECT @id := (SELECT caseid FROM poject.case ORDER BY caseid DESC LIMIT 1)")
        cursor.execute("UPDATE  poject.case set email_report=%s where caseid=@id", (rep))
        conn.commit()
        conn.close()
        return
Beispiel #7
0
class Updates():
	""" обновление программы """
	def __init__(self,app):
		self.app=app
		self.win=Frame(self.app.win)
		
		self.check_b=Button(self.win,text='Проверить доступные обновления',style='mini2.TButton',image=self.app.app.app.img['check'],compound='left',command=self.update_list)
		self.check_b.grid(row=0,column=0,padx=5,pady=5,sticky=N)
		



		
		self.txt=ScrolledText(self.win,width=85,height=10,font=('normal',10))
		self.txt.grid(row=1,column=0,sticky=N,padx=30)
		
		self.down_but=Button(self.win,text='Загрузить обновления',image=self.app.app.app.img['download'],compound='left',style='mini2.TButton',state='disable',command=self.download_updates)
		self.down_but.grid(row=2,column=0,pady=5)
		
	def update_list(self):
		""" загружаем список доступных обновлений """
		serv=self.app.app.app.sets.sync_server
		try:last=int(self.app.app.app.sets.last_update)
		except:last=0
		self.check_b['state']='disable'
		self.txt.delete(0.0,END)
		self.txt.insert(END,'Выполняется проверка обновлений...\n')
		self.win.update()
		data={}
		data['data']=str(last)
		try:
			resp=urllib.urlopen(serv+'/updates',urllib.urlencode(data)).read()
			resp=eval(resp)
		except Exception,x:
			self.txt.insert(END,'Не удалось подключиться к серверу обновлений :(')
			self.win.update()	
			self.check_b['state']='normal'
			return
		if len(resp)==0:
			self.txt.insert(END,'Новых обновлений не найдено!')
			self.win.update()	
			self.check_b['state']='normal'	
			return
		self.txt.delete(0.0,END)
		for x in resp:
			self.txt.insert(END,'Обновление от %s.\n%s\n\n'%(int2date(x[0]),x[1].encode('utf-8')))
		self.resp=resp
		self.down_but['state']='normal'
Beispiel #8
0
    def build_dlg(self):
        top = self.top
        top.resizable(0, 1)

        frame = Tkinter.Frame(top)
        text = ScrolledText(frame, height=13, width=50, background='white')
        text.insert('1.0', self.help_text)
        text.configure(state='disabled')
        text.grid(column=0, row=0, sticky='nesw')
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)

        button = Tkinter.Button(frame, text=_('Close'), command=self.cancel)
        button.grid(column=0, row=1)

        frame.pack(expand=1, fill='both')
Beispiel #9
0
def main():
    root = Tk()
    root.title('test')
    root.geometry('+1000+400')
    global text
    text = ScrolledText(root, font=('微软雅黑', 10))
    text.grid()
    button = Button(root, text='开始爬取', font=('微软雅黑', 10), command=start())
    button.grid()
    global varl
    varl = StringVar()

    label = Label(root, font=('微软雅黑', 10), fg='red', textvar=varl)
    label.grid()
    varl.set('已准备好...')
    root.mainloop()
Beispiel #10
0
    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)
Beispiel #11
0
class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        #print case_name
        #data = cursor.fetchall()
            #id = cursor.execute("SELECT case_name from poject.case where case_name=self.case_name")
        label = tk.Label(self,text='')
        label.pack(side="top", fill="x", pady=10)
        
        
        sidebar = Frame(self, width=200, bg='white', height=500, relief='sunken', borderwidth=2)
        sidebar.pack(expand=True, fill='y', side='left', anchor='nw')
        
        screen = Frame(self, width=200, bg='white', height=500, relief='sunken', borderwidth=2)
        screen.pack(expand=True, fill='y', side='left', anchor='nw')
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        
        button = tk.Button(sidebar, text="Web Forensics",
                           command=lambda: controller.show_frame("WebPage"),width=20)
        button.pack()
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        
        button = tk.Button(sidebar, text="Network Forensics",
                           command=lambda: controller.show_frame("NetworkPage"),width=20)
        button.pack()
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        button = tk.Button(sidebar, text="Email Forensics",
                           command=lambda: controller.show_frame("EmailPage"),width=20)
        button.pack()
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        
        self.text = ScrolledText(screen, undo=True)
        self.text['font'] = ('consolas', '12')
        self.text.grid(row=0,column=4)
        self.text.pack(expand=True, fill='both',side=RIGHT)
Beispiel #12
0
class Licensing( Frame ):
    BUTTON_TEXT = "Copy to clipboard"

    def __init__( self, master ):
        Frame.__init__( self, master )
        COMPOSITOR.register_view( self )
        self._setup_view()
        self.on_model_updated( COMPOSITOR.OTHER_UPDATED )

    def _setup_view( self ):
        self.rowconfigure( 0, weight = 1 )
        self.columnconfigure( 0, weight = 1 )

        self.license_box = ScrolledText( self, state = DISABLED )
        self.license_box.grid( row = 0, column = 0, sticky = W + E + N + S, padx = 5, pady = 5 )

        self.clipboard_button = Button( self, text = self.BUTTON_TEXT, command = self._on_copy_pressed )
        self.clipboard_button.grid( row = 1, column = 0, sticky = N + E )

    def _on_copy_pressed( self ):
        self.license_box.clipboard_clear()
        self.license_box.clipboard_append( self.license_box.get( '0.0', END ) )
        self.clipboard_button.configure( text = "Copied!", state = DISABLED )
        self.after( 2500, lambda: self.clipboard_button.configure( text = self.BUTTON_TEXT, state = NORMAL ) )

    def on_model_updated( self, reason ):
        if reason not in [COMPOSITOR.OTHER_UPDATED, COMPOSITOR.SELECTED_TYPE_CHANGED, COMPOSITOR.LAYER_ADDED, COMPOSITOR.LAYER_REMOVED, COMPOSITOR.SHEET_SELECTED, COMPOSITOR.LAYER_ORDER_CHANGED]:
            return

        # The compositor changed state, so make sure we're up to date, too.
        self.license_box.configure( state = NORMAL )

        # clear the existing text
        self.license_box.delete( 1.0, END )

        sheets = COMPOSITOR.get_selected_sheets().values()
        license_text = LICENSING.get_formatted_licensing( sheets )

        self.license_box.insert( END, license_text )
        self.license_box.configure( state = DISABLED )

    def destroy( self ):
        COMPOSITOR.deregister_view( self )
        Frame.destroy( self )
Beispiel #13
0
def http_s():
    Label(frame3, text='网站:', font=(8)).grid(row=2, column=0)

    e1 = Entry(frame3,
               width=28,
               validate="focusout",
               validatecommand=lambda: test2(e1.get()),
               invalidcommand=intest)
    e1.grid(row=2, column=1, padx=10, pady=5)

    text1 = ScrolledText(frame4,
                         font=('微软雅黑', 8),
                         width=43,
                         height=9,
                         padx=5,
                         pady=5)
    text1.grid(row=0, column=0)

    frame3.pack()

    Button(frame3, text='开始扫描', font=(8),
           command=lambda: bbb(e1.get(), text1)).grid(row=4, column=1)

    frame4.pack(padx=20, pady=5)
Beispiel #14
0
class ClustererGui(ttk.Frame):
    """GUI to open/save xml/text-files and visualize clustering."""
    def __init__(self, master=None):
        """Init GUI - get auto-split-sentences-option and standard test-file-folder from config-file."""
        ttk.Frame.__init__(self, master)
        self.grid(sticky=tk.N + tk.S + tk.E + tk.W)

        self.createWidgets()
        self.filepath = None
        self.xml_filepath = None
        self.filename = None
        self.article_id = None
        self.extraction = None
        self.author_no = None
        self.correct = None
        self.result = None
        self.colors = []

        config = ConfigParser.ConfigParser()
        config.read("config.cfg")
        params = dict(config.items("params"))
        article_dir = params['test_file_dir']
        self.auto_split_sentences = bool(int(params['auto_split_sentences']))
        self.show_knee_point = bool(int(params['show_knee_point']))
        self.show_knee_point = False  # currently not supported in GUI-mode
        self.last_dir = article_dir

    def createWidgets(self):
        """Organize GUI."""
        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)

        left_frame = ttk.Frame(self, relief="raised", borderwidth=1)
        left_frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
        left_frame.rowconfigure(0, weight=0)
        left_frame.rowconfigure(1, weight=1)
        left_frame.columnconfigure(0, weight=1)

        buttons_topleft = ttk.Frame(left_frame)
        buttons_topleft.grid(row=0, column=0)

        self.choose_file_btn = ttk.Button(buttons_topleft,
                                          text='choose file...',
                                          command=self.choose_file)
        self.choose_file_btn.grid(row=0, column=0)

        self.save_file_btn = ttk.Button(buttons_topleft,
                                        text='save file...',
                                        command=self.save_file)
        self.save_file_btn.grid(row=0, column=1)

        self.extract_feat_btn = ttk.Button(
            buttons_topleft,
            text='process',
            command=self.start_featureextr_thread)
        self.extract_feat_btn.grid(row=0, column=2)

        right_frame = ttk.Frame(self)
        right_frame.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
        right_frame.rowconfigure(0, weight=1)
        right_frame.rowconfigure(1, weight=1)

        self.distr_entry = ScrolledText(right_frame, width=30, height=30)
        self.distr_entry.grid(row=0, column=0, columnspan=2, sticky=tk.N)

        self.test_entry = ScrolledText(right_frame, width=30)
        self.test_entry.grid(row=1, column=0, columnspan=2, sticky=tk.N)

        self.scrolledText = ScrolledText(left_frame, undo=True, wrap=tk.WORD)
        self.scrolledText['font'] = ('Helvetica', '12')
        self.scrolledText.tag_configure('lines',
                                        background="#dddddd",
                                        foreground="black",
                                        font=('Helvetica', 9))
        self.scrolledText.tag_configure('blanks',
                                        background="#ffffff",
                                        foreground="black",
                                        font=('Helvetica', 9))
        self.scrolledText.grid(row=1,
                               column=0,
                               sticky=tk.N + tk.S + tk.E + tk.W)

        status_bar = ttk.Frame(self)
        status_bar.grid(row=1, column=0, columnspan=2, sticky=tk.W)
        status_bar.columnconfigure(0, weight=1, minsize=100)
        status_bar.columnconfigure(1, weight=1)

        self.status = tk.StringVar()
        self.status.set("ready")
        self.status_label = ttk.Label(status_bar, textvariable=self.status)
        self.status_label.grid(row=0, column=1, padx=10)

        self.progressbar = ttk.Progressbar(status_bar,
                                           mode='indeterminate',
                                           length=200)
        self.progressbar.grid(row=0, column=0, padx=3)

    def choose_file(self):
        """Choose text or xml file dialog."""
        self.filepath = askopenfilename(initialdir=self.last_dir,
                                        filetypes=(("text and xml files",
                                                    ("*.txt", "*.xml")), ))
        if self.filepath:
            ext = os.path.splitext(self.filepath)[1]

            if ext == ".xml":
                '''save raw-text of xml-file to a new file and print it'''
                self.xml_filepath = self.filepath
                self.filepath = self.create_text_fromXML()

            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            self.scrolledText.delete(1.0, tk.END)
            self.print_raw_text()
            self.scrolledText.edit_reset()

    def create_text_fromXML(self):
        """Create text-file out of given xml-file."""
        new_filepath = os.path.splitext(self.filepath)[0] + ".txt"
        with codecs.open(self.filepath, 'r', 'UTF-8') as xml_file:
            xml_tree = etree.parse(xml_file)

        with codecs.open(new_filepath, 'w', 'UTF-8') as newFile:
            first_entry = True
            for entry in xml_tree.getroot():
                if entry.text is not None:
                    if not first_entry:
                        newFile.write("\n\n")
                    else:
                        first_entry = False
                    newFile.write(entry.text)
        return new_filepath

    def save_file(self):
        """Save text-file-dialog."""
        text = self.scrolledText.get("0.0", tk.END)
        if self.filepath is None:
            name = asksaveasfilename(initialdir=self.last_dir,
                                     defaultextension=".txt")
            if name:
                self.filepath = name
            else:
                return
        try:
            with codecs.open(self.filepath, 'w', 'UTF-8') as newFile:
                newFile.write(text.strip())
            self.scrolledText.edit_reset()
            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            return True
        except Exception:  # as e:
            raise

    def start_featureextr_thread(self):
        """Start thread for feature extraction."""
        self.distr_entry.delete(1.0, tk.END)
        self.status.set("processing...")
        if self.filepath is None or self.article_id is None:
            tkMessageBox.showwarning("Save File",
                                     "Save file for feature extraction.")
            return
        try:
            self.scrolledText.edit_undo()
            self.scrolledText.edit_redo()

            tkMessageBox.showwarning("File changed",
                                     "File was changed, please save.")
            return
        except tk.TclError:
            self.extraction = clusterer.Clusterer(self.article_id,
                                                  self.filepath,
                                                  self.xml_filepath,
                                                  self.auto_split_sentences,
                                                  self.show_knee_point)

            self.ftr_extr_thread = threading.Thread(
                target=self.extract_features)
            self.ftr_extr_thread.daemon = True
            self.progressbar.start()
            self.ftr_extr_thread.start()
            self.after(1000, self.check_feat_thread)

    def check_feat_thread(self):
        """Check if feature extraction thread is still working - if not: visualize cluster-results."""
        if self.ftr_extr_thread.is_alive():
            self.after(1000, self.check_feat_thread)
        else:
            self.status.set("ready")

            # generate author-colormap
            self.colors = [None] * len(set(self.clusters))
            for k in set(self.clusters):
                temp_color = plt.cm.spectral(
                    np.float(k) / (np.max(self.clusters) + 1))
                if k == 0:
                    temp_color = plt.cm.spectral(0.05)
                self.colors[k] = self.convert_to_hex(temp_color)
            self.configure_colors()

            self.progressbar.stop()
            self.print_author_distr()
            self.print_text()
            if self.correct is not None and self.author_no is not None:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                s += "\n\n true number of authors: {}".format(self.author_no)
                s += "\n precision: {:.4f}".format(self.scores[0])
                s += "\n recall: {:.4f}".format(self.scores[1])
                s += "\n f1-score: {:.4f}".format(self.scores[2])
                s += "\n adjusted-rand-index: {:.4f}".format(self.scores[3])
                self.test_entry.insert(tk.INSERT, s)
            else:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                self.test_entry.insert(tk.INSERT, s)

    def extract_features(self):
        """Start feature extraction."""
        self.clusters, self.result, self.author_no, self.believe_score, self.scores = self.extraction.calc_cluster(
        )

        if self.result is not None:
            c = Counter(self.result)
            self.correct = c[True] / sum(c.values()) * 100

    def print_text(self):
        """Print raw text with specified author-colors."""
        self.scrolledText.delete(1.0, tk.END)
        f = open(self.filepath)

        line_number = 0
        actual_line_number = 0
        for line in f:
            actual_line_number += 1
            if line.strip():
                s = str(line_number) + ' ' + str(
                    self.clusters[line_number]) + ' ' + line
                s = line
                line_cluster = str(line_number) + ' ' + str(
                    self.clusters[line_number]) + ' '
                line_cluster = ('{:^' + str(14 - len(line_cluster)) +
                                '}').format(line_cluster)
                self.scrolledText.insert(tk.INSERT, line_cluster, 'lines')
                try:
                    self.scrolledText.insert(tk.INSERT, s,
                                             str(self.clusters[line_number]))
                    # if self.result[line_number]:
                    #     # correct assignment - print text foreground in white
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # else:
                    #     # false assignment - print text foreground in black
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]*10**2))
                except IndexError:
                    self.scrolledText.insert(tk.INSERT, s)
                except TypeError:
                    self.scrolledText.insert(tk.INSERT, s,
                                             str(self.clusters[line_number]))
                line_number += 1
            else:
                s = line
                self.scrolledText.insert(tk.INSERT, s, 'blanks')
        f.close()

    def print_raw_text(self):
        """Print raw text."""
        f = open(self.filepath)
        for line in f:
            self.scrolledText.insert(tk.INSERT, line)
        f.close()

    def get_distribution(self, l=None):
        """Return Counter with author distribution in percent."""
        if l is None:
            l = self.clusters
        counter = Counter(l)
        sum_counter = sum(counter.values())

        for key in counter.iterkeys():
            counter[key] = counter[key] / sum_counter * 100
        return counter

    def print_author_distr(self):
        """Print author distribution with specified author-colors."""
        self.distr_entry.delete(1.0, tk.END)
        distr = self.get_distribution(self.clusters)

        for index, count in distr.most_common():
            author_i = "author " + str(index) + "{:>20}%\n".format(
                locale.format(u'%.2f', count))
            self.distr_entry.insert(tk.INSERT, author_i, str(index))

    def convert_to_hex(self, col):
        """Convert inter-tuple to hex-coded string."""
        red = int(col[0] * 255)
        green = int(col[1] * 255)
        blue = int(col[2] * 255)
        return '#{r:02x}{g:02x}{b:02x}'.format(r=red, g=green, b=blue)

    def configure_colors(self):
        """Configure author-specific colors for author-distribution and cluster-results."""
        for i, c in enumerate(self.colors):
            self.scrolledText.tag_configure(str(i),
                                            background=c,
                                            foreground="white")
            self.distr_entry.tag_configure(str(i),
                                           background=c,
                                           foreground="white")
Beispiel #15
0
root.geometry('+50+50')
varDir = StringVar()  # 设置变量
labelDir = Label(root,
                 font=('微软雅黑', 10),
                 fg='black',
                 justify='left',
                 textvariable=varDir)
labelDir.grid(row=0, column=0)
buttonWorkingDir = Button(root,
                          text='打开工作目录',
                          font=('微软雅黑', 10),
                          fg='black',
                          command=openworkingdir)
buttonWorkingDir.grid(row=0, column=1)
buttonClear = Button(root,
                     text='清空工作目录文件',
                     font=('微软雅黑', 10),
                     fg='red',
                     command=clear)
buttonClear.grid(row=0, column=2)
varDir.set('工作目录: ' + path_to_watch)
text = ScrolledText(root, font=('微软雅黑', 10), fg='blue')
text.grid(row=1, column=0, columnspan=3)
buttonWrok = Button(root, text='开始扫描', font=('微软雅黑', 10), command=fun)
buttonWrok.grid(row=2, column=1)
varTips = StringVar()  # 设置变量
label = Label(root, font=('微软雅黑', 10), fg='red', textvariable=varTips)
label.grid(row=2, column=0)
varTips.set('提示:请点击开始扫描!')
root.mainloop()
Beispiel #16
0
class Application(Frame):

	def __init__(self, master):
		"""Creating GUI instance"""
		Frame.__init__(self, master)
		self.output = multiprocessing.Queue() # Queue used to hold output from processes called
		self.stopped = False # False unless a threat is found (used for if/else cases in displaying to GUI)
		self.threat = False # False until threat is found
		self.create_widgets() 

	def create_widgets(self):
		"""Create all widgets in GUI"""
		self.pack(fill=BOTH, expand=1)

		self.columnconfigure(1, weight=1)
		self.columnconfigure(3, pad=7)
		self.rowconfigure(3, weight=1)
		self.rowconfigure(5, pad=7)

		helv = tkFont.Font(family='Cambria', size=10)

		self.instr = Label(self, text="Choose option:")
		self.instr['font'] = helv
		self.instr.grid(sticky=W, pady=4, padx=5)

		# Create textbox
		self.results = ScrolledText(self, undo=True)
		self.results['font'] = helv
		self.results.grid(row=1, column=1, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)

		#Create firewall log button
		self.firewall_log = Button(self, text='Firewall Log', command=lambda: self.scan_log(self.results))
		self.firewall_log.grid(row=1, column=0)
		self.firewall_log['font'] = helv

		#create checkbox
		cvar = IntVar()
		self.cont = Checkbutton(self, text='Continuous?', variable=cvar)
		self.cont['font'] = helv
		self.cont.grid(row=5, column=0, padx=5)

		#create run scan button
		self.run = Button(self, text='Run Scan', command=lambda: self.start(cvar, self.results))
		self.run.grid(row=2, column=0)
		self.run['font'] = helv

		#Create stop/exit button
		self.exit = Button(self, text='Exit', command=self.stop)
		self.exit.grid(row=5, column=2, pady=4, padx=4)
		self.exit['font'] = helv


	def start(self, var, textbox):
		"""Begins monitoring of a computer's connections, either one
		time or continuously"""
		self.exit['text'] = 'Stop'
		self.p = multiprocessing.Process(None, lambda: ip.display_info(self.output, var.get(), self))
		self.p.start()
		self.after(500, lambda: self.check_proc(textbox))

	def stop(self):
		"""Stops the program from running"""
		if self.exit['text'] == 'Exit': # Quits when no processes are running
			self.destroy()
			self.quit()
		else: # Stops a process and then quits
			self.p.terminate()
			self.p.join()
			self.destroy()
			self.quit()

	def check_proc(self, textbox):
		"""Continually checks if processes are still alive
		and calls display_box when all are not alive"""
		if not self.p.is_alive(): # If no processes are alive
			out = self.output.get() 
			if out == True: # first item will be True if continuous mode running and a threat is found
				threats = self.output.get()
				self.p.terminate()
				self.p.join()
				self.exit['text'] = 'Exit'
				self.threat_alert(threats) # create threat alert
			else:
				self.p.terminate()
				self.p.join()
				self.exit['text'] = 'Exit'
			if self.stopped == False: # When no processes are alive, display output to GUI
				self.display_box(textbox, out)
		else:
			self.after(500, lambda: self.check_proc(textbox)) #continusously check if process is alive

	def scan_log(self, textbox):
		"""Scans firewall log, calls function in  firewall.py"""
		IPs = firewall.read_log('log.txt') 
		ip.display_firewall(self.output, IPs, self)
		self.display_box(textbox, self.output.get())

	def display_box(self, textbox, results):
		"""Displays output to textbox on GUI"""
		textbox.insert(END, results)
			
	
	def threat_alert(self, val):
		"""Creates an alert if an IP is found in the Alienvault database"""
		self.stopped = True
		tkMessageBox.showwarning("Alert", "The address " + val[0] + " has been identified as malicious\nType: " + str(val[1]) + "\nReliability: " + str(val[2]) + "\nRisk: " + str(val[3]))
Beispiel #17
0

##-------------------------------------##


# Create the window
window = Tk()
window.title('In Recent Gaming News...')
window.geometry("1300x520")
window.configure(background = 'white')

# Create and Insert the scrolling text box
news_box = ScrolledText(window, width = 60, height = 15, borderwidth = 2,
                        bg = 'slateblue', wrap = "word", foreground = 'white',
                        font = ('calibri', 16))
news_box.grid(row = 3, column = 2, rowspan = 2)

# Create and Insert the 'next button'
next_but = Button(window, text = 'Next >', width = 10, command = next_button)
next_but.grid(row = 4, column = 8)

# Create and Insert the 'previous button'
prev_but = Button(window, text = '< Previous', width = 10, command = prev_button)
prev_but.grid(row = 4, column = 6)

# Create and Insert page numbers (inbetween the buttons)
page_number = Label(window, text = ' ', width = 10, bg = 'white',
                    font = ("Arial", 18, "bold"))
page_number.grid(row = 4, column = 7)

# Import and display the image
Beispiel #18
0
class budejie:
    def __init__(self):

        self.threads = []  # 线程队列
        self.lock = threading.Lock()
        # 创建gui界面
        self.master = Tk()
        self.master.title('百思不得姐')
        self.master.geometry('+200+200')  # 坐标
        self.text = ScrolledText(self.master, font=('微软雅黑', 10))  # 滚动条
        self.text.grid(row=0, columnspan=3)
        Label(self.master, text='请输入需要爬取视频的数目',
              font=('微软雅黑', 10)).grid(row=1, column=0)
        self.e = Entry(self.master)
        self.e.grid(row=1, column=1)
        self.e.insert(10, '1')
        self.button = Button(self.master,
                             text='开始爬取',
                             font=('微软雅黑', 10),
                             command=self.start)
        self.button.grid(row=1, column=2)
        self.varl = StringVar()
        self.label = Label(self.master,
                           font=('微软雅黑', 10),
                           fg='red',
                           textvariable=self.varl)
        self.label.grid(row=2, columnspan=3)
        self.master.mainloop()
        self.varl.set('熊猫说:已经准备好了...')

    def getPage(self, index):
        # requests请求网页源代码
        url = 'http://www.budejie.com/video/' + str(index)
        user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
        try:
            page = requests.get(url, headers={'User-Agent': user_agent})
            return page
        except:
            return None

    def getInfo(self, pageCode, url_num=20):
        # re正则获取视频链接
        pattern = re.compile(
            r'<div class="j-r-list-c">.*?<a href="/detail-.{8}?.html">(.*?)</a>.*?data-mp4="(.*?)".*?</div>.*?</div>',
            re.S)
        urlList = re.findall(pattern, pageCode)
        return urlList[0:url_num]  # 切片

    def download(self, url_content):
        # 下载模块
        urllib.urlretrieve(url_content[1], url_content[0][:16] + '.mp4')

    def start(self):
        count = int(self.e.get())
        if count:
            # 创建video文件夹
            if os.path.exists('video') == False:
                os.mkdir('video')
            os.chdir('video')

            page_num = 1
            while count > 0:
                page = self.getPage(page_num)
                page_num = page_num + 1
                if page:
                    url_contents = self.getInfo(page.text, count)
                    count = count - 20
                    for url_content in url_contents:
                        self.text.insert(
                            END, '正在抓取:\t' + url_content[0][0:16] + '\n')
                        th = threading.Thread(target=self.download,
                                              args=(url_content, ))
                        th.start()
                        self.threads.append(th)
                        time.sleep(2)

            for th in self.threads:
                th.join()
            self.varl.set('熊猫说:视频已经抓取完毕...')

        else:
            print u'没有获取到您输入的数目,请重新输入...'
Beispiel #19
0
root.title("飒飒动漫开停服")
root.geometry('500x500')
label = tk.Label(root, text="飒飒动漫开停服脚本",font=('Arial',15,),height=4).grid(row=0, column=1)

photo = tk.PhotoImage(file="sasalogo.gif")
label = tk.Label(image=photo)
label.image = photo
label.grid(row=0,column=0,columnspan=1)

tk.Button(root,text="开服按钮",command=enter_and_print_start,bg='green',height=1).grid(row=1, column=0)
tk.Button(root,text="停服按钮",command=enter_and_print_stop,bg='red',height=1).grid(row=1, column=1)
tk.Label(root,text="-----------------------------------------------------------------------------------------------------------",height=1).grid(row=2, columnspan=3)
tk.Label(root,text="公司公网IP修改",height=1).grid(row=2, columnspan=2)
tk.Button(root,text="确认修改",command=ok,bg='white',height=1).grid(row=5, column=1,sticky=tk.E)

var_old_ip = tk.StringVar(value="0.0.0.0")
var_new_ip = tk.StringVar(value="0.0.0.0")
tk.Label(root, text='旧公网IP:', width=8).grid(row=3, sticky=tk.E)
old_ip_input = tk.Entry(root, textvariable=var_old_ip,width=20).grid(row=3, column=1)
tk.Label(root, text='新公网IP:', width=8).grid(row=4, sticky=tk.E)
new_ip_input = tk.Entry(root,textvariable=var_new_ip, width=20).grid(row=4, column=1)

text_output = ScrolledText(root,width=66)   #use ScrolledText(下拉条)
text_output.grid(row=6, columnspan=2)

# text_output = tk.Text(root,width=70)
# text_output.pack(side='left',fill='y')
# text_output.grid()

root.mainloop()
Beispiel #20
0

def save():
    content = text.get("0.0", "end").encode('GBK')
    textfile = open(u'E:\\豆瓣电影排行250.txt', 'w')
    textfile.write(content)
    textfile.close()


root = Tk()

root.title('豆瓣电影top250')
root.geometry('820x500+400+200')

text = ScrolledText(root, font=('楷体', 15), width=80, height=20)
text.grid()

frame = Frame(root)
frame.grid()

# 启动爬虫功能
startButton = Button(frame, text='开始', font=('楷体', 18), command=start)
startButton.grid()
startButton.pack(side=LEFT)
# 保存爬取信息
saveButton = Button(frame, text='保存文件', font=('楷体', 18), command=save)
saveButton.grid()
saveButton.pack(side=LEFT)
# 退出程序
exitButton = Button(frame, text='退出', font=('楷体', 18), command=frame.quit)
exitButton.grid()
class ClustererGui(ttk.Frame):
    """GUI to open/save xml/text-files and visualize clustering."""

    def __init__(self, master=None):
        """Init GUI - get auto-split-sentences-option and standard test-file-folder from config-file."""
        ttk.Frame.__init__(self, master)
        self.grid(sticky=tk.N+tk.S+tk.E+tk.W)

        self.createWidgets()
        self.filepath = None
        self.xml_filepath = None
        self.filename = None
        self.article_id = None
        self.extraction = None
        self.author_no = None
        self.correct = None
        self.result = None
        self.colors = []

        config = ConfigParser.ConfigParser()
        config.read("config.cfg")
        params = dict(config.items("params"))
        article_dir = params['test_file_dir']
        self.auto_split_sentences = bool(int(params['auto_split_sentences']))
        self.show_knee_point = bool(int(params['show_knee_point']))
        self.show_knee_point = False # currently not supported in GUI-mode
        self.last_dir = article_dir


    def createWidgets(self):
        """Organize GUI."""
        top=self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)

        left_frame = ttk.Frame(self, relief="raised", borderwidth=1)
        left_frame.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
        left_frame.rowconfigure(0, weight=0)
        left_frame.rowconfigure(1, weight=1)
        left_frame.columnconfigure(0, weight=1)
        
        buttons_topleft = ttk.Frame(left_frame)
        buttons_topleft.grid(row=0, column=0)

        self.choose_file_btn = ttk.Button(buttons_topleft, text='choose file...',
            command=self.choose_file)
        self.choose_file_btn.grid(row=0, column=0)

        self.save_file_btn = ttk.Button(buttons_topleft, text='save file...',
            command=self.save_file)
        self.save_file_btn.grid(row=0, column=1)
        
        self.extract_feat_btn = ttk.Button(buttons_topleft, text='process',
            command=self.start_featureextr_thread)
        self.extract_feat_btn.grid(row=0, column=2)

        right_frame = ttk.Frame(self)
        right_frame.grid(row=0, column=1, sticky=tk.N+tk.S+tk.E+tk.W)
        right_frame.rowconfigure(0, weight=1)
        right_frame.rowconfigure(1, weight=1)
        
        self.distr_entry = ScrolledText(right_frame, width=30, height=30)
        self.distr_entry.grid(row=0, column=0, columnspan=2, sticky=tk.N)

        self.test_entry = ScrolledText(right_frame, width=30)
        self.test_entry.grid(row=1, column=0, columnspan=2, sticky=tk.N)

        self.scrolledText = ScrolledText(left_frame, undo=True, wrap=tk.WORD)
        self.scrolledText['font'] = ('Helvetica', '12')
        self.scrolledText.tag_configure('lines', background="#dddddd", foreground="black", font=('Helvetica', 9))
        self.scrolledText.tag_configure('blanks', background="#ffffff", foreground="black", font=('Helvetica', 9))        
        self.scrolledText.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)

        status_bar = ttk.Frame(self)
        status_bar.grid(row=1, column=0, columnspan=2, sticky=tk.W)
        status_bar.columnconfigure(0, weight=1, minsize=100)
        status_bar.columnconfigure(1, weight=1)

        self.status = tk.StringVar()
        self.status.set("ready")
        self.status_label = ttk.Label(status_bar, textvariable=self.status)
        self.status_label.grid(row=0, column=1, padx=10)

        self.progressbar = ttk.Progressbar(status_bar, mode='indeterminate', length=200)
        self.progressbar.grid(row=0, column=0, padx=3)
    
    def choose_file(self):
        """Choose text or xml file dialog."""
        self.filepath = askopenfilename(initialdir=self.last_dir, filetypes=(("text and xml files", ("*.txt","*.xml")),))
        if self.filepath:
            ext = os.path.splitext(self.filepath)[1]

            if ext == ".xml":
                '''save raw-text of xml-file to a new file and print it'''
                self.xml_filepath = self.filepath
                self.filepath = self.create_text_fromXML()

            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            self.scrolledText.delete(1.0, tk.END)
            self.print_raw_text()
            self.scrolledText.edit_reset()

    def create_text_fromXML(self):
        """Create text-file out of given xml-file."""
        new_filepath = os.path.splitext(self.filepath)[0] + ".txt"
        with codecs.open(self.filepath, 'r', 'UTF-8') as xml_file:
            xml_tree = etree.parse(xml_file)
        
        with codecs.open(new_filepath, 'w', 'UTF-8') as newFile:
            first_entry = True
            for entry in xml_tree.getroot():
                if entry.text is not None:
                    if not first_entry:
                        newFile.write("\n\n")
                    else:
                        first_entry = False
                    newFile.write(entry.text)
        return new_filepath



    def save_file(self):
        """Save text-file-dialog."""
        text = self.scrolledText.get("0.0", tk.END)
        if self.filepath is None:
            name = asksaveasfilename(initialdir=self.last_dir, defaultextension=".txt")
            if name:
                self.filepath = name
            else:
                return
        try:
            with codecs.open(self.filepath, 'w', 'UTF-8') as newFile:
                newFile.write(text.strip())
            self.scrolledText.edit_reset()
            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            return True
        except Exception:# as e:
            raise


    def start_featureextr_thread(self):
        """Start thread for feature extraction."""
        self.distr_entry.delete(1.0, tk.END)
        self.status.set("processing...")
        if self.filepath is None or self.article_id is None:
            tkMessageBox.showwarning(
                "Save File",
                "Save file for feature extraction.")
            return
        try:
            self.scrolledText.edit_undo()
            self.scrolledText.edit_redo()

            tkMessageBox.showwarning(
                "File changed",
                "File was changed, please save.")
            return
        except tk.TclError:
            self.extraction = clusterer.Clusterer(self.article_id, self.filepath, self.xml_filepath, self.auto_split_sentences, self.show_knee_point)

            self.ftr_extr_thread = threading.Thread(target=self.extract_features)
            self.ftr_extr_thread.daemon = True
            self.progressbar.start()
            self.ftr_extr_thread.start()
            self.after(1000, self.check_feat_thread)

    def check_feat_thread(self):
        """Check if feature extraction thread is still working - if not: visualize cluster-results."""
        if self.ftr_extr_thread.is_alive():
            self.after(1000, self.check_feat_thread)
        else:
            self.status.set("ready")

            # generate author-colormap
            self.colors = [None]*len(set(self.clusters))
            for k in set(self.clusters):  
                temp_color = plt.cm.spectral(np.float(k) / (np.max(self.clusters) + 1))
                if k == 0:
                    temp_color = plt.cm.spectral(0.05)
                self.colors[k] = self.convert_to_hex(temp_color)
            self.configure_colors()

            self.progressbar.stop()
            self.print_author_distr()
            self.print_text()
            if self.correct is not None and self.author_no is not None:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                s += "\n\n true number of authors: {}".format(self.author_no)
                s += "\n precision: {:.4f}".format(self.scores[0])
                s += "\n recall: {:.4f}".format(self.scores[1])
                s += "\n f1-score: {:.4f}".format(self.scores[2])
                s += "\n adjusted-rand-index: {:.4f}".format(self.scores[3])
                self.test_entry.insert(tk.INSERT, s)
            else:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                self.test_entry.insert(tk.INSERT, s)

    def extract_features(self):
        """Start feature extraction."""
        self.clusters, self.result, self.author_no, self.believe_score, self.scores = self.extraction.calc_cluster()

        if self.result is not None:
            c = Counter(self.result)
            self.correct = c[True] / sum(c.values()) * 100

    def print_text(self):
        """Print raw text with specified author-colors."""
        self.scrolledText.delete(1.0, tk.END)
        f = open(self.filepath)

        line_number = 0
        actual_line_number = 0
        for line in f:
            actual_line_number += 1
            if line.strip():
                s = str(line_number) + ' '+str(self.clusters[line_number]) + ' '+line
                s = line
                line_cluster = str(line_number) + ' '+str(self.clusters[line_number])+ ' '
                line_cluster = ('{:^'+str(14-len(line_cluster))+'}').format(line_cluster)
                self.scrolledText.insert(tk.INSERT, line_cluster, 'lines')
                try:
                    self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # if self.result[line_number]:
                    #     # correct assignment - print text foreground in white
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # else:
                    #     # false assignment - print text foreground in black
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]*10**2))
                except IndexError:
                    self.scrolledText.insert(tk.INSERT, s)
                except TypeError:
                        self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                line_number += 1
            else:
                s = line
                self.scrolledText.insert(tk.INSERT, s, 'blanks')
        f.close()

    def print_raw_text(self):
        """Print raw text."""
        f = open(self.filepath)
        for line in f:
            self.scrolledText.insert(tk.INSERT, line)
        f.close()

    def get_distribution(self, l=None):
        """Return Counter with author distribution in percent."""
        if l is None:
            l = self.clusters
        counter = Counter(l)
        sum_counter = sum(counter.values())

        for key in counter.iterkeys():
            counter[key] = counter[key] / sum_counter * 100
        return counter

    def print_author_distr(self):
        """Print author distribution with specified author-colors."""
        self.distr_entry.delete(1.0, tk.END)
        distr = self.get_distribution(self.clusters)

        for index, count in distr.most_common():
            author_i = "author "+str(index)+"{:>20}%\n".format(locale.format(u'%.2f',count))
            self.distr_entry.insert(tk.INSERT, author_i, str(index))

    def convert_to_hex(self, col):
        """Convert inter-tuple to hex-coded string."""
        red = int(col[0]*255)
        green = int(col[1]*255)
        blue = int(col[2]*255)
        return '#{r:02x}{g:02x}{b:02x}'.format(r=red,g=green,b=blue)

    def configure_colors(self):
        """Configure author-specific colors for author-distribution and cluster-results."""
        for i,c in enumerate(self.colors):
            self.scrolledText.tag_configure(str(i), background=c, foreground="white")            
            self.distr_entry.tag_configure(str(i), background=c, foreground="white")
Beispiel #22
0
class Application(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.root = master
        self.grid(sticky='WENS')
        self.createWidgets()
        self.queue = Queue()
        
        self.after(100, self.update_console)
        Thread(target=self.bootstrap).start()
    
    def write(self, text):
        self.queue.put(text)
        sys.stdout.write(text)
    
    def clear(self):
        self.queue.put(None)
    
    def update_console(self):
        try:
            while True:
                line = self.queue.get_nowait()
                if line is None:
                    self.console.delete(1.0, 'end')
                else:
                    self.console.insert('end', str(line))
                self.console.see('end')
                self.console.update_idletasks()
        except Empty:
            pass
        self.after(100, self.update_console)
    
    def bootstrap(self):
        from HAL import HAL

        write = self.write
        timer = self.timer = clock if os.name == 'nt' else time
        begin = timer()
        
        write('Initializing Engine...')
        self.hal = HAL()
        write(' done\n')

        try:
            dirname = sys.argv[1]
        except IndexError:
            dirname = os.getcwd()

        # Here's the legacy loading
        def loadfiles(pattern, attr, name):
            engine = getattr(self.hal.xail, attr)
            for file in glob(os.path.join(dirname, pattern)):
                write('%s Engine: Loading %s...' % (name, file))
                engine.load(io.open(file, encoding='utf-8'))
                write(' Done\n')
        loadfiles('*.gen', 'matrix', 'Matrix')
        loadfiles('*.mtx', 'substr', 'Substring')
        loadfiles('*.rgx', 'regex', 'Regex')
        
        # New unified XAIL loading
        files = glob(os.path.join(dirname, '*.xail'))
        max_length = max(map(len, files))
        for file in files:
            write('Loading %s' % file + ' ' * (max_length - len(file)) + '...')
            start = timer()
            self.hal.feed(io.open(file, encoding='utf-8'))
            write(' Finished in %8.2f ms\n' % ((timer() - start) * 1000))
        write('\n')

        user = getuser()
        prompt = '-%s: '%user
        halpro = '-HAL: '
        length = max(len(prompt), len(halpro))
        prompt.ljust(length)
        halpro.ljust(length)
        self.prompt, self.halpro = prompt, halpro
        self.context = {'USERNAME': user}

        write('Loaded in %.2f seconds.\n\n' % (timer() - begin))
        write(halpro + 'Hello %s. I am HAL %s.' % (user, self.hal.version) + '\n\n')

        self.entry.bind('<Return>', self.answer)
    
    def answer(self, e=None):
        write = self.write
        input = self.input.get()
        answer = self.hal.answer(input, self.context)
        write(self.prompt + input + '\n')
        write(self.halpro + answer + '\n\n')
        self.input.set('')
    
    def createWidgets(self):
        font_console = Font(family='Consolas', size=11)
        self.input = tk.StringVar()
        self.config(borderwidth=10)

        self.console = ScrolledText(self, font=font_console, state='normal')
        self.entry = ttk.Entry(self, textvariable=self.input, font=font_console)
        submit = ttk.Button(self, text='Submit')

        self.console.grid(columnspan=3, sticky='WENS')
        tk.LabelFrame(self, height=5).grid(row=1)
        self.entry.grid(row=2, sticky='WE')
        tk.LabelFrame(self, width=5).grid(row=2, column=1)
        submit.grid(row=2, column=2)
        submit['command'] = self.answer
        
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.root.wm_title('HAL')
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=0)
        self.rowconfigure(0, weight=1)
Beispiel #23
0
def create_frame2():
    root.title("Frame 2")
   
    frame1.destroy()
    
    frame2 = Frame(root, width = window_width, height = window_height, relief = "sunken")
    frame2.grid(column = 0, row = 0, padx = "20px", pady = "5px", sticky = (Tkinter.W+N+E))
    
    menubar = Menu(root)
    filemenu = Menu(menubar, tearoff=0)
    filemenu.add_command(label="New")
    filemenu.add_command(label="Open")
    filemenu.add_command(label="Save")
    filemenu.add_command(label="Save as...")
    filemenu.add_command(label="Close")
    
    filemenu.add_separator()
    
    filemenu.add_command(label="Exit", command=root.quit)
    menubar.add_cascade(label="File", menu=filemenu)
    editmenu = Menu(menubar, tearoff=0)
    editmenu.add_command(label="Undo")
    
    editmenu.add_separator()
    
    editmenu.add_command(label="Cut")
    editmenu.add_command(label="Copy")
    editmenu.add_command(label="Paste")
    editmenu.add_command(label="Delete")
    editmenu.add_command(label="Select All")
    
    menubar.add_cascade(label="Edit", menu=editmenu)
    analyzemenu = Menu(menubar, tearoff=0)
    analyzemenu.add_command(label="Graph", command = display_graph)
#     analyzemenu.add_command(label="About...")
    menubar.add_cascade(label="Analyze", menu=analyzemenu)
    
    helpmenu = Menu(menubar, tearoff=0)
    helpmenu.add_command(label="Help Index")
    helpmenu.add_command(label="About...")
    menubar.add_cascade(label="Help", menu=helpmenu)
    root.config(menu=menubar)
    
    var = StringVar()
    var.set(1)
    R1 = Radiobutton(frame2, text="TCP", variable=var, value=1)
    R1.grid(column = 0, row =1, sticky = (Tkinter.W))

    R2 = Radiobutton(frame2, text="IP", variable=var, value=2)
    R2.grid(column =1, row = 1, sticky = (Tkinter.W))

    R3 = Radiobutton(frame2, text="ICMP", variable=var, value=3)
    R3.grid(column = 0, row = 2, sticky = (Tkinter.W))
    
    R4 = Radiobutton(frame2, text="ARP", variable=var, value=4)
    R4.grid(column = 1, row = 2, sticky = (Tkinter.W))
    
    apply_button = Button(frame2, text = "Apply")
    apply_button.grid(column = 0, row = 3, sticky = (Tkinter.W), padx = "5px", pady = "5px", command = apply_program(var))
    
    start_time = time.time()
    
    headers = ["No.", "Source", "Time", "Destination", "Protocol", "Length"]
    rows = []
    col = []
    j= 0
    for i in range(4,5):
        for k in headers:
            e = Entry(frame2, justify = "center")
            e.grid(row=i, column= j, sticky=N+S+E+W)
            e.insert(END, k)
            j = j+1
            
#     values = [autoIncrement(), str(s_addr), time.time()- start_time,  str(d_addr), str(protocol), str(tcph_length)]
    j = 0  
    for i in range(5,15):
        for v in range(6):
            e = Entry(frame2, justify = "center")
            e.grid(row=i, column= v, sticky=N+S+E+W)
            e.insert(END, "")

            
            
    text2 = ScrolledText(frame2, width = 50, height = 10)
    text2.insert(0.0, "frame details here")
    text2.grid(columnspan = 2, sticky = (Tkinter.W+E+N), padx = "5px", pady = "5px")
Beispiel #24
0
button_open_file = Tkinter.Button(root, text='Open files...',
                                  width=11, command=open_file)
button_open_file.grid(column=0, row=0)
button_open_dir = Tkinter.Button(root, text='Open dir...',
                                 width=11, command=open_dir)
button_open_dir.grid(column=1, row=0)
quiet_var = Tkinter.BooleanVar()
button_quiet = Tkinter.Checkbutton(root, text='Quiet', width=11,
                                   command=quiet, indicatoron=False,
                                   variable=quiet_var)
button_quiet.grid(column=2, row=0, sticky='ns')
button_close = Tkinter.Button(root, text='Close', width=11, command=root.quit)
button_close.grid(column=3, row=0, sticky='e')
text = ScrolledText(root, state='disabled',
                    font=font, exportselection=True)
text.grid(column=0, row=1, columnspan=4, sticky='news')
text.tag_config('h2', foreground='blue', font=font_bold)
text.tag_config('h3', foreground='blue')
text.tag_config('h4', font=font_bold)
text.tag_config('good', foreground='#00a000')
text.tag_config('bad', foreground='red')
text.tag_config('txt', background='#e8e8e8')
root.columnconfigure(3, weight=999)
root.rowconfigure(1, weight=999)

def select_all():
    text.tag_remove('sel', 0.0, 'end')
    text.tag_add('sel', 0.0, 'end')

def text_copy():
    #text.event_generate("<<Copy>>")
Beispiel #25
0
class Application(Frame):
    #create global variables
    #chatColors = ['billColor', 'jeffColor', 'mattColor']
    buddies = {'Billy': PyChatBuddies.bill_the_conqueror, 'Matt': PyChatBuddies.matt_the_unstable, 'Jeff': PyChatBuddies.jeff_the_grand}


    randNum = 0
    userName = ""
    userColor = ""
    """
    function to initialize frame
    """
    def __init__(self, master):
        #initialize frame
        Frame.__init__(self,master)
        #screen to ask user for input
        self.login_screen()

    """
    function to generate random integers
    """
    def generateRand(self, size):
        #seed the randomness
        random.seed()
        #declaration allows us to modify global variable
        global randNum
        #random number between 0 and size of list -1 (to account for zero indexing
        randNum = random.randint(0, size - 1)
        return randNum
    """
    function for user input
    """
    def userInput(self, userName):
         #get text from input field
        lastResponse = self.inputField.get()
        userIndex = self.chatbox.index("insert")
        self.chatbox.insert('insert', userName + ": " + lastResponse + "\n")
        self.chatbox.tag_add("userColor", userIndex + "", "insert")
    """
    Function to remove friend
    """
    def removeFriend(self, username):
        buddyToRemove = self.friendsList.get(ACTIVE)
        del self.buddies[buddyToRemove]
        #TODO test
        #must rerender friendslist
        print self.buddies
        self.PyChat_Chat_Screen_friendsList(0,8,8,8, self.buddies)
    """
    Function for the AI to think of a response
    """
    def chatThink(self, event):
        #Make a copy of the username global variable
        userName = self.userName
        self.userInput(userName)
        #You do need to use the insert method after the delete method, as shown below
        self.inputField.delete(0, END)
        self.inputField.insert(0, "")
        self.inputField.configure(state='disabled')
        random
        #choose random buddy
        buddy = self.friendsList.get(ACTIVE)
        buddies = self.buddies
        #choose chat color
        #chatColorTag = buddies.get(buddy)
        chatList = buddies.get(buddy).get_greetings()
        chat = chatList[random.randrange(0, 3)]
        chatColor = buddies.get(buddy).get_chat_color()
        chatFont = buddies.get(buddy).get_chat_font()
        htmlTag = buddies.get(buddy).get_html_tag()
        #choose random chat
        #find the index to start the text coloring
        index = self.chatbox.index('insert')
        self.chatRespond(buddy, chat, chatColor, chatFont, htmlTag, index)
        self.inputField.configure(state='normal')

    """
    function to generate bot's Messages
    """
    def chatRespond(self, buddy, chat, chatColor, chatFont, htmlTag, index):
        self.chatbox.insert('insert', buddy + ": " + chat)
        userColor = ''
        self.chatbox.tag_configure(htmlTag, foreground = chatColor, font = chatFont)
        self.chatbox.tag_add(htmlTag, index + "", "insert")
        #scroll to end
        self.chatbox.see('end')
    """
    function to validate username input
    """
    def inputValidate(self, event):
        #TODO validate input
        self.userName = self.inputField.get()
        #make a copy to a local variable
        userName = self.userName
        #self.userProfilePicture = 'profile_pics/' + userName + '_thumbnail.png'
        #TODO do this for friends list
        tkMessageBox.showinfo('UserName', 'Your name is ' + userName)
         #create chat
        self.chat_screen()
        #create friends list
        #self.friends_screen()
        """
    function to upload a profile picture
    """
    def uploadProfilePicture(self):
        fileName = askopenfilename(filetypes = [('PNG FILES', '*.png')])
        #the following is a script to resize an image while maintaining the aspect ratio
        #http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio
        basewidth = 50
        img = PIL.Image.open(fileName)
        wpercent = (basewidth/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
        img.save('profile_pics/' + self.userName + '_thumbnail.png')
        self.userProfilePicture = 'profile_pics/' + self.userName + '_thumbnail.png'
        self.userProfileScreen()
    """
    function to create initial widgets
    """
    def login_screen(self):
        """
        Using a loop is infesible because the value of i will always be used and generate the phrases of the last buddies in the array
        best fix for right now is to use a finite number of buddies
        TODO make a class for these different screens
        """
        self.Pychat_newScreen("Welcome")
        self.enterLabel = Label(self, text = "Please enter a username")
        self.enterLabel.grid(row = 2, column = 2, columnspan = 2)
        #username input field
        self.inputField = Entry(self)
        self.inputField.grid(row =3, column = 3)
        self.inputField.bind('<Return>', self.inputValidate)

    """
    function to create initial widgets
    """
    def chat_screen(self):
        """
        Using a loop is infesible because the value of i will always be used and generate the phrases of the last buddies in the array
        best fix for right now is to use a finite number of buddies
        TODO make a class for these different screens
        """
        #destroy old frame and add new one
        self.destroy()
        self.Pychat_newScreen("PyChat")
        #making copies of global variables
        userName = self.userName
        userColor = self.userColor


        self.PyChat_Chat_Screen_profilePicture(10, 2, "You Have No Profile Picture Yet")
        #username label
        self.userNameLabel = Label(self, text = userName)
        self.userNameLabel.grid(row = 9, column = 2)
        #profile button
        self.profileButton = Button(self, text = "Profile", command = self.userProfileScreen)
        self.profileButton.grid(row = 9, column = 0)
        #chatbox
        self.chatbox = ScrolledText(self, wrap = 'word', width = 50, height = 20, bg = 'beige')
        self.chatbox.grid(row = 0, column = 0, rowspan =8, columnspan =7)
        #input field
        self.inputField = Entry(self)
        self.inputField.grid(row =9, column = 6)
        self.inputField.bind('<Return>', self.chatThink)
        #friends list
        self.PyChat_Chat_Screen_friendsList(0,8,8,8, self.buddies)


        #add friend
        #self.addFriendButton = Button(self, text = "Add friend", command = self.addFriendScreen)
        #self.addFriendButton.grid(row = 9, column = 8)
        #remove friend
        self.removeFriendButton = Button(self, text = "Remove friend", command =lambda self=self: self.removeFriend(userName))
        self.removeFriendButton.grid(row = 9, column = 9)
    """
    function to create profile widgets
    """
    def userProfileScreen(self):
        #destroy old frame and add new one
        self.destroy()
        Frame.__init__(self)
        self.grid(row = 0, column = 0)
        root.title(self.userName + "'s Profile")
        username = self.userName
        userColor = self.userColor
        self.uploadProfilePictureButton = Button(self, text = "Upload New Picture", command = self.uploadProfilePicture)
        self.uploadProfilePictureButton.grid()
        self.PyChat_Chat_Screen_profilePicture(0,0,"Please Upload a new Picture")
        #username
        #self.userNameLabel = Label(self, text = "username: " + userName)
        #TODO create change button
    def Pychat_newScreen(self, name):
        Frame.__init__(self)
        self.grid(row =0, column = 0)
        root.title(name)
    def PyChat_Chat_Screen_profilePicture(self, row, column, altText):
        try:
            profilePicture = self.userProfilePicture
            profilePictureThumbnail = self.profilePictureThumbnail
        except:
            profilePicture = 'none'
            profilePictureThumbnail = 'none'
        if hasattr(self, 'userProfilePicture'):
            self.profilePictureThumbnail = PhotoImage(file = profilePicture)
            self.profilePictureThumbnailLabel = Label(self, image = profilePictureThumbnail)
            self.profilePictureThumbnailLabel.grid(row=row, column=column)
        else:
            self.profilePictureThumbnailLabel = Label(self, text = altText)
            self.profilePictureThumbnailLabel.grid(row=row, column=column)
    def PyChat_Chat_Screen_friendsList(self, row, column, rowspan, colspan, buddies):
        self.friendsList = Listbox(self, selectmode=BROWSE)
        self.friendsList.grid(row = row, column = column, rowspan = rowspan, columnspan = colspan)
        #populate friendslist
        #TODO move friendslist to a file
        for buddy in buddies.keys():
            self.friendsList.insert(END, buddy)
Beispiel #26
0
# -*- coding: utf-8 -*-
from Tkinter import *
from ttk import *
from ScrolledText import ScrolledText


master = Tk()
Label(master, text=u"输入").grid(row=0, column=1)
Label(master, text=u"输出").grid(row=0, column=3)
txt_mobile= ScrolledText(master=master, width=30, height=70, yscrollcommand='1')
txt_mobile.grid(row=1, column=1)
btn = Button(master=master,  text=u"开始查询")

btn.grid(row=1, column=2, sticky=N, pady=150)


txt_locate = ScrolledText(master=master, width=40, height=70, yscrollcommand='1')
txt_locate.grid(row=1, column=3)

mainloop()
Beispiel #27
0
class MyMQTTClientCore(MQTTClientCore):
    def __init__(self, appname, clienttype):
        self.q = Queue.Queue(200)
        MQTTClientCore.__init__(self, appname, clienttype)
        self.clientversion = VERSION
        self.watchtopic = WATCHTOPIC
        self.workingdir = self.cfg.WORKINGDIR
    	self.interval = self.cfg.INTERVAL
        self.root = Tk()
        #build UI

        self.root.title("MQTT Dashboard")
        frame = Frame(self.root)
        frame.pack()
        host_ofx=0
        Label(frame, text="Hostname:").grid(row=host_ofx, column=0, sticky=W)
        self.host_text = Text(frame, height=1, width=30)
        self.host_text.grid(row=host_ofx, column=1, columnspan=3, sticky=W)
        self.host_text.delete(1.0, END)
        self.host_text.insert(END, self.mqtthost)
        self.button_connect = Button(frame, text="Connect", command=connect)
        self.button_connect.grid(row=host_ofx, column=4, columnspan=2, sticky=W)
        self.button_disconnect = Button(frame, text="Disconnect", command=disconnect)
        self.button_disconnect.grid(row=host_ofx, column=5, columnspan=2)

        fill0_ofx=host_ofx+1
        Label(frame, text="").grid(row=fill0_ofx, column=0)

        version_ofx=fill0_ofx+1
        Label(frame, text="Version:").grid(row=version_ofx, column=0, sticky=W)
        self.version_text = Text(frame, height=1, width=30, state=DISABLED)
        self.version_text.grid(row=version_ofx, column=1, columnspan=3)
        self.revision_text = Text(frame, height=1, width=30, state=DISABLED)
        self.revision_text.grid(row=version_ofx, column=4, columnspan=3)
        self.timestamp_text = Text(frame, height=1, width=30, state=DISABLED)
        self.timestamp_text.grid(row=version_ofx, column=7, columnspan=3)

        fill1_ofx=version_ofx+1
        Label(frame, text="").grid(row=fill1_ofx, column=0)

        load_ofx=fill1_ofx+1
        Label(frame, text="Load:").grid(row=load_ofx, column=0, sticky=W)
        Label(frame, text="Per Sec").grid(row=load_ofx, column=1, columnspan=2)
        Label(frame, text="Per 1 Min").grid(row=load_ofx, column=3, columnspan=2)
        Label(frame, text="Per 5 Min").grid(row=load_ofx, column=5, columnspan=2)
        Label(frame, text="Per 15 Min").grid(row=load_ofx, column=7, columnspan=2)
        Label(frame, text="Total").grid(row=load_ofx, column=9, columnspan=2)

        Label(frame, text="Received").grid(row=load_ofx+1, column=2)
        Label(frame, text="Sent").grid(row=load_ofx+1, column=1)
        Label(frame, text="Received").grid(row=load_ofx+1, column=4)
        Label(frame, text="Sent").grid(row=load_ofx+1, column=3)
        Label(frame, text="Received").grid(row=load_ofx+1, column=6)
        Label(frame, text="Sent").grid(row=load_ofx+1, column=5)
        Label(frame, text="Received").grid(row=load_ofx+1, column=8)
        Label(frame, text="Sent").grid(row=load_ofx+1, column=7)
        Label(frame, text="Received").grid(row=load_ofx+1, column=10)
        Label(frame, text="Sent").grid(row=load_ofx+1, column=9)

        Label(frame, text="Bytes").grid(row=load_ofx+2, column=0, sticky=W)
        self.bytes_ss_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_ss_text.grid(row=load_ofx+2, column=1)
        self.bytes_sr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_sr_text.grid(row=load_ofx+2, column=2)
        self.bytes_1ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_1ms_text.grid(row=load_ofx+2, column=3)
        self.bytes_1mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_1mr_text.grid(row=load_ofx+2, column=4)
        self.bytes_5ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_5ms_text.grid(row=load_ofx+2, column=5)
        self.bytes_5mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_5mr_text.grid(row=load_ofx+2, column=6)
        self.bytes_15ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_15ms_text.grid(row=load_ofx+2, column=7)
        self.bytes_15mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.bytes_15mr_text.grid(row=load_ofx+2, column=8)
        self.bytes_ts_text = Text(frame, height=1, width=16, state=DISABLED)
        self.bytes_ts_text.grid(row=load_ofx+2, column=9)
        self.bytes_tr_text = Text(frame, height=1, width=16, state=DISABLED)
        self.bytes_tr_text.grid(row=load_ofx+2, column=10)

        Label(frame, text="Messages").grid(row=load_ofx+3, column=0, sticky=W)
        self.messages_ss_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_ss_text.grid(row=load_ofx+3, column=1)
        self.messages_sr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_sr_text.grid(row=load_ofx+3, column=2)
        self.messages_1ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_1ms_text.grid(row=load_ofx+3, column=3)
        self.messages_1mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_1mr_text.grid(row=load_ofx+3, column=4)
        self.messages_5ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_5ms_text.grid(row=load_ofx+3, column=5)
        self.messages_5mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_5mr_text.grid(row=load_ofx+3, column=6)
        self.messages_15ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_15ms_text.grid(row=load_ofx+3, column=7)
        self.messages_15mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.messages_15mr_text.grid(row=load_ofx+3, column=8)
        self.messages_ts_text = Text(frame, height=1, width=16, state=DISABLED)
        self.messages_ts_text.grid(row=load_ofx+3, column=9)
        self.messages_tr_text = Text(frame, height=1, width=16, state=DISABLED)
        self.messages_tr_text.grid(row=load_ofx+3, column=10)

        Label(frame, text="Published").grid(row=load_ofx+4, column=0, sticky=W)
#        self.publish_ss_text = Text(frame, height=1, width=10, state=DISABLED)
#        self.publish_ss_text.grid(row=5+1, column=1)
#        self.publish_sr_text = Text(frame, height=1, width=10, state=DISABLED)
#        self.publish_sr_text.grid(row=load_ofx+4, column=2)
        self.publish_1ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_1ms_text.grid(row=load_ofx+4, column=3)
        self.publish_1mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_1mr_text.grid(row=load_ofx+4, column=4)
        self.publish_5ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_5ms_text.grid(row=load_ofx+4, column=5)
        self.publish_5mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_5mr_text.grid(row=load_ofx+4, column=6)
        self.publish_15ms_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_15ms_text.grid(row=load_ofx+4, column=7)
        self.publish_15mr_text = Text(frame, height=1, width=10, state=DISABLED)
        self.publish_15mr_text.grid(row=load_ofx+4, column=8)
#        self.publish_ts_text = Text(frame, height=1, width=10, state=DISABLED)
#        self.publish_ts_text.grid(row=load_ofx+4, column=9)
#        self.publish_tr_text = Text(frame, height=1, width=10, state=DISABLED)
#        self.publish_tr_text.grid(row=load_ofx+4, column=10)

        Label(frame, text="Connections").grid(row=load_ofx+5, column=0, sticky=W)
#        self.connections_s_text = Text(frame, height=1, width=20, state=DISABLED)
#        self.connections_s_text.grid(row=load_ofx+5, column=1, columnspan=2)
        self.connections_1m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.connections_1m_text.grid(row=load_ofx+5, column=3, columnspan=2)
        self.connections_5m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.connections_5m_text.grid(row=load_ofx+5, column=5, columnspan=2)
        self.connections_15m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.connections_15m_text.grid(row=load_ofx+5, column=7, columnspan=2)
#        self.connections_t_text = Text(frame, height=1, width=20, state=DISABLED)
#        self.connections_t_text.grid(row=load_ofx+5, column=9, columnspan=2)

        Label(frame, text="Sockets").grid(row=load_ofx+6, column=0, sticky=W)
#        self.sockets_s_text = Text(frame, height=1, width=20, state=DISABLED)
#        self.sockets_s_text.grid(row=load_ofx+6, column=1, columnspan=2)
        self.sockets_1m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.sockets_1m_text.grid(row=load_ofx+6, column=3, columnspan=2)
        self.sockets_5m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.sockets_5m_text.grid(row=load_ofx+6, column=5, columnspan=2)
        self.sockets_15m_text = Text(frame, height=1, width=21, state=DISABLED)
        self.sockets_15m_text.grid(row=load_ofx+6, column=7, columnspan=2)
#        self.sockets_t_text = Text(frame, height=1, width=20, state=DISABLED)
#        self.sockets_t_text.grid(row=load_ofx+6, column=9, columnspan=2)

        fill2_ofx=load_ofx+7
        Label(frame, text="").grid(row=fill2_ofx, column=0)

        clients_ofx=fill2_ofx+1
        clients_ofy=0
        Label(frame, text="Clients:").grid(row=clients_ofx, column=clients_ofy, sticky=W)
        Label(frame, text="Active").grid(row=clients_ofx+1, column=clients_ofy+1, sticky=W)
        self.active_text = Text(frame, height=1, width=7, state=DISABLED)
        self.active_text.grid(row=clients_ofx+1, column=clients_ofy+2)
        Label(frame, text="Inactive").grid(row=clients_ofx+2, column=clients_ofy+1, sticky=W)
        self.inactive_text = Text(frame, height=1, width=7, state=DISABLED)
        self.inactive_text.grid(row=clients_ofx+2, column=clients_ofy+2)
        Label(frame, text="Total").grid(row=clients_ofx+3, column=clients_ofy+1, sticky=W)
        self.clients_total_text = Text(frame, height=1, width=7, state=DISABLED)
        self.clients_total_text.grid(row=clients_ofx+3, column=clients_ofy+2)
        Label(frame, text="Expired").grid(row=clients_ofx+4, column=clients_ofy+1, sticky=W)
        self.expired_text = Text(frame, height=1, width=7, state=DISABLED)
        self.expired_text.grid(row=clients_ofx+4, column=clients_ofy+2)
        Label(frame, text="Maximum").grid(row=clients_ofx+5, column=clients_ofy+1, sticky=W)
        self.max_text = Text(frame, height=1, width=7, state=DISABLED)
        self.max_text.grid(row=clients_ofx+5, column=clients_ofy+2)

        other_ofx=fill2_ofx+1
        other_ofy=8
        Label(frame, text="Other:").grid(row=other_ofx, column=other_ofy, sticky=W)
        Label(frame, text="Uptime").grid(row=other_ofx+1, column=other_ofy+1, sticky=W)
        self.uptime_text = Text(frame, height=1, width=16, state=DISABLED)
        self.uptime_text.grid(row=other_ofx+1, column=other_ofy+2)
        Label(frame, text="Heap Current").grid(row=other_ofx+2, column=other_ofy+1, sticky=W)
        self.heap_text = Text(frame, height=1, width=16, state=DISABLED)
        self.heap_text.grid(row=other_ofx+2, column=other_ofy+2)
        Label(frame, text="Heap Max.").grid(row=other_ofx+3, column=other_ofy+1, sticky=W)
        self.heap_max_text = Text(frame, height=1, width=16, state=DISABLED)
        self.heap_max_text.grid(row=other_ofx+3, column=other_ofy+2)
#        Label(frame, text="Bridges:").grid(row=other_ofx+4, column=other_ofy, sticky=W)
#        self.connections_text = Text(frame, height=3, width=8, state=DISABLED)
#        self.connections_text.grid(row=other_ofx+5, column=other_ofy+2, rowspan=3)

        msg_ofx=fill2_ofx+1
        msg_ofy=4
        Label(frame, text="Messages:").grid(row=msg_ofx, column=msg_ofy, sticky=W)
        Label(frame, text="Retained").grid(row=msg_ofx+1, column=msg_ofy+1, sticky=W)
        self.retained_text = Text(frame, height=1, width=7, state=DISABLED)
        self.retained_text.grid(row=msg_ofx+1, column=msg_ofy+2)
        Label(frame, text="Stored").grid(row=msg_ofx+2, column=msg_ofy+1, sticky=W)
        self.stored_text = Text(frame, height=1, width=7, state=DISABLED)
        self.stored_text.grid(row=msg_ofx+2, column=msg_ofy+2)
        Label(frame, text="Dropped").grid(row=msg_ofx+3, column=msg_ofy+1, sticky=W)
        self.dropped_text = Text(frame, height=1, width=7, state=DISABLED)
        self.dropped_text.grid(row=msg_ofx+3, column=msg_ofy+2)
        Label(frame, text="Inflight").grid(row=msg_ofx+4, column=msg_ofy+1, sticky=W)
        self.inflight_text = Text(frame, height=1, width=7, state=DISABLED)
        self.inflight_text.grid(row=msg_ofx+4, column=msg_ofy+2)
        Label(frame, text="Subscriptns").grid(row=msg_ofx+5, column=msg_ofy+1, sticky=W)
        self.subscriptions_text = Text(frame, height=1, width=7, state=DISABLED)
        self.subscriptions_text.grid(row=msg_ofx+5, column=msg_ofy+2)

        fill3_ofx=msg_ofx+8
        Label(frame, text="").grid(row=fill3_ofx, column=0)

        log_ofx=fill3_ofx+1
        Label(frame, text="Log:").grid(row=log_ofx, column=0, sticky=W)
        self.log_text = ScrolledText(frame, height=6, state=DISABLED)
        self.log_text.grid(row=log_ofx+1, column=0, columnspan=11, sticky=N+W+E+S)
        self.root.update()
        self.root.protocol("WM_DELETE_WINDOW", self.closehandler)
        self.root.update()
        self.t = threading.Thread(target=self.do_thread_loop)

    def do_thread_loop(self):
        self.main_loop()        

    def on_connect(self, mself, obj, rc):
        MQTTClientCore.on_connect(self, mself, obj, rc)
        self.mqttc.subscribe("$SYS/#", qos=2)

    def on_message(self, mself, obj, msg):
        MQTTClientCore.on_message(self, mself, obj, msg)
        obj.put(msg)

    def closehandler(self):
        print "closing window"
        self.root.destroy()
        self.root.quit()
Beispiel #28
0
class ExportApp(Frame):
    """GUI version of the Phoshare tool."""

    def __init__(self, master=None):
        """Initialize the app, setting up the UI."""
        Frame.__init__(self, master, padding=10)

        top = self.winfo_toplevel()
        menu_bar = Menu(top)
        top["menu"] = menu_bar

        apple = Menu(menu_bar, name='apple')
        menu_bar.add_cascade(label='Phoshare', menu=apple)
        apple.add_command(label="About Phoshare", command=self.__aboutHandler)

        sub_menu = Menu(menu_bar, name='help')
        menu_bar.add_cascade(label="Help", menu=sub_menu)
        sub_menu.add_command(label="Phoshare Help", command=self.help_buttons)

        self.thread_queue = Queue.Queue(maxsize=100)
        self.active_library = None

        top.columnconfigure(0, weight=1)
        top.rowconfigure(0, weight=1)
        self.grid(sticky=N+S+E+W)

        self.valid_library = False
        self.exiftool = False

        self.iphoto_library = StringVar()
        self.iphoto_library_status = StringVar()
        self.browse_library_button = None
        self.export_folder = StringVar()

        self.library_status = None
        self.dryrun_button = None
        self.export_button = None
        self.text = None

        self.events = StringVar()
        self.albums = StringVar()
        self.smarts = StringVar()

        self.foldertemplate = StringVar()
        self.nametemplate = StringVar()
        self.captiontemplate = StringVar()

        self.update_var = IntVar()
        self.delete_var = IntVar()
        self.originals_var = IntVar()
        self.link_var = IntVar()
        self.folder_hints_var = IntVar()
        self.faces_box = None
        self.faces_var = IntVar()
        self.face_keywords_box = None
        self.face_keywords_var = IntVar()
        self.face_albums_var = IntVar()
        self.face_albums_text = StringVar()

        self.iptc_box = None
        self.iptc_all_box = None
        self.iptc_var = IntVar()
        self.iptc_all_var = IntVar()

        self.gps_box = None
        self.gps_var = IntVar()
        self.verbose_var = IntVar()

        self.info_icon = PhotoImage(file="info-b16.gif")

        self.create_widgets()

        # Set up logging so it gets redirected to the text area in the app.
        self.logging_handler = logging.StreamHandler(self)
        self.logging_handler.setLevel(logging.WARN)
        _logger.addHandler(self.logging_handler)

    def __aboutHandler(self):
        HelpDialog(self, """%s %s

  Copyright 2010 Google Inc.

http://code.google.com/p/phoshare""" % (phoshare_version.PHOSHARE_VERSION,
	phoshare_version.PHOSHARE_BUILD),
                   title="About Phoshare")

    def init(self):
        """Initializes processing by launching background thread checker and
           initial iPhoto library check."""
        self.thread_checker()
        if exiftool.check_exif_tool(sys.stdout):
            self.exiftool = True
            self.faces_box.configure(state=NORMAL)
            self.face_keywords_box.configure(state=NORMAL)
            self.iptc_box.configure(state=NORMAL)
            self.iptc_all_box.configure(state=NORMAL)
            self.gps_box.configure(state=NORMAL)

        options = self.Options()
        options.load()
        self.init_from_options(options)
        self.check_iphoto_library()

    def init_from_options(self, options):
        """Populates the UI from options."""
        self.iphoto_library.set(options.iphoto)
        self.export_folder.set(options.export)
        self.albums.set(su.fsdec(options.albums))
        self.events.set(su.fsdec(options.events))
        self.smarts.set(su.fsdec(options.smarts))
        self.foldertemplate.set(su.unicode_string(options.foldertemplate))
        self.nametemplate.set(su.unicode_string(options.nametemplate))
        self.captiontemplate.set(su.unicode_string(options.captiontemplate))
        self.update_var.set(_int_from_bool(options.update))
        self.delete_var.set(_int_from_bool(options.delete))
        self.originals_var.set(_int_from_bool(options.originals))
        self.link_var.set(_int_from_bool(options.link))
        self.folder_hints_var.set(_int_from_bool(options.folderhints))
        self.faces_var.set(_int_from_bool(options.faces) and self.exiftool)
        self.face_keywords_var.set(_int_from_bool(options.face_keywords) and
                                   self.exiftool)
        self.face_albums_var.set(_int_from_bool(options.facealbums))
        self.face_albums_text.set(options.facealbum_prefix)
        if options.iptc and self.exiftool:
            self.iptc_var.set(1)
            if options.iptc == 2:
                self.iptc_all_var.set(1)
        self.gps_var.set(_int_from_bool(options.gps) and self.exiftool)

    def _add_section(self, container, text, help_command):
        """Adds a new UI section with a bold label and an info button.

        Args:
          container: UI element that will contain this new item
          row: row number in grid. Uses two rows.
          text: label frame text.
          help_command: command to run when the info button is pressed.
        Returns: tuple of new section and content frames.
        """
        section_frame = Frame(container)
        section_frame.columnconfigure(0, weight=1)
        label = Label(section_frame, text=text)
        label.config(font=_BOLD_FONT)
        label.grid(row=0, column=0, sticky=W, pady=5)
        Button(section_frame, image=self.info_icon,
               command=help_command).grid(row=0, column=1, sticky=E)

        content_frame = Frame(section_frame)
        content_frame.grid(row= 1, column=0, columnspan=2, sticky=N+S+E+W, pady=5)

        return (section_frame, content_frame)

    def _create_button_bar(self, container, row):
        """Creates the button bar with the Dry Run and Export buttons.

        Args:
          row: row number in grid.
        Returns: next row number in grid.
        """
        button_bar = Frame(container)
        button_bar.grid(row=row, column=0, sticky=E+W, padx=10)
        button_bar.columnconfigure(0, weight=1)
        verbose_box = Checkbutton(button_bar, text="Show debug output", var=self.verbose_var)
        verbose_box.grid(row=0, column=0, sticky=E)
        self.dryrun_button = Button(button_bar, text="Dry Run",
                                    command=self.do_dryrun, state=DISABLED)
        self.dryrun_button.grid(row=0, column=1, sticky=E, pady=5)
        self.export_button = Button(button_bar, text="Export",
                                    command=self.do_export, state=DISABLED)
        self.export_button.grid(row=0, column=2, pady=5)
        return row + 1

    def _create_library_tab(self, library_tab):
        library_tab.columnconfigure(0, weight=1)
        row = 0

        f = Frame(library_tab)
        f.grid(row=row, columnspan=2, stick=E+W, padx=5, pady=5)
        row += 1
        f.columnconfigure(1, weight=1)

        Label(f, text="iPhoto Library:").grid(sticky=E)
        iphoto_library_entry = Entry(f, textvariable=self.iphoto_library)
        iphoto_library_entry.grid(row=0, column=1, sticky=E+W)
        self.browse_library_button = Button(f, text="Browse...",
                                            command=self.browse_library)
        self.browse_library_button.grid(row=0, column=2)

        self.library_status = Label(f, textvariable=self.iphoto_library_status)
        self.library_status.grid(row=1, column=1, sticky=W)

        (cf, lf) = self._add_section(library_tab, "Events, Albums and Smart Albums",
                                     self.help_events)
        cf.grid(row=row, columnspan=2, stick=E+W)
        row += 1
        lf.columnconfigure(1, weight=1)
        Label(lf, text="Events:").grid(sticky=E)
        events_entry = Entry(lf, textvariable=self.events)
        events_entry.grid(row=0, column=1, sticky=EW)

        Label(lf, text="Albums:").grid(sticky=E)
        albums_entry = Entry(lf, textvariable=self.albums)
        albums_entry.grid(row=1, column=1, sticky=EW)

        Label(lf, text="Smart Albums:").grid(sticky=E)
        smarts_entry = Entry(lf, textvariable=self.smarts)
        smarts_entry.grid(row=2, column=1, columnspan=3, sticky=EW)

    def _create_files_tab(self, files_tab):
        files_tab.columnconfigure(0, weight=1)
        # Export folder and options
        row = 0
        (cf, lf) = self._add_section(files_tab, "Export Folder and Options", self.help_export)
        cf.grid(row=row, columnspan=2, stick=E+W)
        row += 1
        lf.columnconfigure(1, weight=1)
        label = Label(lf, text="Export Folder:")
        label.grid(sticky=E)
        export_folder_entry = Entry(lf, textvariable=self.export_folder)
        export_folder_entry.grid(row=0, column=1, columnspan=2, sticky=E+W)
        Button(lf, text="Browse...",
               command=self.browse_export).grid(row=0, column=3)

        update_box = Checkbutton(lf, text="Overwrite changed pictures",
                                 var=self.update_var)
        update_box.grid(row=1, column=1, sticky=W)
        originals_box = Checkbutton(lf, text="Export originals",
                                    var=self.originals_var)
        originals_box.grid(row=2, column=1, sticky=W)
        hint_box = Checkbutton(lf, text="Use folder hints",
                               var=self.folder_hints_var)
        hint_box.grid(row=3, column=1, sticky=W)

        delete_box = Checkbutton(lf, text="Delete obsolete pictures",
                                 var=self.delete_var)
        delete_box.grid(row=4, column=1, sticky=W)
        link_box = Checkbutton(lf, text="Use file links", var=self.link_var)
        link_box.grid(row=5, column=1, sticky=W)

        # Templates ----------------------------------------
        (cf, lf) = self._add_section(files_tab, "Name Templates", self.help_templates)
        cf.grid(row=row, columnspan=2, stick=E+W)
        row += 1
        lf.columnconfigure(1, weight=1)
        Label(lf, text="Folder names:").grid(sticky=E)
        foldertemplate_entry = Entry(lf, textvariable=self.foldertemplate)
        foldertemplate_entry.grid(row=0, column=1, sticky=EW)

        Label(lf, text="File names:").grid(sticky=E)
        nametemplate_entry = Entry(lf, textvariable=self.nametemplate)
        nametemplate_entry.grid(row=1, column=1, sticky=EW)

        Label(lf, text="Captions:").grid(sticky=E)
        captiontemplate_entry = Entry(lf, textvariable=self.captiontemplate)
        captiontemplate_entry.grid(row=2, column=1, sticky=EW)

    def _create_metadata_tab(self, metadata_tab):
        metadata_tab.columnconfigure(0, weight=1)
        row = 0
        # Metadata --------------------------------------------
        (cf, lf) = self._add_section(metadata_tab, "Metadata", self.help_metadata)
        cf.grid(row=row, columnspan=2, stick=E+W)
        row += 1
        self.iptc_box = Checkbutton(lf,
                                    text=("Export metadata (descriptions, "
                                          "keywords, ratings, dates)"),
                                    var=self.iptc_var, state=DISABLED,
                                    command=self.change_iptc_box)
        self.iptc_box.grid(row=0, column=0, columnspan=2, sticky=W)

        self.iptc_all_box = Checkbutton(lf,
                                        text="Check previously exported images",
                                        var=self.iptc_all_var,
                                        command=self.change_metadata_box,
                                        state=DISABLED)
        self.iptc_all_box.grid(row=1, column=0, sticky=W)

        self.gps_box = Checkbutton(lf,
                                   text="Export GPS data",
                                   var=self.gps_var,
                                   command=self.change_metadata_box,
                                   state=DISABLED)
        self.gps_box.grid(row=2, column=0, sticky=W)

        # Faces ---------------------------------------------------
        (cf, lf) = self._add_section(metadata_tab, "Faces", self.help_faces)
        cf.grid(row=row, columnspan=2, stick=E+W)
        row += 1
        lf.columnconfigure(2, weight=1)
        self.faces_box = Checkbutton(lf, text="Copy faces into metadata",
                                     var=self.faces_var, state=DISABLED,
                                     command=self.change_metadata_box)
        self.faces_box.grid(row=0, column=0, sticky=W)

        self.face_keywords_box = Checkbutton(
            lf,
            text="Copy face names into keywords",
            var=self.face_keywords_var,
            command=self.change_metadata_box,
            state=DISABLED)
        self.face_keywords_box.grid(row=1, column=0, sticky=W)

        checkbutton = Checkbutton(lf, text="Export faces into folders",
                                  var=self.face_albums_var)
        checkbutton.grid(row=2, column=0, sticky=W)
        label = Label(lf, text="Faces folder prefix:")
        label.grid(row=2, column=1, sticky=E)
        entry = Entry(lf, textvariable=self.face_albums_text)
        entry.grid(row=2, column=2, sticky=E+W)

    def create_widgets(self):
        """Builds the UI."""
        self.columnconfigure(0, weight=1)
        n = Notebook(self)
        n.grid(row=0, sticky=E+W+N+S)

        library_tab = Frame(n)
        n.add(library_tab, text='Library')
        self._create_library_tab(library_tab)

        files_tab = Frame(n)
        n.add(files_tab, text='Files')
        self._create_files_tab(files_tab)

        metadata_tab = Frame(n)
        n.add(metadata_tab, text='Metadata')
        self._create_metadata_tab(metadata_tab)

        self._create_button_bar(self, 1)

        self.text = ScrolledText(self, borderwidth=4, relief=RIDGE, padx=4,
                                 pady=4)
        self.text.grid(row=2, column=0, sticky=E+W+N+S)
        self.rowconfigure(2, weight=1)

    def change_iptc_box(self):
        """Clears some options that depend on the metadata export option."""
        mode = self.iptc_var.get()
        if not mode:
            self.faces_var.set(0)
            self.face_keywords_var.set(0)
            self.iptc_all_var.set(0)
            self.gps_var.set(0)

    def change_metadata_box(self):
        """Sets connected options if an option that needs meta data is changed.
        """
        mode = (self.faces_var.get() or self.face_keywords_var.get() or
                self.iptc_all_var.get() or self.gps_var.get())
        if mode:
            self.iptc_var.set(1)

    def help_events(self):
        HelpDialog(self, """Events, Albums and Smart Albums

Selects which events, albums, or smart albums to export.

Each field is a regular expression, and at least one must be filled in.
Matches are done against the beginning of the event or album name. An
entry in Events of
    Family
will export all events that start with "Family", including "Family 2008"
and "Family 2009". "|" separates alternate patterns, so
    Family|Travel
will export all events that start with either "Family" or "Travel".

"." matches any character, and therefore,
    .
will export all events. To export all events with "2008" in the name, use
    .*2008

For more details on regular expressions, see
    http://en.wikipedia.org/wiki/Regular_expression""")

    def help_templates(self):
        HelpDialog(self, """Folder, file, and image caption templates.

Templates are strings with place holders for values. The place holders have
the format "{name}". Everything else in the template will be copied. Examples:
  {title}
  {yyyy}/{mm}/{dd} {title} - generates "2010/12/31 My Birthday" if the date
      of the pictures is Dec 31, 2010, and the title is "My Birthday".
  {yyyy} Event: {event} - generates "2010 Event: Birthday" for an event with
      any date in 2010 and the name "Birthday".

Available place holders for folder names:
  {name} - name of the album or event.
  {hint} - folder hint (taken from line event or album description starting with
           @).
  {yyyy} - year of album or event date.
  {mm} - month of album or event date.
  {dd} - date of album or event date.

Available place holders for file names:
  {album} - name of album (or in the case of an event, the name of the event).
  {index} - number of image in album, starting at 1.
  {index0} - number of image in album, padded with 0s, so that all numbers have
             the same length.
  {event} - name of the event. In the case of an album, the name of the event
            to which the image belongs.
  {event_index} - number of image in the event, starting at 1. If the case of an
                  album, this number will be based on the event to which the
                  image belongs.
  {event_index0} - same as {event_index}, but padded with leading 0s so that all
                   values have the same length.
  {title} - image title.
  {yyyy} - year of image.
  {mm} - month of image (01 - 12).
  {dd} - day of image (01 - 31).

  If you are using {album}/{index}/{index0} place holders, the image will be
  named based on whatever album or event it is contained. That means an image
  in two albums will be exported with different names, even so the files are
  identical. If you want to use the same name for each image, regardless of
  which album it is in, use {event}, {event_index}, and {event_index0} instead.

Available place holders for captions:
  {title} - image title.
  {description} - image description.
  {title_description} - concatenated image title and description, separated by a
                        : if both are set.
  {yyyy} - year of image.
  {mm} - month of image (01 - 12).
  {dd} - day of image (01 - 31).
""")

    def help_buttons(self):
        HelpDialog(self, """Export modes.

Click on "Dry Run" to see what Phoshare would do without actually modifying any
files.

Click on "Export" to export your files using the current settings.

All your settings will be saved when you click either Dry Run and Export, and
re-loaded if you restart Phoshare.

Check "Show debug output" to generate additional output message that can assist
in debugging Phoshare problems.
""")

    def help_export(self):
        HelpDialog(self, """Export Settings

Export Folder: path to the folder for exporting images.

Overwrite changed pictures: If set, pictures that already exist in the export
                            folder will be overriden if an different version
                            exist in iPhoto. Any edits made to previously
                            exported images in the export folder will be lost!
                            Use Dry Run to see which files would be overwritten.

Export originals: If set, and an image has been modified in iPhoto, both the
                  original and the edited version will be exported. The original
                  will be stored in a sub-folder called "Originals".

Use folder hints: By default, each exported event or album will become a folder
                  in the export folder. With folder hints, a sub-folder name can
                  be given in the event or album description by adding a line
                  starting with a @ character. Example:
                      Family Vacation
                      @Vacation
                  would export all images in that event into a sub-folder called
                  "Vacation".

Delete obsolete pictures: If set, any image, movie file or folder in the export
                          folder that does not exist in the iPhoto library will
                          be deleted. Use Dry Run to see which files would be
                          deleted.

Use file links: Don't copy images during export, but make a link to the files
                in the iPhoto library instead. This option is only available
                if the export folder is on the same drive as the iPhoto library.
                This option will save a lot of disk space because it avoids
                making copies of all your images and videos. Using this option
                causes the metadata of the images IN YOUR IPHOTO LIBRARY to be
                modified. While phoshare should not cause any problems to your
                images, it is best to use this option only if you have a backup
                of your iPhoto library, and you know how to restore your library
                from the backup. For more details on link mode, see
                https://sites.google.com/site/phosharedoc/Home#TOC-link-mode""")

    def help_faces(self):
        HelpDialog(self, """Faces options.

Copy faces into metadata: faces tags and face regions will be copied into the
                          image metadata using the Microsoft Photo Region
                          Schema:
               http://msdn.microsoft.com/en-us/library/ee719905(VS.85).aspx

Copy faces names into keywords: If set, face names will be merged into image
                                keywords. Requires "Export metadata" checked.

Export faces into folders: If checked, folders will be created for each face
                           tag, each containing all the images tagged with
                           that person.

Faces folder prefix: If set, the string will be used as a prefix for the
                     face export folders if "Exported faces into folders"
                     is checked. This can be just a value like "Face: ", or
                     a sub-folder name like "Faces/" if it ends with a "/"

Metadata options will be disabled if exiftool is not available.
""")

    def help_metadata(self):
        HelpDialog(self, """Metadata options.

Export metadata: sets the description, keywords, rating and date metadata in the
                 exported images to match the iPhoto settings.

Check previously exported images: If not checked, metadata will only be set for new or
                        updated images. If checked, metadata will be checked in
                        all images, including ones that were previously
                        exported. This is much slower.

Export GPS data: export the GPS coordinates into the image metadata.

Metadata options will be disabled if exiftool is not available.""")

    def check_iphoto_library(self):
        self.valid_library = False
        self.enable_buttons()
        self.iphoto_library_status.set("Checking library location...")
        self.launch_export("library")

    def set_library_status(self, good, message):
        if good:
            self.valid_library = True
        self.enable_buttons()
        self.iphoto_library_status.set(message)

    def write_progress(self, text):
        self.text.insert(END, text)
        self.text.see(END)

    def enable_buttons(self):
        if self.valid_library:
            self.dryrun_button.config(state=NORMAL)
            self.export_button.config(state=NORMAL)
        else:
            self.dryrun_button.config(state=DISABLED)
            self.export_button.config(state=DISABLED)
        self.browse_library_button.config(state=NORMAL)

    def browse_library(self):
        path = tkFileDialog.askopenfilename(title="Locate iPhoto Library")
        self.iphoto_library.set(path)
        self.check_iphoto_library()

    def browse_export(self):
        path = tkFileDialog.askdirectory(title="Locate Export Folder")
        self.export_folder.set(path)

    def do_export(self):
        if self.active_library:
            self.stop_thread()
            return
        if not self.can_export():
            return
        self.export_button.config(text="Stop Export")
        self.dryrun_button.config(state=DISABLED)
        self.run_export(False)

    def do_dryrun(self):
        if self.active_library:
            self.stop_thread()
            return
        if not self.can_export():
            return
        self.dryrun_button.config(text="Stop Dry Run")
        self.export_button.config(state=DISABLED)
        self.run_export(True)

    def stop_thread(self):
        if self.active_library:
            self.active_library.abort()

    def export_done(self):
        self.active_library = None
        self.dryrun_button.config(text="Dry Run")
        self.export_button.config(text="Export")
        self.enable_buttons()

    class Options(object):
        """Simple helper to create an object compatible with the OptionParser
        output in Phoshare.py."""

        def __init__(self):
            self.iphoto = '~/Pictures/iPhoto Library'
            self.export = '~/Pictures/Album'
            self.albums = ''
            self.events = '.'
            self.smarts = ''
            self.ignore = []
            self.delete = False
            self.update = False
            self.link = False
            self.dryrun = False
            self.folderhints = False
            self.captiontemplate = u'{description}'
            self.foldertemplate = u'{name}'
            self.nametemplate = u'{title}'
            self.aperture = False # TODO
            self.size = ''  # TODO
            self.picasa = False  # TODO
            self.movies = True  # TODO
            self.originals = False
            self.iptc = 0
            self.gps = False
            self.faces = False
            self.facealbums = False
            self.facealbum_prefix = ''
            self.face_keywords = False
            self.verbose = False

        def load(self):
            """Attempts to load saved options. Returns True if saved options
            were available."""
            if not os.path.exists(_CONFIG_PATH):
                return False
            config = ConfigParser.SafeConfigParser()
            config.read(_CONFIG_PATH)
            s = 'Export1'
            if config.has_option(s, 'iphoto'):
                self.iphoto = config.get(s, 'iphoto')
            if config.has_option(s, 'export'):
                self.export = config.get(s, 'export')
            if config.has_option(s, 'albums'):
                self.albums = config.get(s, 'albums')
            if config.has_option(s, 'events'):
                self.events = config.get(s, 'events')
            if config.has_option(s, 'smarts'):
                self.smarts = config.get(s, 'smarts')
            if config.has_option(s, 'foldertemplate'):
                self.foldertemplate = config.get(s, 'foldertemplate')
            if config.has_option(s, 'nametemplate'):
                self.nametemplate = config.get(s, 'nametemplate')
            if config.has_option(s, 'captiontemplate'):
                self.captiontemplate = config.get(s, 'captiontemplate')
            if config.has_option(s, 'delete'):
                self.delete = config.getboolean(s, 'delete')
            if config.has_option(s, 'update'):
                self.update = config.getboolean(s, 'update')
            if config.has_option(s, 'link'):
                self.link = config.getboolean(s, 'link')
            if config.has_option(s, 'folderhints'):
                self.folderhints = config.getboolean(s, 'folderhints')
            if config.has_option(s, 'captiontemplate'):
                self.nametemplate = unicode(config.get(s, 'captiontemplate'))
            if config.has_option(s, 'nametemplate'):
                self.nametemplate = unicode(config.get(s, 'nametemplate'))
            if config.has_option(s, 'size'):
                self.size = config.get(s, 'size')
            if config.has_option(s, 'picasa'):
                self.picasa = config.getboolean(s, 'picasa')
            if config.has_option(s, 'movies'):
                self.movies = config.getboolean(s, 'movies')
            if config.has_option(s, 'originals'):
                self.originals = config.getboolean(s, 'originals')
            if config.has_option(s, 'iptc'):
                self.iptc = config.getint(s, 'iptc')
            if config.has_option(s, 'gps'):
                self.gps = config.getboolean(s, 'gps')
            if config.has_option(s, 'faces'):
                self.faces = config.getboolean(s, 'faces')
            if config.has_option(s, 'facealbums'):
                self.facealbums = config.getboolean(s, 'facealbums')
            if config.has_option(s, 'facealbum_prefix'):
                self.facealbum_prefix = config.get(s, 'facealbum_prefix')
            if config.has_option(s, 'face_keywords'):
                self.face_keywords = config.getboolean(s, 'face_keywords')
            return True

        def save(self):
            """Saves the current options into a file."""
            config = ConfigParser.RawConfigParser()
            s = 'Export1'
            config.add_section(s)
            config.set(s, 'iphoto', self.iphoto)
            config.set(s, 'export', self.export)
            config.set(s, 'albums', su.fsenc(self.albums))
            config.set(s, 'events', su.fsenc(self.events))
            config.set(s, 'smarts', su.fsenc(self.smarts))
            config.set(s, 'foldertemplate', su.fsenc(self.foldertemplate))
            config.set(s, 'nametemplate', su.fsenc(self.nametemplate))
            config.set(s, 'captiontemplate', su.fsenc(self.captiontemplate))
            config.set(s, 'delete', self.delete)
            config.set(s, 'update', self.update)
            config.set(s, 'link', self.link)
            config.set(s, 'dryrun', self.dryrun)
            config.set(s, 'folderhints', self.folderhints)
            config.set(s, 'captiontemplate', self.captiontemplate)
            config.set(s, 'nametemplate', self.nametemplate)
            config.set(s, 'size', self.size)
            config.set(s, 'picasa', self.picasa)
            config.set(s, 'movies', self.movies)
            config.set(s, 'originals', self.originals)
            config.set(s, 'iptc', self.iptc)
            config.set(s, 'gps', self.gps)
            config.set(s, 'faces', self.faces)
            config.set(s, 'facealbums', self.facealbums)
            config.set(s, 'facealbum_prefix', self.facealbum_prefix)
            config.set(s, 'face_keywords', self.face_keywords)

            config_folder = os.path.split(_CONFIG_PATH)[0]
            if not os.path.exists(config_folder):
                os.makedirs(config_folder)
            configfile = open(_CONFIG_PATH, 'wb')
            config.write(configfile)
            configfile.close()

    def can_export(self):
        if (not self.albums.get() and not self.events.get() and
            not self.smarts.get()):
            tkMessageBox.showerror(
                "Export Error",
                ("Need to specify at least one event, album, or smart album "
                 "for exporting."))
            return False
        return True

    def run_export(self, dry_run):
        mode = "export"
        if dry_run:
            mode = "dry_run"
        self.launch_export(mode)

    def launch_export(self, mode):
        """Launch an export operation in a new thread, to not block the UI.

        Args:
            mode - name of operation to run, "library", "dry_run", or "export".
        """
        self.text.delete('1.0', END)
        self.browse_library_button.config(state=DISABLED)
        export_thread = threading.Thread(target=self.export_thread,
                                         args=(mode,))
        export_thread.start()

    def export_thread(self, mode):
        """Run an export operation in a thread, to not block the UI.

        Args:
            mode - name of operation to run, "library", "dry_run", or "export".
        """
        try:
            # First, load the iPhoto library.
            library_path = su.expand_home_folder(self.iphoto_library.get())
            album_xml_file = iphotodata.get_album_xmlfile(library_path)
            data = iphotodata.get_iphoto_data(album_xml_file)
            msg = "Version %s library with %d images" % (
                data.applicationVersion, len(data.images))
            self.write(msg + '\n')
            if mode == "library":
                # If we just need to check the library, we are done here.
                self.thread_queue.put(("done", (True, mode, msg)))
                return

            # Do the actual export.
            export_folder = su.expand_home_folder(self.export_folder.get())
            args = ['Phoshare.py', '--export', '"' + export_folder + '"']

            options = self.Options()
            options.iphoto = self.iphoto_library.get()
            args.extend(['--iphoto', '"' + options.iphoto + '"'])
            options.export = self.export_folder.get()
            options.dryrun = mode == "dry_run"
            options.albums = self.albums.get()
            if options.albums:
                args.extend(['--albums', '"' + options.albums + '"'])
            options.events = self.events.get()
            if options.events:
                args.extend(['--events', '"' + options.events + '"'])
            options.smarts = self.smarts.get()
            if options.smarts:
                args.extend(['--smarts', '"' + options.smarts + '"'])
            options.foldertemplate = unicode(self.foldertemplate.get())
            if options.foldertemplate:
                args.extend(['--foldertemplate', '"' +
                             options.foldertemplate + '"'])
            options.nametemplate = unicode(self.nametemplate.get())
            if options.nametemplate:
                args.extend(['--nametemplate', '"' +
                             options.nametemplate + '"'])
            options.captiontemplate = unicode(self.captiontemplate.get())
            if options.captiontemplate:
                args.extend(['--captiontemplate', '"' +
                             options.captiontemplate + '"'])
            options.ignore = []  # TODO
            options.update = self.update_var.get() == 1
            if options.update:
                args.append('--update')
            options.delete = self.delete_var.get() == 1
            if options.delete:
                args.append('--delete')
            options.originals = self.originals_var.get() == 1
            if options.originals:
                args.append('--originals')
            options.link = self.link_var.get() == 1
            if options.link:
                args.append('--link')
            options.folderhints = self.folder_hints_var.get() == 1
            if options.folderhints:
                args.append('--folderhints')
            options.faces = self.faces_var.get() == 1
            if options.faces:
                args.append('--faces')
            options.face_keywords = self.face_keywords_var.get() == 1
            if options.face_keywords:
                args.append('--face_keywords')
            if self.iptc_all_var.get() == 1:
                options.iptc = 2
                args.append('--iptcall')
            elif self.iptc_var.get() == 1:
                options.iptc = 1
                args.append('--iptc')
            else:
                options.iptc = 0
            options.gps = self.gps_var.get()
            if options.gps:
                args.append('--gps')
            options.facealbums = self.face_albums_var.get() == 1
            if options.facealbums:
                args.append('--facealbums')
            options.facealbum_prefix = self.face_albums_text.get()
            if options.facealbum_prefix:
                args.append('--facealbum_prefix')

            exclude = None # TODO

            options.save()
            print " ".join(args)

            self.logging_handler.setLevel(logging.DEBUG if self.verbose_var.get() else logging.INFO)
            self.active_library = phoshare_main.ExportLibrary(export_folder)
            phoshare_main.export_iphoto(self.active_library, data, exclude,
                                        options)
            self.thread_queue.put(("done", (True, mode, '')))
        except Exception, e:  # IGNORE:W0703
            self.thread_queue.put(("done",
                                   (False, mode,
                                    str(e) + '\n\n' + traceback.format_exc())))
class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.label_0 = Label(self, text = "Enter differential equation:")
        self.label_0.grid(row = 0, column = 0, sticky =W)  
        
        self.label_1 = Label(self, text = "y' = ")
        self.label_1.grid(row = 1, column = 0, sticky =W)    
        
        self.input_1 = Entry(self)
        self.input_1.grid(row = 1, column = 1, sticky = W)  
        
        self.label_2 = Label(self, text = "y")
        self.label_2.grid(row = 1, column = 2, sticky =W) 
        
        self.label_2 = Label(self, text = "Enter initial condition:")
        self.label_2.grid(row = 2, column = 0, sticky =W)        
        
        self.label_3 = Label(self, text = "y(")
        self.label_3.grid(row = 3, column = 0, sticky =W)  
        
        self.input_2 = Entry(self)
        self.input_2.grid(row = 3, column = 1, sticky = W)    
        
        self.label_4 = Label(self, text = ") = ")
        self.label_4.grid(row = 3, column = 2, sticky =W)       
        
        self.input_3 = Entry(self)
        self.input_3.grid(row = 3, column = 3, sticky = W)    
        
        self.label_5 = Label(self, text = "Approximate: y(")
        self.label_5.grid(row = 4, column = 0, sticky =W)
        
        self.input_4 = Entry(self)
        self.input_4.grid(row = 4, column = 1, sticky = W)  
        
        self.label_6 = Label(self, text = ")")
        self.label_6.grid(row = 4, column = 2, sticky =W)   
        
        self.label_7 = Label(self, text = "Step size: ")
        self.label_7.grid(row = 5, column = 0, sticky =W)     
        
        self.input_5 = Entry(self)
        self.input_5.grid(row = 5, column = 1, sticky = W)        
        
        self.button = Button(self)
        self.button["text"] = "Get Solution"
        self.button["command"] = self.calculate      
        self.button.grid(row = 6, column = 0, sticky = W)
        
        self.textbox = ScrolledText(self, wrap = WORD, width = 30, height = 10)
        self.textbox.grid(row = 7, column = 0, columnspan = 2, sticky = W)  
        
        self.label_8 = Label(self, text = "Give me a sample calculation:")
        self.label_8.grid(row = 8, column = 0, sticky =W)    
        
        self.button = Button(self)
        self.button["text"] = "Sample"
        self.button["command"] = self.sample      
        self.button.grid(row = 8, column = 1, sticky = W)        
        
    def calculate(self):
        """Increase the click count and display the new total"""
        df = float(self.input_1.get())
        h_accum = float(self.input_2.get())
        init = float(self.input_3.get())
        end = float(self.input_4.get())
        h = float(self.input_5.get())
        
        results = get_result (df, init, h, end, h_accum)
        self.textbox.delete(0.0, END)
        self.textbox.insert(0.0, results)      
        
    def sample(self):
        self.input_1.delete(0, 'end')
        self.input_2.delete(0, 'end')
        self.input_3.delete(0, 'end')
        self.input_4.delete(0, 'end')
        self.input_5.delete(0, 'end')
        
        self.input_1.insert(0, -5)
        self.input_2.insert(0, 0)
        self.input_3.insert(0, 1)
        self.input_4.insert(0, 4)
        self.input_5.insert(0, 0.25)
Beispiel #30
0
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')
Beispiel #31
0
class UploadWizard(Wizard):
    def __init__(self, root, data):
        self.root = root
        self.data = data
        self.secure = False
        super(UploadWizard, self).__init__(
            width=450,
            height=300,
            cancelcommand=self._handle_cancel,
            finishcommand=self._handle_finish,
        )
        self.servers = ServerList()
        self.server_lbox = None
        self.upthread = None
        self.old_upload_state = None
        self.setup_gui()

    def setup_gui(self):
        self.title("Upload Wizard")
        self.protocol("WM_DELETE_WINDOW", self._handle_cancel)
        self.setup_gui_server_pane()
        self.setup_gui_user_pane()
        self.setup_gui_program_pane()
        self.setup_gui_upload_pane()

    def setup_gui_server_pane(self):
        fr = self.add_pane(
            'server', 'Select Server',
            entrycommand=self._enter_server_pane
        )
        fr.config(padx=20, pady=20)
        self.ssl_enable = IntVar()
        lbox_lbl = Label(fr, text="Select a Server to upload to:")
        self.server_lbox = ScrolledListbox(
            fr, horiz_scroll=False, width=20, highlightthickness=1)
        muck_lbl = Label(fr, text="Name")
        host_lbl = Label(fr, text="Host")
        port_lbl = Label(fr, text="Port")
        svalid = (self.register(self._serv_validate))
        pvalid = (self.register(self._port_validate), '%P')
        self.muck_entry = Entry(
            fr, width=30, validate=ALL, validatecommand=svalid)
        self.host_entry = Entry(
            fr, width=30, validate=ALL, validatecommand=svalid)
        self.port_entry = Entry(
            fr, width=10, validate=ALL, validatecommand=pvalid)
        self.port_entry.insert(END, '8888')
        self.ssl_cb = Checkbutton(
            fr, text="SSL",
            variable=self.ssl_enable,
            highlightthickness=3,
            command=self._update_server_buttons,
        )
        self.serv_del = Button(fr, text="-", width=1, command=self._del_server)
        self.serv_add = Button(fr, text="+", width=1, command=self._add_server)
        self.serv_save = Button(fr, text="Save", command=self._save_server)
        ToolTip(self.serv_del, "Delete selected Favorite Server")
        ToolTip(self.serv_add, "Enter a new Server")
        ToolTip(self.serv_save, "Save as a Favorite Server")
        self.server_lbox.bind('<<ListboxSelect>>', self._server_listbox_select)
        lbox_lbl.grid(row=0, column=0, sticky=N+W)
        self.server_lbox.grid(
            row=1, column=0, rowspan=8, padx=5, sticky=N+S+E+W)
        muck_lbl.grid(row=1, column=1, sticky=W, padx=5)
        self.muck_entry.grid(row=2, column=1, columnspan=3, sticky=E+W, padx=5)
        host_lbl.grid(row=3, column=1, sticky=W, padx=5)
        self.host_entry.grid(row=4, column=1, columnspan=3, sticky=E+W, padx=5)
        port_lbl.grid(row=5, column=1, sticky=W, padx=5)
        self.port_entry.grid(row=6, column=1, columnspan=2, sticky=E+W, padx=5)
        self.ssl_cb.grid(row=6, column=3, sticky=E, padx=5)
        self.serv_del.grid(row=8, column=1, sticky=N+W, padx=5)
        self.serv_add.grid(row=8, column=2, sticky=N+W, padx=5)
        self.serv_save.grid(row=8, column=3, sticky=N+E, padx=5)
        fr.grid_columnconfigure(2, weight=1, minsize=50)
        fr.grid_rowconfigure(7, weight=1)
        self.server_lbox.focus()
        return fr

    def setup_gui_user_pane(self):
        fr = self.add_pane(
            'user', 'Select a user',
            entrycommand=self._enter_user_pane
        )
        fr.config(padx=20, pady=20)
        lbox_lbl = Label(fr, text="Select a User to upload to:")
        self.user_lbox = ScrolledListbox(fr, horiz_scroll=False, width=20)
        user_lbl = Label(fr, text="UserName")
        pass_lbl = Label(fr, text="Password")
        uvalid = (self.register(self._user_validate))
        self.user_entry = Entry(
            fr, width=30, validate=ALL, validatecommand=uvalid)
        self.pass_entry = Entry(
            fr, width=30, show="*", validate=ALL, validatecommand=uvalid)
        self.user_del = Button(fr, text="-", width=1, command=self._del_user)
        self.user_add = Button(fr, text="+", width=1, command=self._add_user)
        self.user_save = Button(fr, text="Save", command=self._save_user)
        ToolTip(self.user_del, "Delete selected User")
        ToolTip(self.user_add, "Enter a new User")
        ToolTip(self.user_save, "Save User Info")
        self.user_lbox.bind('<<ListboxSelect>>', self._user_listbox_select)
        lbox_lbl.grid(row=0, column=0, sticky=N+W)
        self.user_lbox.grid(row=1, column=0, rowspan=8, padx=5, sticky=N+S+E+W)
        user_lbl.grid(row=1, column=1, sticky=W, padx=5)
        self.user_entry.grid(row=2, column=1, columnspan=3, sticky=E+W, padx=5)
        pass_lbl.grid(row=3, column=1, sticky=W, padx=5)
        self.pass_entry.grid(row=4, column=1, columnspan=3, sticky=E+W, padx=5)
        self.user_del.grid(row=6, column=1, sticky=N+W, padx=5)
        self.user_add.grid(row=6, column=2, sticky=N+W, padx=5)
        self.user_save.grid(row=6, column=3, sticky=N+E, padx=5)
        fr.grid_columnconfigure(2, weight=1, minsize=50)
        fr.grid_rowconfigure(5, weight=1)
        return fr

    def setup_gui_program_pane(self):
        fr = self.add_pane(
            'program', 'Program Info',
            entrycommand=self._enter_program_pane
        )
        pvalid = (self.register(self._program_validate))
        fr.config(padx=20, pady=20)
        prog_lbl = Label(fr, text="Program Name or DBRef")
        self.prog_entry = Entry(
            fr, width=30, validate=ALL, validatecommand=pvalid)
        global previous_progname
        self.prog_entry.insert(END, previous_progname)
        prog_lbl.grid(row=0, column=0, sticky=W+S)
        self.prog_entry.grid(row=1, column=0, sticky=N+E+W)
        fr.grid_columnconfigure(0, weight=1)
        fr.grid_rowconfigure(2, weight=1)
        return fr

    def setup_gui_upload_pane(self):
        fr = self.add_pane(
            'upload', 'Uploading',
            entrycommand=self._enter_upload_pane
        )
        fr.config(padx=20, pady=20)
        self.upload_lbl = Label(
            fr, text="", justify=LEFT, anchor=W, wraplength=400)
        self.progressbar = ProgressBar(
            fr, length=300,
            value=10.0, maximum=100.0,
            mode=INDETERMINATE,
        )
        self.console_log = ScrolledText(
            fr, font='TkFixedFont',
            relief=SUNKEN,
            borderwidth=2,
            background="black",
            foreground="white",
            width=1,
            height=1,
            insertontime=0,
            takefocus=0,
            cursor='arrow',
        )
        ro_binds = [
            "<Key>",
            "<<Cut>>",
            "<<Clear>>",
            "<<Paste>>",
            "<<PasteSelection>>",
            "<Double-Button-1>",
        ]
        for bind in ro_binds:
            self.console_log.bind(bind, lambda e: "break")
        self.upload_lbl.grid(row=0, column=0, sticky=W+S)
        self.progressbar.grid(row=1, column=0, sticky=N+E+W, padx=15, pady=5)
        self.console_log.grid(row=2, column=0, sticky=N+S+E+W)
        fr.grid_columnconfigure(0, weight=1)
        fr.grid_rowconfigure(2, weight=1)
        return fr

    def _enter_server_pane(self):
        self.set_finish_enabled(False)
        self.set_next_enabled(False)
        self.set_next_text()
        self.set_default_button("next")
        self.set_finish_text("Done")
        self._populate_server_listbox()
        if self.server_lbox.size() > 0:
            self.server_lbox.focus()
        else:
            self.muck_entry.focus()
        self._update_server_buttons()

    def _enter_user_pane(self):
        self.set_finish_enabled(False)
        self.set_next_enabled(False)
        self.set_next_text()
        self.set_default_button("next")
        self._populate_user_listbox()
        if self.user_lbox.size() > 0:
            self.user_lbox.focus()
        else:
            self.user_entry.focus()
        self._update_user_buttons()

    def _enter_program_pane(self):
        self.set_finish_enabled(False)
        self.set_next_enabled(False)
        self.set_next_text("Upload")
        self.set_default_button("next")
        self.prog_entry.focus()

    def _enter_upload_pane(self):
        self.set_default_button("finish")
        self.set_next_text()
        self.set_prev_enabled(False)
        self.set_finish_enabled(False)
        self._upload_start()
        global previous_progname
        previous_progname = self.prog_entry.get()

    def _populate_server_listbox(self):
        self.server_lbox.delete(0, END)
        for serv in self.servers.get_servers():
            self.server_lbox.insert(END, str(serv))

    def _update_server_listbox(self):
        sel = self.server_lbox.curselection()
        self._populate_server_listbox()
        if sel:
            self.server_lbox.selection_set(sel[0])
        self._update_server_buttons()

    def _server_listbox_select(self, event=None):
        try:
            sel = int(self.server_lbox.curselection()[0])
            servers = self.servers.get_servers()
            serv = servers[sel]
            self.muck_entry.delete(0, END)
            self.host_entry.delete(0, END)
            self.port_entry.delete(0, END)
            self.muck_entry.insert(END, serv.name)
            self.host_entry.insert(END, serv.host)
            self.port_entry.insert(END, serv.port)
            self.ssl_enable.set(serv.ssl)
            self._update_server_buttons()
        except (ValueError, IndexError):
            return

    def _update_server_buttons(self, event=None):
        add_state = 'normal'
        del_state = 'normal'
        save_state = 'normal'
        items = self.server_lbox.curselection()
        if not items:
            del_state = 'disabled'
            if not self.muck_entry.get():
                if not self.host_entry.get():
                    if self.port_entry.get() == '8888':
                        if not self.ssl_enable.get():
                            add_state = 'disabled'
        if not self.host_entry.get() or not self.port_entry.get():
            save_state = 'disabled'
        self.serv_del.config(state=del_state)
        self.serv_add.config(state=add_state)
        self.serv_save.config(state=save_state)
        self.set_next_enabled(
            bool(items or (self.host_entry.get() and self.port_entry.get()))
        )

    def _serv_validate(self):
        self.after_idle(self._update_server_buttons)
        return True

    def _port_validate(self, val):
        self.after_idle(self._update_server_buttons)
        if val == '':
            return True
        try:
            val = int(val)
            return True
        except ValueError:
            self.bell()
        return False

    def _add_server(self):
        self.server_lbox.selection_clear(0, END)
        self.muck_entry.delete(0, END)
        self.host_entry.delete(0, END)
        self.port_entry.delete(0, END)
        self.port_entry.insert(END, '8888')
        self.ssl_enable.set('0')
        self.muck_entry.focus()
        self._update_server_buttons()

    def _del_server(self):
        del_confirmed = askyesno(
            "Delete Server",
            "Are you sure you want to delete this server?",
            parent=self
        )
        if del_confirmed:
            try:
                sel = int(self.server_lbox.curselection()[0])
                self.servers.del_server(sel)
                self.servers.save()
                self._update_server_listbox()
            except (ValueError, IndexError):
                self.bell()

    def _save_server(self):
        sel = -1
        try:
            sel = int(self.server_lbox.curselection()[0])
            self.servers.del_server(sel)
            self._update_server_listbox()
        except (ValueError, IndexError):
            pass
        server = ServerInfo(
            name=self.muck_entry.get(),
            host=self.host_entry.get(),
            port=self.port_entry.get(),
            use_ssl=self.ssl_enable.get()
        )
        self.servers.add_server(server)
        self.servers.save()
        self._update_server_listbox()
        if sel >= 0:
            self.server_lbox.selection_set(sel)
        self._server_listbox_select()
        self._update_server_buttons()

    def _populate_user_listbox(self):
        host = self.host_entry.get()
        port = int(self.port_entry.get())
        serv = self.servers.find_by_host_and_port(host, port)
        self.user_lbox.delete(0, END)
        if not serv:
            return
        for user in serv.get_users():
            self.user_lbox.insert(END, user.user)

    def _update_user_listbox(self):
        sel = self.user_lbox.curselection()
        self._populate_user_listbox()
        if sel:
            self.user_lbox.selection_set(sel[0])
        self._update_user_buttons()

    def _user_listbox_select(self, event=None):
        host = self.host_entry.get()
        port = int(self.port_entry.get())
        serv = self.servers.find_by_host_and_port(host, port)
        if not serv:
            return
        try:
            sel = int(self.user_lbox.curselection()[0])
            users = serv.get_users()
            user = users[sel]
            self.user_entry.delete(0, END)
            self.pass_entry.delete(0, END)
            self.user_entry.insert(END, user.user)
            self.pass_entry.insert(END, user.password)
            self._update_server_buttons()
        except (ValueError, IndexError):
            return

    def _update_user_buttons(self, event=None):
        add_state = 'normal'
        del_state = 'normal'
        save_state = 'normal'
        host = self.host_entry.get()
        port = int(self.port_entry.get())
        serv = self.servers.find_by_host_and_port(host, port)
        if not serv:
            del_state = 'disabled'
            add_state = 'disabled'
            save_state = 'disabled'
        items = self.user_lbox.curselection()
        if not items:
            del_state = 'disabled'
            if not self.user_entry.get():
                if not self.pass_entry.get():
                    add_state = 'disabled'
        if not self.user_entry.get():
            save_state = 'disabled'
        self.user_del.config(state=del_state)
        self.user_add.config(state=add_state)
        self.user_save.config(state=save_state)
        self.set_next_enabled(
            bool(items or (self.user_entry.get() and self.pass_entry.get()))
        )

    def _user_validate(self):
        self.after_idle(self._update_user_buttons)
        return True

    def _add_user(self):
        self.user_lbox.selection_clear(0, END)
        self.user_entry.delete(0, END)
        self.pass_entry.delete(0, END)
        self._update_user_buttons()
        self.user_entry.focus()

    def _del_user(self):
        del_confirmed = askyesno(
            "Delete User",
            "Are you sure you want to delete this user?",
            parent=self
        )
        if del_confirmed:
            host = self.host_entry.get()
            port = int(self.port_entry.get())
            serv = self.servers.find_by_host_and_port(host, port)
            if not serv:
                return
            try:
                sel = int(self.server_lbox.curselection()[0])
                serv.del_user(sel)
                self.servers.save()
                self._update_user_listbox()
            except (ValueError, IndexError):
                self.bell()

    def _save_user(self):
        host = self.host_entry.get()
        port = int(self.port_entry.get())
        serv = self.servers.find_by_host_and_port(host, port)
        if not serv:
            return
        serv.add_user(
            user=self.user_entry.get(),
            password=self.pass_entry.get(),
        )
        self.servers.save()
        self._update_user_listbox()

    def _update_program_buttons(self, event=None):
        self.set_next_enabled(bool(self.prog_entry.get()))

    def _program_validate(self):
        self.after_idle(self._update_program_buttons)
        return True

    def _upload_start(self):
        force_ssl = bool(self.ssl_enable.get())
        host = self.host_entry.get()
        port = int(self.port_entry.get())
        user = self.user_entry.get()
        password = self.pass_entry.get()
        progname = self.prog_entry.get()
        self.upload_lbl.config(text="Connecting to %s:%s..." % (host, port))
        self.progressbar.start()
        self.upthread = UploadThread(
            host, port, force_ssl,
            user, password, progname,
            self.data,
        )
        self.upthread.start()
        self.old_upload_state = ''
        self._update_upload_state()

    def _update_upload_state(self):
        logtxt = self.upthread.get_log_text()
        if logtxt:
            self.console_log.insert(END, logtxt)
            self.console_log.see(END)
        state = self.upthread.state
        self.upload_lbl.config(text=self.upthread.status)
        if state in [UPLOAD_FAIL, UPLOAD_SUCCESS]:
            self.set_finish_enabled(True)
            self.set_cancel_enabled(False)
        else:
            self.after(100, self._update_upload_state)
        if state == UPLOADING:
            uploaded = self.upthread.bytes_uploaded
            total = self.upthread.total_bytes
            pcnt = float(uploaded) / total
            self.progressbar.config(value=pcnt)
        if state == self.old_upload_state:
            return
        self.old_upload_state = state
        if state == UPLOADING:
            self.progressbar.stop()
            self.progressbar.config(mode=DETERMINATE)
        elif state == UPLOAD_FAIL:
            self.progressbar.stop()
            self.progressbar.grid_forget()
        elif state == UPLOAD_SUCCESS:
            self.progressbar.stop()
            self.progressbar.config(mode=DETERMINATE)
            self.progressbar.config(value=100.0)

    def _handle_cancel(self):
        self.destroy()

    def _handle_finish(self):
        self.destroy()
Beispiel #32
0
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()
Beispiel #33
0
#adding text area to the main window
Label(root, text="Send serial command to arduino device").grid(row=0, column=0, columnspan=3, padx=8, sticky=W )
Label(root, text="Baud rate").grid(row=1, column=0, padx=8, sticky=W)
baud_rate=StringVar()
baud_rate.set("9600")
Label(root, textvariable=baud_rate).grid(row=1, column=1, padx=1,  sticky=W )
serial_out_data=StringVar()
send_data = ttk.Entry(root, width=23, textvariable=serial_out_data)
send_data.grid(row=1, column=2, columnspan=5, padx=8, sticky=W)
send_button=Button(text="Send", command=send_serial)
send_button.grid(row=1, column=5, padx=8)
Label(root, text="").grid(row=2)

txt_a = ScrolledText(root,  width=60, height=13)
txt_a.grid(row=3, column=0, columnspan=6)
txt_a.delete(INSERT)


#txt=Message(root, textvariable=serial_out_data, width=100).grid(row=3, column=0, columnspan=6)
Label(root, text=" ").grid(row=4)
Label(root, text="VOLTAGE MONITOR").grid(row=5, column=0,columnspan=3, padx=8, sticky=W+S+E+N)
Label(root, text="Battery   ").grid(row=6, column=0, padx=8, sticky=W)
Label(root, text="Solar cell").grid(row=6, column=1, padx=8, sticky=W)
Label(root, text="Charging  ").grid(row=6, column=2, padx=8, sticky=W)
Label(root, text="          ").grid(row=6, column=3, padx=8, sticky=W)
Label(root, text="          ").grid(row=6, column=4, padx=8, sticky=W)
Label(root, text="          ").grid(row=6, column=5, padx=8, sticky=W)
# set the voltages to 0.0V for battery, solar and charging
#battery
#pwm slider
Beispiel #34
0
class CoreGUI(object):
  def __init__(self,parent):
    self.parent = parent
    self.InitUI()
    self.progress = ttk.Progressbar(self.parent, orient = 'horizontal', length = 800, mode = 'determinate')
    self.progress.grid(column=0, row=3, columnspan=8)
    dianabutton = Button(self.parent, text="Start Diana", command=self.main)
    dianabutton.grid(column=0, row=1, columnspan=2)
    self.sizetext=StringVar()
    self.sizetext.set("")
    self.sizebox = Label(self.parent, textvariable=self.sizetext, height=2)
    self.sizebox.grid(column=2, row=1, columnspan=1)
    self.pathbox = Entry(self.parent, bd =2, width=50)
    self.pathbox.grid(column=3, row=1, columnspan=3)
    self.pathbox.bind('<Return>', self.catchEnter)
    pathbutton = Button(self.parent, text="Velg Katalog", command=self.askdirectory)
    pathbutton.grid(column=6, row=1, columnspan=1)
    self.copybutton = Button(self.parent, text="Kopier filer", command=self.copytodir)
    self.copybutton.grid(column=7, row=1, columnspan=1)
    self.copybutton.config(state='disabled')
    self.copyDir = os.path.expanduser("~")
    self.pathbox.insert(0,self.copyDir)
    self.sizetext.set("Ledig: " + GetHumanReadable(dirfree(self.copyDir)))

  def main(self):

    self.progress["value"] = 0
    embedded_rawstr = r"""(?m).* INFO .*Source:(?P<SourceFile>\S*)"""
    self.sourceFiles = set() 

    cmd = subprocess.Popen('diana', shell=True, stdout=subprocess.PIPE)
    while True:
      line = cmd.stdout.readline()
      if not line:
	  # Diana er avsluttet, da kan vi fylle tekstboks hvis noen felter ble valgt
        self.text_box.delete("1.0",END)
        if (self.sourceFiles):
          self.progress["maximum"] = len(self.sourceFiles)
          self.copybutton.config(state='normal')
          self.totalFsize = 0
          for lines in self.sourceFiles:
            fileSize = os.path.getsize(lines)
            self.text_box.insert(END, GetHumanReadable(fileSize).rjust(14) + " - " + lines + "\n")
            self.totalFsize += fileSize
          self.text_box.insert(END, "\n" + GetHumanReadable(self.totalFsize).rjust(14) + " Totalt\n")
        else:
          self.copybutton.config(state='disabled')
          self.text_box.insert(END, "\n\nIngen Felter ble valgt\n") 
          self.text_box.insert(END, "\n\nBruk \"Start Diana\" på nytt og velg noen felter for å kunne kopiere..\n") 

        break
      match_obj = re.search(embedded_rawstr, line)
      if match_obj:
        SourceFile = match_obj.group('SourceFile')
        print "<" + SourceFile + ">"
        self.sourceFiles.add(SourceFile)

  def InitUI(self):
    self.text_box = ScrolledText(self.parent, wrap='word', height = 15, width=100)
    self.text_box.grid(column=0, row=0, columnspan = 8, sticky='NSWE', padx=5, pady=5)
    self.text_box.insert(END, "\nKopiering av feltfiler valgt i Diana:\n\n")
    self.text_box.insert(END, "Klikk på \"Start Diana\"\n")
    self.text_box.insert(END, "Gå til Felt menyen i Diana og velg modell\n")
    self.text_box.insert(END, "Velg de feltene du er ute etter og klikk Utfør etc\n")
    self.text_box.insert(END, "Når du er ferdig, avslutt Diana og de feltene som ble valgt listes opp her.\n")
    self.text_box.insert(END, "Velg hvor de skal kopieres med \"Velg Katalog\" og klikk deretter \"Kopier Filer\"\n")
    self.text_box.insert(END, "\nOBS: GigaByte filer tar stor plass og tar også lang tid å kopiere\n")

  def askdirectory(self):
    okorcancel = tkFileDialog.askdirectory(initialdir=self.pathbox.get(), parent=root, mustexist=True)
    if (okorcancel):
      self.copyDir = okorcancel
      self.sizetext.set("Ledig: " + GetHumanReadable(dirfree(self.copyDir)))
    else:
      self.copyDir = self.pathbox.get()
    
    self.pathbox.delete(0,END)
    self.pathbox.insert(0,self.copyDir)

  def copytodir(self):
    if (not os.path.isdir(self.pathbox.get())):
      tkMessageBox.showerror("Katalog finnes ikke!", "\"" + self.pathbox.get() + "\" er ikke tilgjengelig")
      self.pathbox.delete(0,END)
      self.pathbox.insert(0,self.copyDir)
    else:
      self.copyDir=self.pathbox.get()
      print "Target: " + self.copyDir
      targetDisk = os.statvfs(self.copyDir)
      targetFree = targetDisk.f_frsize * targetDisk.f_bavail
      if (not os.access(self.copyDir, os.W_OK)):
        tkMessageBox.showerror("Ikke skrivetilgang!","Du har ikke skrivetilgang på \n \"" + self.copyDir + "\".\nVelg en annen i stedet.")
      elif (self.totalFsize > targetFree):
        tkMessageBox.showerror("For lite ledig plass", "Det er " + GetHumanReadable(targetFree) + " ledig på katalogen \"" + self.copyDir + "\" og du trenger " + GetHumanReadable(self.totalFsize))
      else:
        self.filecnt = 1
        self.progress["value"] = 0
        self.sourcelines = list(self.sourceFiles)
        self.copyfiles()


  def copyfiles(self):
    self.progress["value"] = self.filecnt
    print "copy #" + str(self.filecnt) + " av " + str(len(self.sourcelines))  + ":" + self.sourcelines[self.filecnt -1] + " to " + self.copyDir
    errmsg = ""
    try:
      shutil.copy(self.sourcelines[self.filecnt -1], self.copyDir)
    except shutil.Error as e:
      errmsg = 'Error: %s' % e
      tkMessageBox.showerror("shutil - Feil på kopiering","Problem med å kopiere \"" + self.sourcelines[self.filecnt -1] + "\" til " + self.copyDir + "\" katalogen - " + errmsg)
      print errmsg
    except IOError as e:
      errmsg = 'Error: %s' % e.strerror
      tkMessageBox.showerror("IOError: Feil på kopiering","Problem med å kopiere \"" + self.sourcelines[self.filecnt -1] + "\" til " + self.copyDir + "\" katalogen - " + errmsg)
      print errmsg
    self.filecnt += 1
    if (self.filecnt <= len(self.sourcelines)):
      root.after(10, self.copyfiles) # Kaller seg selv etter 10ms for å oppdatere progressbar
    if (self.filecnt > len(self.sourcelines)):
      if (not errmsg):
        tkMessageBox.showinfo("DianaSaveFelt","Kopiering fullført!")
      else:
        tkMessageBox.showerror("DianaSaveFelt","Kopiering feilet!")

  # Trigger på enter i pathboksen
  def catchEnter(self,event):
    if (not os.path.isdir(self.pathbox.get())):
      tkMessageBox.showerror("Katalog finnes ikke!", "\"" + self.pathbox.get() + "\" er ikke tilgjengelig")
      self.pathbox.delete(0,END)
      self.pathbox.insert(0,self.copyDir)
    else:
      self.sizetext.set("Ledig: " + GetHumanReadable(dirfree(self.pathbox.get())))
Beispiel #35
0
class ttkTestApplication(ttk.Frame):
    """
    This class for design a Test Pad
    """
    _adb = None
    _entry = None
    _text = None

    def __init__(self, master=None):
        self._adb = AdbUnit.AdbUnit()
        ttk.Frame.__init__(self, master, class_='ttktestApplication')

        #Set the windows title
        title = 'mobileco '+ __version__+ '-Test'
        self.master.title(title)
        self.create_test()

        #Set the pad position
        master.geometry("+%d+%d" % (300, 200))
        self.grid()

    def create_test(self):
        """
        Build widgets for pad
        """

        #add test button
        cl = 0
        for bn in ['enginner','gps','validation','test','catlog','setting']:
            g_button = ttk.Button(self,name = bn,text = bn)
            g_button.bind('<ButtonRelease-1>', self._test_func)
            g_button.grid(row = 0,column = cl)
            cl +=1
        #add command line
        t = ttk.Label(self,text = "命令:")
        t.grid(row = 1,column = 0)
        self._entry = ttk.Entry(self,width = 25)
        self._entry.grid(row = 1,column = 1,columnspan=cl-1)
        self._entry.bind("<Return>",self.get_cmd)

        self._text = ScrolledText(self,width = cl*10,height = 20)
        self._text.grid(row = 2,column =0,columnspan =cl)
        self.master.bind('<Configure>',self.resize)

        pass

    def get_cmd(self,event):
        """
        Get the Entry text for cmd ,And send to mobile
        """

        str_cmd = event.widget.get()
        self.show_respon("youjin# "+ str_cmd + '\n')
        self._entry.delete('0','end')
        self._entry.update()
        rep = self._adb.adbshellcommand(str_cmd)

        if rep is None:
            rep = "more than one device and emulator"
        self.show_respon("adb#"+ rep )
        self._text.configure(width = 50,height = 30)

    def show_respon(self,str):
        """
        Place the text in a Text widget for show
        """
        self._text.insert('end',str)
        self._text.yview_moveto(1)
        pass

    def _test_func(self,event):
        """
        implement the Fix button widget function
        """
        bn =  event.widget.winfo_name()
        print bn

        cmd = "none"
        if bn == "enginner":
            cmd = "am start -n  com.sprd.engineermode/.EngineerModeActivity"
            pass
        elif bn == "gps":
            cmd = "am start -n com.spreadtrum.sgps/.SgpsActivity"
            pass
        elif bn == "validation":
            cmd = "am start -n com.sprd.validationtools/.ValidationToolsMainActivity"
            pass
        elif bn == "test":
            cmd = "input keyevent 60;am force-stop test.zhlt.g1;am start -n test.zhlt.g1/.TestActivity"
            pass
        elif bn == "catlog":
            cmd = "cat /sdcard/test.log"
            pass
        elif bn == "setting":
            cmd = "am start -n com.android.settings/com.android.settings.Settings"
            pass
        if self._adb.device_exist():
            self.show_respon(cmd)
            rep =  self._adb.adbshellcommand(cmd)
            self.show_respon(rep)
        pass

    def resize(self,event):
        print event.width,' ',event.height

        pass
Beispiel #36
0
class BoardWindow(tk.Frame):

	square_side = 45
	def __init__(self, pipe, colors, master=None):
		#instance variables
		self.game_pipe = pipe
		self.colors = colors
		self.player = 1
		self.turn = 1
		self.moves_made = 0

		#initialize gui
		tk.Frame.__init__(self, master)
		self.bind("<Destroy>", self.__window_close)
		self.grid()
		self.__create_widgets()
		self.game_pipe.send(self.__order_selection_dialog())
		self.__draw_turns()
		self.__get_initial_state()
		self.mainloop()

	def __get_initial_state(self):
		self.game_pipe.send("initial_state")
		moves = self.game_pipe.recv()
		self.__make_moves(moves)

	def __create_widgets(self):
		tk.Label(self, text="Othellobot", font=('Arial', -17, 'italic')).grid(column=0, row=0)
		tk.Label(self, text="by Luke Turner and Antonio Ledesma", font=('Arial', -12)).grid(column=0, row=1)

		self.forfeit_move_button = tk.Button(self, text="Forfeit Move", command=self.__board_doubleclick)
		self.forfeit_move_button.grid(column=1,row=1)

		self.turns = tk.Canvas(self, width=410, height=65)
		self.turns.grid(column=1,row=0)

		self.undo_frame = tk.LabelFrame(self, text="Undo Moves", padx=5, pady=5)
		self.__fill_undo_frame()
		self.undo_frame.grid(column=2,row=0)

		self.board = tk.Canvas(self, width=370, height=370)
		self.board.grid(column=0, row=2)

		self.logbox = ScrolledText(self)
		self.logbox.grid(column=1, row=2, columnspan=2)
		
		self.__draw_board()

	def __window_close(self, e):
		self.game_pipe.send("END_GAME")
		self.game_pipe.close()

	def __fill_undo_frame(self):
		self.undo_button = tk.Button(self.undo_frame, text="Undo", command=self.__undo_moves)
		self.undo_button.grid(column=2,row=1)
		self.undo_move_string = tk.StringVar()
		self.undo_move_string.set('-1')
		tk.Entry(self.undo_frame, textvariable=self.undo_move_string, state=tk.NORMAL).grid(column=2,row=0)

	def __order_selection_dialog(self):
		choice = tkMessageBox.askquestion("Order Selector", "Do you want to be Player 1 (Red)?")
		if choice == u"yes":
			self.log("You are Player 1. The CPU is Player 2.\n")
			self.player = 1
		else:
			self.log("You are Player 2. The CPU is Player 1.\n")
			self.player = 2
		self.focus_force()
		return choice

	def __invalid_move_alert(self):
		tkMessageBox.showwarning("Invalid Move Choice", "Your choice of move was invalid. Please try again.")
		self.focus_force()

	def __invalid_undo_alert(self):
		tkMessageBox.showwarning("Invalid Undo", "The move index to undo to is invalid.")
		self.focus_force()

	def log(self, text):
		self.logbox.insert(tk.INSERT, text)

	def __draw_board(self):

		for col in range(1,9):
			for row in range(1,9):

				coords = [self.square_side*(col-1)+5, self.square_side*(row-1)+5, 
				(self.square_side*col)+5, (self.square_side*row)+5]
				tag = "ABCDEFGH"[col - 1] + str(row)

				self.board.create_rectangle(*coords, tags=tag+"R")
				self.board.create_oval(*coords, tags=tag+"C", outline="", activeoutline="black")
				self.board.create_text((coords[0]+coords[2])/2, 
					(coords[1]+coords[3])/2, 
					tags=tag+"T", text=tag)

		self.board.bind("<Double-Button-1>", self.__board_doubleclick)
		self.log("CONTROLS: Double-click on square during your turn to place your tile.\n" +
			"          Double-click anywhere during CPU turn to give it permission to move.\n" +
			"Beginning Game. Initial turn goes to player 1.\n")

	def __draw_turns(self):
		self.turns.create_rectangle(5, 5, 200, 55, tags=("1", "R"))
		self.turns.create_rectangle(200, 5, 400, 55, tags=("2", "R"))
		if self.player == 1:
			player_loc = 100
			cpu_loc = 300
		else:
			player_loc = 300
			cpu_loc = 100

		self.turns.create_text(player_loc, 23, text="Player", font=("Arial", -14, "bold"))
		self.turns.create_text(cpu_loc, 23, text="CPU", font=("Arial", -14, "bold"))
		self.turns.create_text(100, 40, text="2", tags="1T", font=("Arial", -14, "bold"))
		self.turns.create_text(300, 40, text="2", tags="2T", font=("Arial", -14, "bold"))
		self.__set_turn(1)

	def __set_turn(self, turn):
		self.turn = turn
		self.turns.itemconfigure("R", fill="")
		self.turns.itemconfigure(str(turn), fill="red")


	def __alter_game_state(self, game_data):
		if game_data["valid"]:
			logstring = "[MOVE " + str(game_data['moves_made']) + "] " + game_data["initial_move"]["color"]
			if game_data["initial_move"]["loc"] == "-1":
				# forfeit the move.
				logstring += " forfeits their move.\n"
			else:
				logstring += (" moves to " + str(game_data["initial_move"]["loc"]) + ".\n")
				self.__make_moves(game_data["moves"])

			if "undone" in game_data:
				logstring = "[UNDO] We're undoing back to move " + str(game_data['moves_made']) + ".\n"

			self.log(logstring)
			self.moves_made = game_data['moves_made']
			self.__set_turn(game_data["turn"])
			self.__update_scores(game_data["scores"])
		else:
			self.__invalid_move_alert()

	def __update_scores(self, scores):
		self.turns.itemconfigure("1T", text=scores[0])
		self.turns.itemconfigure("2T", text=scores[1])

	def __undo_moves(self):
		move = self.undo_move_string.get()
		try:
			move_number = int(move)
			if move_number < 0:
				move_number = self.moves_made + move_number
			if move_number < 0 or move_number >= self.moves_made:
				raise IndexError()

			self.game_pipe.send({'undo': True, 'move_number': move_number})
			board_setup = self.game_pipe.recv()
			while not 'undone' in board_setup: 
				board_setup = self.game_pipe.recv()
			self.__alter_game_state(board_setup)
			self.game_pipe.send(True)
			self.__alter_game_state(self.game_pipe.recv())
			self.game_pipe.send(True)
		except (ValueError, IndexError):
			self.__invalid_undo_alert()

	def __board_doubleclick(self, event=False):
		if not event:
			loc = "-1"
		else:
			obj = self.board.find_closest(event.x, event.y)[0]
			loc = self.board.gettags(obj)[0][:-1]

		if self.turn == self.player:
			# Player turn
			self.game_pipe.send(loc)
			if self.game_pipe.poll(0.25):
				game_data = self.game_pipe.recv()
				self.__alter_game_state(game_data)
		else:
			self.configure(cursor='wait')
			game_data = self.game_pipe.recv()
			self.__alter_game_state(game_data)
			self.game_pipe.send(True)
			self.configure(cursor='arrow')

	def __make_moves(self, moves):
		self.board.itemconfigure("H", fill="")
		self.board.dtag("H", "H")
		for move in moves:
			if move['color'] == '':
				color = '' #self.cget('background')
				border = ''
			else:
				color = move['color']
				border = 'black'
			self.board.itemconfigure(move['loc']+"C", fill=color, outline=border)
			self.board.addtag_withtag("red", move['loc']+"C")
			self.board.itemconfigure(move['loc']+"R", fill="yellow", outline="black")
			self.board.addtag_withtag("H", move['loc']+"R")
Beispiel #37
0
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)
Beispiel #38
0
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")
Beispiel #39
0
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"
Beispiel #40
0
class App(object):

    def notice(self, msg):
        self.txt_locate.insert(END, msg)
        self.txt_locate.insert(END, '\n')

    def check_status(self):
        try:
            dat = backendQueue.get(block=False)
        except:
            dat = None

        if dat is None:
            pass
        elif dat['type'] == 'start':
            pass
        elif dat['type'] == 'process':
            self.progress['value'] += 1
            self.notice(dat['data'])

        elif dat['type'] == 'end':
            # tkMessageBox.showinfo(title=u'tips', message=dat['data'])

            self.btn.state(['!disabled'])
            return

        self.txt_locate.after(100, self.check_status)

    def query(self, *args):
        if self.btn.instate(['disabled']): return
        self.btn.state(['disabled'])

        self.txt_locate.delete("1.0", 'end-1c')

        mobiles = self.txt_mobile.get("1.0", 'end-1c').strip()

        if not mobiles:
            tkMessageBox.showerror(title=u'错误', message=u'请输入手机号')
            self.btn.state(['!disabled'])
            return

        mobiles = map(lambda x: x.strip(), mobiles.strip().split('\n'))
        self.progress["value"] = 0
        self.progress["maximum"] =  len(mobiles)

        guiQueue.put(mobiles)
        self.check_status()

    def __init__(self):
        self.root = Tk()

        Label(self.root, text=u"输入手机号码").grid(row=0, column=1)
        Label(self.root, text=u"输出信息").grid(row=0, column=3)
        self.progress = Progressbar(self.root, orient="horizontal", length=100, mode="determinate")
        self.progress.grid(row=0, column=2)
        self.txt_mobile = ScrolledText(master=self.root, width=30, height=70, yscrollcommand='1')
        self.txt_mobile.grid(row=1, column=1, padx=5)
        self.btn = Button(master=self.root, text=u"开始查询")

        self.btn.grid(row=1, column=2, sticky=N, pady=150)
        self.btn.bind("<Button-1>", self.query)
        self.txt_locate = ScrolledText(master=self.root, width=35, height=70, yscrollcommand='1')
        self.txt_locate.grid(row=1, column=3, padx=5)

        jobthread = threading.Thread(target=JobThread(), kwargs={"gui": self})
        jobthread.setDaemon(True)
        jobthread.start()
Beispiel #41
0
    if i % blk_size != 0:
        blks.append(dict(dictn))
    fd.close()
    return blks


root = Tk()
root.configure(background='black')
root.title("Merge Join Algorithm with Given Queries")
root.resizable(width=False, height=False)
frame = Frame(root)
queryvar = StringVar()
ql = StringVar()
frame.grid(row=2, column=0, columnspan=4)
text = ScrolledText(frame, wrap="word")
text.grid(row=2)
text.config(font=("Courier", 12))
text.configure(background='white', foreground='black')
d = "C:/Users/skuch/Desktop/Courses/8340_DB2/Project/Tables/"
branchNYC = readBlocks(d + "NewYork_Branch.txt", 7)
text.insert(INSERT, "\n")
#text.insert(INSERT, len(branchNYC))

accountNYC = readBlocks(d + 'NewYork_Account.txt', 10)
text.insert(INSERT, "\n")
#text.insert(INSERT, len(accountNYC))

depositorNYC = readBlocks(d + 'NewYork_Depositor.txt', 15)
text.insert(INSERT, "\n")
#text.insert(INSERT, len(depositorNYC))
Beispiel #42
0
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
Beispiel #43
0
    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background = "#000000")
        self.style.configure("TCheckbutton", background = "#000000")
        self.style.configure("TButton", background = "#000000") 
        self.pack(fill=BOTH, expand=1)
        
        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight = 1)
        self.rowconfigure(6, weight = 1)
        
        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky = W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height = 20)
        area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=3, sticky = N+S+E+W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self, text="IP Address",variable=self.ip, width=10)
        ip_add_button.grid(row = 1, column = 3, sticky = N)
        ip_add_button.config(anchor = W, activebackground = "red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self, text="Ports", variable=self.port, width=10)
        port_button.grid(row = 1, column = 3)
        port_button.config(anchor = W, activebackground = "orange")
        
        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self, text="Host Name",variable=self.host, width=10)
        host_name_button.grid(row = 1, column = 3, sticky = S)
        host_name_button.config(anchor = W, activebackground = "yellow")
        
        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self, text="Gateway", variable=self.gateway, width=10)
        gateway_btn.grid(row = 2, column = 3, sticky = N)
        gateway_btn.config(anchor = W, activebackground = "green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self, text="Services", variable = self.service, width=10)
        service_btn.grid(row = 2, column = 3)
        service_btn.config(anchor = W, activebackground = "blue")

        # Starting IP label
        ip_label = Label(self, text = "Starting IP:  ")
        ip_label.grid(row = 5, column = 0, pady = 1, padx = 3, sticky = W)
        self.ip_from = Entry(self, width = 15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row = 5 , column = 0, pady = 1, padx = 3, sticky = E)

        # Ending IP label
        ip_label_two = Label(self, text = "Ending IP:  ")
        ip_label_two.grid(row = 5, column = 1, pady = 1, padx = 5, sticky = W)
        self.ip_to = Entry(self, width = 15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = E)
        
        # Starting Port Label
        port_label = Label(self, text = "Starting Port:  ")
        port_label.grid(row = 5, column = 0, pady = 3, padx = 5, sticky = S+W)
        self.port_from = Entry(self, width = 15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row = 5 , column = 0, pady = 1, padx = 5, sticky = S+E)

        # Ending Port Label
        port_label_two = Label(self, text = "Ending Port:  ")
        port_label_two.grid(row = 5, column = 1, pady = 3, padx = 5, sticky = S+W)
        self.port_to = Entry(self, width = 15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = S+E)

        # Scan Me 
        self_scan_button = Button(self, text="Scan Me", command = lambda : self.onClick(1), width = 33)
        self_scan_button.grid(row = 6, column = 1, sticky = N)

        # Scan near me Button
        scan_other_button = Button(self, text="Scan Near Me", width = 33, command = lambda : self.onClick(2))
        scan_other_button.grid(row = 6, column = 0, pady=1, sticky = N)
        
        # Clear button
        clear_button = Button(self, text="Clear text", command = self.clear_text, width = 12)
        clear_button.grid(row = 6, column = 3, pady=1, sticky = N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient = HORIZONTAL, length = 175)
        self.label_scanning.grid(row = 6, column = 0, columnspan = 4, padx = 7, pady = 7, sticky = E+S+W)
        self.label_scanning.config(mode = "determinate")
Beispiel #44
0
Frame(root,
      height=root.winfo_screenheight() / 2 - 15,
      width=root.winfo_screenwidth(),
      bg='gray').grid(row=0, column=0, sticky=W + N)
Frame(root,
      height=root.winfo_screenheight() / 2 - 21,
      width=root.winfo_screenwidth(),
      bg='BurlyWood').grid(row=0, column=0, sticky=W + N)

analysisText = ScrolledText(root,
                            width=149,
                            height=18,
                            font=('Consolas', 13),
                            fg='black',
                            bg='white')
analysisText.grid(row=0, column=0, sticky=W + N, padx=6)
#数据部分
Frame2 = Frame(root,
               height=root.winfo_screenheight() / 4,
               width=root.winfo_screenwidth(),
               bg='gray')
Frame2.grid(row=1, column=0)

dataText = ScrolledText(Frame2,
                        width=149,
                        height=10,
                        font=('Consolas', 13),
                        fg='black',
                        bg='white')
dataText.grid(row=1, column=0, sticky=W, padx=5, columnspan=3)
Beispiel #45
0
    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background="#000000")
        self.style.configure("TCheckbutton", background="#000000")
        self.style.configure("TButton", background="#000000")
        self.pack(fill=BOTH, expand=1)

        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)

        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky=W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height=20)
        area.grid(row=1,
                  column=0,
                  columnspan=3,
                  rowspan=4,
                  padx=3,
                  sticky=N + S + E + W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self,
                                    text="IP Address",
                                    variable=self.ip,
                                    width=10)
        ip_add_button.grid(row=1, column=3, sticky=N)
        ip_add_button.config(anchor=W, activebackground="red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self,
                                  text="Ports",
                                  variable=self.port,
                                  width=10)
        port_button.grid(row=1, column=3)
        port_button.config(anchor=W, activebackground="orange")

        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self,
                                       text="Host Name",
                                       variable=self.host,
                                       width=10)
        host_name_button.grid(row=1, column=3, sticky=S)
        host_name_button.config(anchor=W, activebackground="yellow")

        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self,
                                  text="Gateway",
                                  variable=self.gateway,
                                  width=10)
        gateway_btn.grid(row=2, column=3, sticky=N)
        gateway_btn.config(anchor=W, activebackground="green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self,
                                  text="Services",
                                  variable=self.service,
                                  width=10)
        service_btn.grid(row=2, column=3)
        service_btn.config(anchor=W, activebackground="blue")

        # Starting IP label
        ip_label = Label(self, text="Starting IP:  ")
        ip_label.grid(row=5, column=0, pady=1, padx=3, sticky=W)
        self.ip_from = Entry(self, width=15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row=5, column=0, pady=1, padx=3, sticky=E)

        # Ending IP label
        ip_label_two = Label(self, text="Ending IP:  ")
        ip_label_two.grid(row=5, column=1, pady=1, padx=5, sticky=W)
        self.ip_to = Entry(self, width=15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row=5, column=1, pady=1, padx=5, sticky=E)

        # Starting Port Label
        port_label = Label(self, text="Starting Port:  ")
        port_label.grid(row=5, column=0, pady=3, padx=5, sticky=S + W)
        self.port_from = Entry(self, width=15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row=5, column=0, pady=1, padx=5, sticky=S + E)

        # Ending Port Label
        port_label_two = Label(self, text="Ending Port:  ")
        port_label_two.grid(row=5, column=1, pady=3, padx=5, sticky=S + W)
        self.port_to = Entry(self, width=15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row=5, column=1, pady=1, padx=5, sticky=S + E)

        # Scan Me
        self_scan_button = Button(self,
                                  text="Scan Me",
                                  command=lambda: self.onClick(1),
                                  width=33)
        self_scan_button.grid(row=6, column=1, sticky=N)

        # Scan near me Button
        scan_other_button = Button(self,
                                   text="Scan Near Me",
                                   width=33,
                                   command=lambda: self.onClick(2))
        scan_other_button.grid(row=6, column=0, pady=1, sticky=N)

        # Clear button
        clear_button = Button(self,
                              text="Clear text",
                              command=self.clear_text,
                              width=12)
        clear_button.grid(row=6, column=3, pady=1, sticky=N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient=HORIZONTAL, length=175)
        self.label_scanning.grid(row=6,
                                 column=0,
                                 columnspan=4,
                                 padx=7,
                                 pady=7,
                                 sticky=E + S + W)
        self.label_scanning.config(mode="determinate")
Beispiel #46
0
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
Beispiel #47
0
class EvalGUI:    
    def __init__(self, master):
        master.title("Eval")
      
        self.master = master
        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)

        self.fixed_width_font = ("Courier New", -12)
        self.frame.columnconfigure(0, weight=1)
        
        self.eval = Eval()

        # output control
        row = 0        
        self.out = ScrolledText(self.frame, wrap=NONE, bd=0, width=80, height=25, undo=1, maxundo=50, padx=5, pady=5, font=self.fixed_width_font)
        self.out.grid(row=row, column=0, sticky="NEWS")
        self.frame.rowconfigure(row, weight=1)

        # input control
        row += 1        
        self.commandEntry = EvalGUI.ExpressionEntry(self, master=self.frame, font=self.fixed_width_font)
        self.commandEntry.grid(row=row, column=0, sticky=EW)
        self.commandEntry.focus_set()
        
    def calculate(self, command):                
        result = self.eval.calculate(command)
        if result.isError(): return result
        self.out.insert(END, "a[%d] = %s = %s\n" % (result.index, command, result.data))
        self.out.yview_pickplace(END)        
        return result

    class ExpressionEntry(Entry):
        def __init__(self, eval, **args):
            self.evalInst = eval
            Entry.__init__(self, **args)
            self.history = []
            self.historyIdx = 1
            self.history0Text = ""
            self.bind('<Return>', self.onEnter)
            self.bind('<Up>', self.onUp)
            self.bind('<Down>', self.onDown)            
        
        def set(self, text):
            self.delete(0, len(self.get()))
            self.insert(0, text)
            self.select_range(0, len(text))
        
        def onEnter(self, event):
            command = self.get()
            self.history.append(command)
            result = self.evalInst.calculate(command)
            if not result.isError():
                self.select_range(0, len(command))
            else:
                result.printError()
                self.set(result.getErrorString())
            self.historyIdx = 1
        
        def onUp(self, event):
            self.setHistory(1)

        def onDown(self, event):
            self.setHistory(-1)

        def setHistory(self, change):
            if len(self.history) == 0: return
            # check if current content corresponds to history index, otherwise reset
            if self.get() != self.history[-self.historyIdx]:
                self.historyIdx = 0
            # remember user entry before using history
            if self.historyIdx == 0:
                self.history0Text = self.get()
            # set new history index
            self.historyIdx += change
            # check bounds
            if self.historyIdx < 0:
                self.historyIdx = 0
            elif self.historyIdx > len(self.history):
                self.historyIdx = len(self.history)
            # set new content
            if self.historyIdx == 0:
                self.set(self.history0Text)            
            else:
                self.set(self.history[-self.historyIdx])
Beispiel #48
0
    text.delete('1.0',END)
    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)
Beispiel #49
0
"2 hours" : 120 * 60,
"1.5 hours" : 90 * 60,
"1 hour" : 60 * 60,
"30 mins" : 30 * 60
}

w1State = StringVar()
w1State.set("30 mins") # default value
w1 = apply(OptionMenu, (master, w1State) + tuple(report_time_table.keys()))
w1.grid(row=2, column=6)
w1.config(state=DISABLED)

#--------Text scrollar defination--------------#
s1= ScrolledText(master)
s1['font'] = ('console','10')
s1.grid(row=8,columnspan=8,sticky="ew")
redir = redirect(s1)
sys.stdout = redir
sys.stderr = redir
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
logging.getLogger('').addHandler(console)
#log.addHandler(console)
#------- Menu defination -------------#

# parent menu
menubar = Menu()
# child menu 
fmenu = Menu()
fmenu.add_command(label = 'Export config', command = export)
fmenu.add_command(label = 'Import config', command = load)
Beispiel #50
0
#!/usr/bin/env python
# coding:utf-8
import urllib2
import http.client
import re
import Tkinter
from ScrolledText import ScrolledText
import lxml.html


root = Tkinter.Tk()
root.title('大众论坛--临沂')
text = ScrolledText(root, font=('微软雅黑', 10))
text.grid()  # 布局
varl = Tkinter.StringVar()
printTxt = ''

url='http://bbs.dzwww.com/forum.php?mod=forumdisplay&fid=138'
html = urllib2.urlopen(url).read().decode('utf-8', 'ignore')

doc = lxml.html.fromstring(html)

#print html
contents =  doc.xpath('//tr/th/a[3]')  #re.findall(reg, html)

print type(contents)


def start():
    for link in contents:
        print link.text
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)
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 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)
Beispiel #54
0
                         rowspan=2,
                         columnspan=17,
                         sticky=W + E + N + S)
Button(root, image=nxpLogo, bg='white').grid(row=0,
                                             column=17,
                                             rowspan=2,
                                             columnspan=1,
                                             sticky=W + E + N + S)

textBox = ScrolledText(root,
                       font=('times', 10),
                       height=30,
                       fg='green',
                       bg='black',
                       state=DISABLED)
textBox.grid(row=2, column=0, rowspan=4, columnspan=18, sticky=W + E + N + S)

Label(root,
      font=('times', 12, 'bold'),
      height=2,
      disabledforeground='black',
      text=USER_NAME_STR,
      bg='lightyellow',
      state=DISABLED,
      anchor=W).grid(row=6,
                     column=0,
                     rowspan=2,
                     columnspan=1,
                     sticky=W + E + N + S)
userNameEntry = Entry(root, bd=4, font=('times', 10))
userNameEntry.grid(row=6,
Beispiel #55
0
    D = Button(top,
               text="Scratch text",
               command=lambda: catchtext(text11.get(1.0, END)),
               height=2,
               width=13)
    E = Button(top,
               text="Scratch text",
               command=lambda: catchtext(text111.get(1.0, END)),
               height=2,
               width=13)
    # text.pack()
    # text1.pack()
    # C.pack()
    # text2.pack()
    B.grid(row=1, column=1)
    text.grid(row=1, column=0)
    # text.bind("<Button-1>", callback)
    text1.grid(row=2, column=0)
    C.grid(row=2, column=1)
    text11.grid(row=3, column=0)
    D.grid(row=3, column=1)
    text111.grid(row=4, column=0)
    E.grid(row=4, column=1)
    text2.grid(row=5, column=0)
    # root = Tk()

    #    text.insert(INSERT, "Hello.....")
    #    text.insert(END, "Bye Bye.....")

    top.mainloop()
Beispiel #56
0
msg1 = tkinter.ttk.Label(root, text='', foreground='red')
msg1.grid(row=6, column=0, columnspan=5)

sh = tkinter.ttk.Separator(root, orient=tkinter.HORIZONTAL)
sh.grid(row=7, column=0, columnspan=5, sticky="we")
sh = tkinter.ttk.Separator(root, orient=tkinter.HORIZONTAL)
sh.grid(row=8, column=0, columnspan=5, sticky="we")

sh = tkinter.ttk.Separator(root, orient=tkinter.HORIZONTAL)
sh.grid(row=19, column=0, columnspan=18, sticky="we")
sh = tkinter.ttk.Separator(root, orient=tkinter.HORIZONTAL)
sh.grid(row=20, column=0, columnspan=18, sticky="we")

label5.grid(row=21, column=0)
shellfield.grid(row=21, column=1, columnspan=8)
button = tkinter.ttk.Button(root, text='运行', command=main)
button.grid(row=21, column=9)
button = tkinter.ttk.Button(root, text='生成服务器信息', command=checkreport)
button.grid(row=21, column=10)
text = ScrolledText(root,
                    font=('Fixedsys', 12),
                    fg='blue',
                    width=93,
                    height=16,
                    wrap=tkinter.WORD)
text.grid(row=22, column=0, rowspan=18, columnspan=14)

viewmsg()
root.config(menu=menubar)
root.mainloop()
Beispiel #57
0
class PixivDownloadFrame(Frame):
    def __init__(self, root, api, search_handler):
        Frame.__init__(self, root)
        if not search_handler or not api:
            raise PixivError(
                'You must set  authPixivApi and search_handler for the DownloadFrame'
            )
        self.api = api
        self.search_handler = search_handler
        self.downloader = IllustrationDownloader(api)
        self.queue = PixivQueue(self.downloader,
                                callback=self.download_callback)
        self.task_text = ScrolledText(self,
                                      height=20,
                                      width=30,
                                      bg='light gray')
        self.print_text = ScrolledText(self,
                                       height=20,
                                       width=40,
                                       bg='light gray')
        self.root = root
        self.frames = [
            DownloadFrame(self, 'By Url or Id', self.queue, self.api,
                          self.task_text),
            SearchFrame(self, 'By Search', self.queue, self.api,
                        self.search_handler),
            RankingFrame(self, 'By Ranking', self.queue, self.api),
            RelatedFrame(self, 'By Related', self.queue, self.api)
        ]
        self.switch_menu = None
        self.init_ui()

    def init_ui(self):
        self.root.title("Pixiv Downloader")
        self.root.resizable(width=False, height=False)
        menubar = Menu(self)
        self.root.config(menu=menubar)
        self.switch_menu = Menu(menubar, tearoff=0)
        for frame in self.frames:
            frame.init_ui()
            frame.set_frames(self.frames)
            self.switch_menu.add_command(label=frame.name,
                                         command=frame.switch)
        menubar.add_cascade(label="Download Mode Switch",
                            menu=self.switch_menu)
        # 公共组件
        # text1.bind("<Key>", lambda e: "break")
        self.task_text.insert(END, 'Download Completed:\n')
        self.print_text.tag_configure('info', foreground='#3A98FE')
        self.print_text.tag_configure('warning', foreground='#ff9900')
        self.print_text.tag_configure('error', foreground='#FF2D21')
        quote = "Console Log:\n"
        self.print_text.insert(END, quote, 'info')
        self.task_text.grid(row=3, column=0, sticky=W)
        self.print_text.grid(row=3, column=1, sticky=W)

        banner = Label(self, text="Power by imn5100", width=30, height=5)
        banner.grid(row=4, columnspan=2)

        self.grid()
        self.frames[0].grid(row=1, columnspan=2)
        self.queue.run()

    def download_callback(self, msg=None):
        """
        任务完成回调
        :param msg: 回调消息
        :return: none
        """
        if msg:
            self.task_text.insert(END, msg)
        else:
            self.task_text.insert(END, "A work Done\n")
Beispiel #58
0
from ScrolledText import ScrolledText
from Tkinter import *
from GUI.function import login_from_GUI

window = Tk()

window.title("INSTATRACK - LOGIN ")

window.geometry('1000x300')

lbl = Label(window, text="Voglio la LAMBORGHINI")

lbl.grid(column=0, row=0)

txt = ScrolledText(window, width=90, height=20)

txt.grid(column=0, row=1)


def clicked():
    login_from_GUI(txt)
    print("Premuto il pulsante")


btn = Button(window, text="LOGIN", command=clicked)

btn.grid(column=1, row=0)

window.mainloop()
Beispiel #59
0
def salvar():
    fichero = tkFileDialog.asksaveasfilename()
    f = open(fichero,"w")
    f.write(contenido.get(1.0, END))
    f.close()
    
if __name__ == '__main__':
    
    ventana = Tk()
    ventana.title("Editor tonto de textos")
    
    t = Label(ventana)
    t.grid(row=0, column=2, sticky=W + E, columnspan=2)
    
    nombreFichero = StringVar()
    t["textvariable"] = nombreFichero

    botonLoad = Button(ventana, text="Load", command=cargar)
    botonLoad.grid(row=0, column=0, sticky=W)
    
    botonSave = Button(ventana, text="Save", command=salvar)
    botonSave.grid(row=0, column=1, sticky=W)
    
    contenido = ScrolledText(ventana)
    contenido.grid(row=1, columnspan=3, sticky=W + E + N + S)
    
    ventana.grid_columnconfigure(2, weight=1)
    ventana.grid_rowconfigure(1, weight=1)
    ventana.mainloop()