예제 #1
0
    def populatePositionBarFrame(self, master):

        master.grid_columnconfigure(0, weight=1)

        row = 0
        col = 0
        w = self.wPosBar = Progressbar(master,
                                       style="TProgressbar",
                                       orient='horizontal',
                                       length=100,
                                       mode='indeterminate')

        #w = self.wPosBar = Progressbar (
        #	master, orient = 'horizontal',
        #	length = 100, mode = 'indeterminate')

        w.grid(row=row, column=col, sticky=NSEW)
        w['value'] = self.relBarMin
        w['maximum'] = self.relBarMax

        row += 1
        w = self.wRelPosBar = Progressbar(master,
                                          style="TProgressbar",
                                          orient='horizontal',
                                          length=100,
                                          mode='indeterminate')

        #w = self.wRelPosBar = Progressbar (
        #	master, orient = 'horizontal',
        #	length = 100, mode = 'indeterminate')

        w.grid(row=row, column=col, sticky=NSEW)
        w['value'] = self.relBarMin
        w['maximum'] = self.relBarMax
    def __init__(self, parent, progress_var):
        Frame.__init__(self, parent)

        progress_label = Label(self, text="Progress:")
        progress_label.pack(side=LEFT, anchor=CENTER, padx=12, pady=3)

        self.progressbar = Progressbar(self, length=903, variable=progress_var)
        self.progressbar.pack(side=RIGHT, padx=6)
예제 #3
0
    def create_layout(self):
        # usb label 
        usb_lbl = Label(text='usb status:', height=4, width=20, font=self.font_size)
        usb_lbl.grid(column=0, row=0)

        # usb status label
        self.usb_status_lbl = Label(text=self.usb_status, height=4, width=20, font=self.font_size)
        self.usb_status_lbl.grid(column=1, row=0)

        # network label 
        net_lbl = Label(text='network status:', height=4, width=20, font=self.font_size)
        net_lbl.grid(column=0, row=1)

        # network status label
        self.net_status_lbl = Label(text=self.net_status, height=4, font=self.font_size)
        self.net_status_lbl.grid(column=1, row=1)

        # start date label
        start_lbl = Label(text='start date:', height=4, font=self.font_size)
        start_lbl.grid(column=0, row=2)
        
        # start date text
        self.start_txt = Entry(width=25, font=self.font_size) 
        self.start_txt.grid(column=1, row=2)
        
        # end date label
        end_lbl = Label(text='end date:', height=4, font=self.font_size)
        end_lbl.grid(column=0, row=3)
        
        # end date text
        self.end_txt = Entry(width=25, font=self.font_size) 
        self.end_txt.grid(column=1, row=3)

        # start button
        self.usb_button = Button(text='USB sync', height=3,  command= lambda: self.start_button_click('USB'), font=self.font_size)
        self.usb_button.grid(column=0, row=4, sticky=N+S+E+W) 

        # stop button
        self.stop_button = Button(text='stop sync', height=3, command= lambda: self.stop_button_click(), font=self.font_size)
        self.stop_button.grid(column=1, row=4, sticky=N+S+E+W) 

        # start button
        self.net_button = Button(text='Net sync', height=3, command= lambda: self.start_button_click('Net'), font=self.font_size)
        self.net_button.grid(column=0, row=5, sticky=N+S+E+W) 
        
        # start button
        self.exit_button = Button(text='exit', height=3, command=self.exit, font=self.font_size)
        self.exit_button.grid(column=1, row=5, sticky=N+S+E+W) 

        # sync status label
        self.sync_status_lbl = Label(text=self.sync_status, width=50, height=4, font=self.font_size)
        self.sync_status_lbl.grid(column=0, row=6, columnspan=2)

        # progress bar
        self.progressbar = Progressbar(orient='horizontal', length=240, mode='determinate', style='text.Horizontal.TProgressbar')

        # time estimator
        self.time_est = Label(height=3, font=self.font_size)
예제 #4
0
 def __init__(self, parent, **kwargs):
     """!
     A constructor for the class
     @param self The pointer for the object
     @param parent The parent object for the frame
     @param **kwargs Other arguments as accepted by ttk.Scrollbar
     """
     #Initialise the inherited class
     Progressbar.__init__(self, parent, **kwargs)
예제 #5
0
파일: fenetre.py 프로젝트: jmarzin/rarefu
 def __init__(self, lecteur):
     self.root = Tk()
     self.max = lecteur.getNumPages()
     self.label = Label(self.root, text="Interprétation des pages")
     self.label.pack()
     self.progressbar = Progressbar(self.root,
                                    orient='horizontal',
                                    length=200,
                                    value=0)
     self.progressbar.pack()
     self.root.update()
예제 #6
0
 def loadplaylist(self):
     progress_dialog = tk.Toplevel()
     progress_dialog.title("Loading Playlist")
     bar = Progressbar(progress_dialog,
                       orient="horizontal",
                       length=500,
                       value=0,
                       mode="determinate")
     bar.grid(row=4, columnspan=2)
     thread = threading.Thread(target=self.threadedPlaylistLoad,
                               args=(bar, progress_dialog))
     thread.start()
def splashscreen():
    root = Tk()
    root.geometry("+200+200")
    root.overrideredirect(True)
    root.configure(bg = "white")
    back = PhotoImage(file = "splashscreen.gif")
    l1 = Label(root, image = back, bg = "white")
    scritta = Progressbar(root, orient = "horizontal", mode = "determinate", length = 240)
    scritta.start(30)
    copyright = Label(root, text = "Copyright by lokk3d", bg = "white")
    root.after(3000, root.destroy)
    l1.pack()
    scritta.pack(side  = "left")
    copyright.pack( side = "right")
    root.mainloop()
예제 #8
0
파일: fenetre.py 프로젝트: jmarzin/rarefu
class Suivi:
    def __init__(self, lecteur):
        self.root = Tk()
        self.max = lecteur.getNumPages()
        self.label = Label(self.root, text="Interprétation des pages")
        self.label.pack()
        self.progressbar = Progressbar(self.root,
                                       orient='horizontal',
                                       length=200,
                                       value=0)
        self.progressbar.pack()
        self.root.update()

    def maj(self, avancement):
        self.progressbar['value'] = avancement * 100 / self.max
        self.root.update()
예제 #9
0
 def show_progress(self, start):
     if start:
         self.prog_win = Toplevel(self.main_container, padx=8, pady=8)
         self.prog_win.transient(self)
         self.prog_win.title('Working...')
         self.prog_win.resizable(0, 0)
         self.progress_bar = Progressbar(self.prog_win,
                                         orient=HORIZONTAL,
                                         mode='indeterminate',
                                         length=250,
                                         takefocus=True)
         self.progress_bar.grid()
         self.progress_bar.start()
     else:
         self.progress_bar.stop()
         self.prog_win.destroy()
예제 #10
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.selected = "";
        self.controller = controller
        label = Label(self, text="Select server", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label.pack(side="top", fill="x", pady=10)
        
        self.button1 = Button(self, text="Next",state="disabled", command=self.callback_choose)
        button2 = Button(self, text="Refresh", command=self.callback_refresh)        
        button3 = Button(self, text="Back", command=self.callback_start)
        
        scrollbar = Scrollbar(self)
        self.mylist = Listbox(self, width=100, yscrollcommand = scrollbar.set )
        self.mylist.bind("<Double-Button-1>", self.twoClick)

        self.button1.pack()
        button2.pack()
        button3.pack()
        # create list with a scroolbar
        scrollbar.pack( side = "right", fill="y" )
        self.mylist.pack( side = "top", fill = "x", ipadx=20, ipady=20, padx=20, pady=20 )
        scrollbar.config( command = self.mylist.yview )
        # create a progress bar
        label2 = Label(self, text="Refresh progress bar", justify='center', anchor='center')
        label2.pack(side="top", fill="x")
        
        self.bar_lenght = 200
        self.pb = Progressbar(self, length=self.bar_lenght, mode='determinate')
        self.pb.pack(side="top", anchor='center', ipadx=20, ipady=20, padx=10, pady=10)
        self.pb.config(value=0)
예제 #11
0
파일: biab.py 프로젝트: ob/biab
 def layout_gui(self):
     master = self.master
     s = Style()
     s.theme_use('default')
     s.configure('TProgressbar', thickness=50)
     helv36 = tkFont.Font(family='Helvetica', size=36, weight='bold')
     b = Button(master, text="Quit", command=self.quit, width=10, height=2)
     b['font'] = helv36
     b.grid(row=0, column=0)
     pb = Progressbar(master,
                      orient=VERTICAL,
                      length=100,
                      mode='determinate',
                      style='TProgressbar')
     pb['value'] = 50
     pb.grid(row=0, column=1)
예제 #12
0
    def __init__(self, master):
        self.root = master
        self.searching = False
        self.can_download = True
        audiojack.set_useragent('AudioJack', '1.0')
        self.frame = ScrollableFrame(self.root)
        self.frame.setconfig(bg='#0D47A1', width=1280, height=720)
        self.frame.pack(side=TOP, fill=BOTH, expand=1)
        self.label = Label(self.frame.mainframe, text='AudioJack', fg='#ffffff', bg=self.frame.mainframe['background'], font=('Segoe UI', 48))
        self.label.pack()
        self.url_entry = Entry(self.frame.mainframe, width=48, font=('Segoe UI', 20), bg='#1565C0', bd=2, highlightthickness=1, highlightcolor='#1565C0', highlightbackground='#0D47A1', fg='#ffffff', insertbackground='#ffffff', relief=FLAT, insertwidth=1)
        self.url_entry.pack()
        self.submit_button = Button(self.frame.mainframe, width=60, font=('Segoe UI', 16), text='Go!', bd=0, bg='#1E88E5', fg='#ffffff', activebackground='#2196F3', activeforeground='#ffffff', relief=SUNKEN, cursor='hand2', command=self.submit)
        self.submit_button.pack()

        self.search_progress = Progressbar(self.frame.mainframe, orient='horizontal', length=720, maximum=100 ,mode='indeterminate')

        self.error_info = Label(self.frame.mainframe, fg='#ff0000', bg=self.frame.mainframe['background'])

        # Use pack_forget on this to reset the view
        self.contents = Frame(self.frame.mainframe, bg=self.frame.mainframe['background'])

        # Contains results and custom tag options
        self.select_frame = Frame(self.contents, bg=self.frame.mainframe['background'])
        self.select_frame.pack()

        #Search results
        self.results_label = Label(self.select_frame, text='Results:', fg='#ffffff', bg=self.frame.mainframe['background'])
        self.results_frame = Frame(self.select_frame, bg=self.frame.mainframe['background'])
        self.results_label.pack()
        self.results_frame.pack()

        # Downloads
        self.file_label = Label(self.contents, fg='#ffffff', bg=self.frame.mainframe['background'])
예제 #13
0
    def configureLayout(self):

        self.top_frame = Frame(self, relief=RAISED, borderwidth=1)

        self.tip_label_text = StringVar()
        self.tip_label = Label(self.top_frame, textvariable=self.tip_label_text)
        self.tip_label_text.set("Install KA Lite")

        self.kaliteleaf_label = Label(self.top_frame, image=self.kaliteleaf_photo, width=16, height=16)
        self.kaliteleaf_label.image = self.kaliteleaf_photo

        self.info_label_text = StringVar()
        self.info_label_frame = Frame(self)
        self.info_label = Label(self.info_label_frame, textvariable=self.info_label_text)
        self.info_label_text.set("Ready to start...")

        self.progress_bar_frame = Frame(self)
        self.progress_bar_value = IntVar()
        self.progress_bar = Progressbar(self.progress_bar_frame, mode="indeterminate", variable=self.progress_bar_value, length=400)

        self.bottom_space_frame = Frame(self)

        self.install_button_frame = Frame(self)
        self.install_button = Button(self.install_button_frame, text="Install", command=self.startInstallation, width=15, height=2)

        self.quit_button = Button(self.install_button_frame, text="Quit", state=DISABLED, command=quitInstaller, width=15, height=2)
	def __body(self):
		self.BUTTONS={}
		self.BUTTONS["Update"]=Button(self,text="Update",command=self.updateManga)
		self.BUTTONS["CheckForUpdates"]=Button(self,text="Check Updates",command=self.updateManga_check)
		self.BUTTONS["Delete"]=Button(self,text="Delete",command=self.deleteManga)

		self.BUTTONS["Update"].grid(row=0,column=0,sticky=N+S+E+W)
		self.BUTTONS["CheckForUpdates"].grid(row=1,column=0,sticky='nsew')
		self.BUTTONS["Delete"].grid(row=2,column=0,sticky=N+S+E+W)

		self.LABELS={}
		self.LABELS["Status"]=Label(self,text="Status:\nUnknown")
		self.LABELS["ChapterCount"]=Label(self,text="Chapters:\nUnknown")
		self.LABELS["Updates"]=Label(self,text="Updates:\nUnknown")
		self.LABELS["Summary"]=LabelResizing(self,text="Summary:\n")
		self.LABELS["Picture"]=Label(self,image=None)
		self.LABELS["UpdatingStatus"]=Label(self,text="")

		self.LABELS["Status"].grid(row=0,column=1)
		self.LABELS["ChapterCount"].grid(row=1,column=1)
		self.LABELS["Updates"].grid(row=2,column=1)
		self.LABELS["Summary"].grid(row=3,column=0,sticky='nwe')
		self.LABELS["Picture"].grid(row=0,column=2,rowspan=5)
		self.LABELS["UpdatingStatus"].grid(row=5,column=0,columnspan=3)

		self.PROGRESSBAR=Progressbar(self)
		self.PROGRESSBAR.grid(row=6,column=0,columnspan=3,sticky=E+W)

		self.bindChidrenScrolling()
		self.grid_columnconfigure(0,weight=1)
		self.grid_columnconfigure(1,weight=2)
예제 #15
0
def progress_bar(root, filelist):
    global pbar_step, pbar_perc_step

    # create the window with the initial title
    Pwin = Toplevel(root)
    Pwin.title('Scanning files...(counting lines)')
    Pwin.grab_set()
    Pwin.pbar_var = IntVar(Pwin)
    # very simple window with one widget, a 400px progress bar
    # max value is set to the number of files

    # create a ttk Progressbar if we can, otherwise fake on with a Scale widget
    if real_pbar:
        Pwin.pbar = Progressbar(Pwin, orient='horizontal', length=400, mode='determinate', variable=Pwin.pbar_var,
                                maximum=len(filelist))
    else:
        Pwin.pbar = Scale(Pwin, orient='horizontal', length=400, from_=0.0, to=float(len(filelist)), label='Files',
                          resolution=1.0)
    Pwin.pbar.grid(row=0, column=0, padx=15, pady=15)
    Pwin.pbar_var.set(0)
    Pwin.update()

    # count the lines in the files
    # this is pretty fast, but no so fast that it's not worth keeping the progress bar visible for now
    # very large files may take a few seconds, and if you have large numbers of files
    linecount = 0
    for file in filelist:
        l = scanfile(file)
        if real_pbar:
            Pwin.pbar.step(1)
        else:
            pbar_pos = Pwin.pbar.get() + 1.0
            Pwin.pbar.set(pbar_pos)
        Pwin.update()
        if l != -1:
            linecount += l

    # set the progress bar step amount - make it roughly 0.5% of the total
    pbar_step = int(linecount / 200)
    if pbar_step < PROGBAR_STEP:
        pbar_step = PROGBAR_STEP

    # this is the point where we may decide not to show the progress bar
    if linecount > SHOW_PROGBAR_THRESHOLD:
        Pwin.title('Scanning files...(checking queries)')
        if real_pbar:
            Pwin.pbar.configure(maximum=linecount)
            Pwin.pbar.start()
        else:
            Pwin.pbar.configure(to=100.0, resolution=0.1, label='Progress %')
            Pwin.pbar.set(0.0)
            pbar_perc_step = (pbar_step * 100.0) / float(linecount)
        Pwin.update()
        return Pwin
    else:
        Pwin.grab_release()
        Pwin.destroy()
        return None
예제 #16
0
파일: micall.py 프로젝트: tarah28/MiCall
    def __init__(self, parent, *args, **kwargs):
        self.pssm = Pssm(path_to_lookup=AssetWrapper('micall/g2p/g2p_fpr.txt').path,
                         path_to_matrix=AssetWrapper('micall/g2p/g2p.matrix').path)

        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        parent.report_callback_exception = self.report_callback_exception

        self.rundir = None  # path to MiSeq run folder containing data
        self.workdir = gettempdir()  # default to temp directory
        os.chdir(self.workdir)
        
        self.line_counter = LineCounter()

        self.run_info = None
        self.target_files = []

        self.button_frame = tk.Frame(self)
        self.button_frame.pack(side='top')
        self.console_frame = tk.Frame(self)
        self.console_frame.pack(side='top', fill='both', expand=True)
        
        try:
            with open(MiCall.CONFIG_FILE, 'rU') as f:
                self.config = json.load(f)
        except:
            self.config = {}

        self.nthreads = self.config.get('threads', None)
        if not self.nthreads:
            self.nthreads = int(round(cpu_count() * 0.5))
            self.config['threads'] = self.nthreads
            self.write_config()

        self.button_run = tk.Button(
            self.button_frame, text="Run", command=self.process_files
        )
        self.button_run.grid(row=0, column=1, sticky='W')

        self.progress_bar = Progressbar(self.button_frame, orient='horizontal', length=500, mode='determinate')
        self.progress_bar.grid(row=1, columnspan=5)

        scrollbar = tk.Scrollbar(self.console_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.console = tk.Text(self.console_frame,
                               bg='black',
                               fg='white',
                               yscrollcommand=scrollbar.set)
        self.console.pack(side=tk.LEFT, fill=tk.BOTH)
        self.console.tag_configure('ERROR', foreground="red")
        scrollbar.config(command=self.console.yview)

        # redirect stderr to Text widget
        #sys.stderr = Redirector(self.console)

        self.write('Welcome to MiCall v{}, running with {} threads.\n'.format(
            pipeline_version,
            self.nthreads))
예제 #17
0
	def __init__(self, parent, controller, frame_number):
		BaseInputPage.__init__(self, parent, controller, frame_number)

		self.move_back = False
		self.need_subjects_file = False

		self.downloaded_file_path = '~/Downloads/'

		self.operation = Operations(self.controller)

		self.start = tk.Button(self, text='Start Execution', command=lambda : self.executeCommand())
		self.start.grid(row=self.starting_row, column=0, sticky='W', padx=5, pady=3)

		self.stop = tk.Button(self, text='Stop Execution', state="disabled", command=lambda : self.terminateCommand())
		self.stop.grid(row=self.starting_row, column=2, sticky='E', padx=5, pady=3)

		self.progressbar = Progressbar(self)
		self.progressbar.configure(mode='determinate', max=100)
		self.progressbar.grid(row=self.starting_row+1, column=0, columnspan=3, sticky='ew', padx=10, pady=10)

		self.controller.progressbar = self.progressbar

		self.output = Text(self, height=15, width=100)
		self.output.grid(row=self.starting_row+2, column=0, columnspan=3, sticky='ew', padx=10)
		self.hyperlink = HyperlinkManager(self.output)

		self.lf_subject_file = LabelFrame(self, text='Visual QC', padx=15, font='Helvetica 14 bold')
		self.lf_subject_file.grid(row=self.starting_row+3, column=0, columnspan=3, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
		self.lf_subject_file.grid_rowconfigure(0, weight=1)
		self.lf_subject_file.grid_columnconfigure(4, weight=1)
		createToolTip(self.lf_subject_file, self.controller.desc.subject_file)

		self.lb_subject_file = Label(self.lf_subject_file, text="Select flagged subjects textfile", font='Helvetica 13 bold')
		self.lb_subject_file.grid(row=0, column=0, sticky="W", pady=3)

		self.select = tk.Button(self.lf_subject_file, text='Select flagged subjects file', command=lambda : self.chooseFile(self, controller, controller.selected_subjects, 'Selected Subjects', default_dir=self.downloaded_file_path))
		self.select.grid(row=1, column=0, sticky='W', padx=5, pady=3)

		lb_or = Label(self.lf_subject_file, text="-OR-", font='Helvetica 13 bold')
		lb_or.grid(row=1, column=1, sticky="W", pady=3)

		self.continue_with_all_sub = tk.Button(self.lf_subject_file, text='Continue with all subjects', command=lambda : self.continueWithAllSub())
		self.continue_with_all_sub.grid(row=1, column=2, sticky='W', padx=10, pady=3)

		self.controller.display = self.output
    def init_widgets(self):
        self.content_wrapper = Frame(self)
        self.content_wrapper.configure(bg="white")

        self.screen_title = Header1Label(self.content_wrapper)
        self.empty_space_1 = PLabel(self.content_wrapper)
        self.progress_bar_control_var = DoubleVar()
        self.progress_bar = Progressbar(self.content_wrapper,
                                        orient=HORIZONTAL,
                                        mode="determinate",
                                        length=WINDOW_WIDTH / 2,
                                        variable=self.progress_bar_control_var)
        self.wait_text = PLabel(self.content_wrapper)
        self.information_display = PLabel(self.content_wrapper)
        self.empty_space_2 = PLabel(self.content_wrapper)
        self.next_button = Button(self.content_wrapper,
                                  text="Next",
                                  state=DISABLED,
                                  command=lambda: self.on_next_button())
예제 #19
0
파일: guielements.py 프로젝트: rmtew/PyDA
    def addProgressBar(self, pack_side, **kwargs):
        '''
        Arguments:
        pack_side - the side in which the Progressbar will be packed
        kwargs - optional keyword arguments

        Description:
        Adds a Progressbar to the toolbar.
        '''
        return self.addElement(Progressbar(self, **kwargs), pack_side)
예제 #20
0
 def startProgressbar(self):
     progressbar = Progressbar(self.progressFrame,
                               orient="horizontal",
                               length=500,
                               mode="indeterminate")
     thread = threading.Thread(target=self.animateProgressBar,
                               args=[progressbar])
     thread.daemon = True
     self.progressbarRunning = True
     thread.start()
     return thread
예제 #21
0
    def __init__(self, tk_frame, police, **kwargs):
        LabelFrame.__init__(self, tk_frame, text="Tirage", font=police, **kwargs)
        self.waiting_time = 10

        self.message = Label(self, text="Appuyez sur le bouton pour lancer le tirage", font=police)
        self.message.grid(column=0, row=0, columnspan=2)

        self.bouton_quitter = Button(self, text="Quitter", command=self.quit, font=police)
        self.bouton_quitter.grid(column=0, row=1, pady=10)

        self.bouton_cliquer = Button(self, text="Lancer!", fg="red",
                                     command=self.click, font=police)
        self.bouton_cliquer.grid(column=1, row=1)

        self.message_price = Label(self, text="Tirage pour:", font=police)
        self.price = Label(self, text='', bg="white", width=40, height=1, font=police)
        self.message_price.grid(column=0, row=3)
        self.price.grid(column=1, row=3, columnspan=1, padx=10, pady=10)

        self.message_name = Label(self, text="Le gagnant est:", font=police)
        self.name = Label(self, text="", bg="white", width=40, height=1, font=police)
        self.message_name.grid(column=0, row=4)
        self.name.grid(column=1, row=4, columnspan=1, pady=10)
        
        self.parent_name = self.winfo_parent()
        self.parent = self._nametowidget(self.parent_name)

        # Part waiting time
        self.interval = Label(self, text="Intervalle entre tirages (s)", font=police)
        self.interval.grid(column=0, row=6, columnspan=1, pady=10)
        self.v = StringVar()
        self.v.set(self.waiting_time)
        self.interval_length = Entry(self, textvariable=self.v,  width=5, justify=CENTER, font=police)
        self.interval_length.grid(column=1, row=6, columnspan=1)
        self.progress_bar = Progressbar(self, length=300)
        self.progress_bar.grid(column=0, row=8, columnspan=2, pady=10)
        self.nb_players_text = Label(self, text="Nombre de joueurs", font=police)
        self.nb_players_text.grid(column=0, row=10, columnspan=1, pady=10)
        self.nb_players = Label(self, text="0", font=police)
        self.nb_players.grid(column=1, row=10, columnspan=1, pady=10)
        self.nb_prices_text = Label(self, text="Nombre de prix restants", font=police)
        self.nb_prices_text.grid(column=0, row=11, columnspan=1, pady=10)
        self.nb_prices = Label(self, text="0", font=police)
        self.nb_prices.grid(column=1, row=11, columnspan=1, pady=10)

        # police=tkFont.Font(self, size=12)#, family='Courier')
        # self.config(, font=police)
        # for i in range(5):
        # self.grid_rowconfigure(2, weight=1)
        # self.grid_rowconfigure(5, weight=1)
        # self.grid_rowconfigure(7, weight=1)
        # self.grid_rowconfigure(9, weight=1)
        for i in range(2):
            self.grid_columnconfigure(i, weight=1)
예제 #22
0
	def sonifyProcessPage(self):

		Label(self, text="Processing", justify=CENTER, font=root.fontH1).pack(pady=20)

		self.processing = Label(self, text="", justify=CENTER)
		self.processing.pack(pady=20)

		self.pbar = Progressbar(self, orient='horizontal', mode='indeterminate')
		self.pbar.start(10)
		self.pbar.pack()

		self.after(100, self.sonifyProcess)
예제 #23
0
    def __init__(self, master, sproxy):
        """
        Construct new TkSynthWindow

        master - The Tk container for self.  In practice this is an 
                 instance of llia.gui.tk.GroupWindow

        sproxy - An instance of llia.Proxy.
        """
        Frame.__init__(self, master)
        self.config(background=factory.bg())
        self.synth = sproxy
        self.synth.synth_editor = self
        self.app = sproxy.app
        self.sid = sproxy.sid
        self.group_index = -1
        factory.set_pallet(sproxy.specs["pallet"])
        main = factory.paned_window(self)
        main.pack(expand=True, fill="both")
        self.bank_editor = TkBankEditor(main, self, sproxy)
        self.bus_and_buffer_editor = None
        east = factory.frame(main)
        self.notebook = factory.notebook(east)
        self.notebook.pack(anchor="nw", expand=True, fill="both")
        south = factory.frame(east)
        south.pack(after=self.notebook, anchor="w", expand=True, fill="x")
        self._lab_status = factory.label(south, "<status>")
        self._lab_extended = factory.label(south, "")
        b_panic = factory.panic_button(south, command=self.panic)
        b_lower = factory.button(south, "-", command=self.lower_window)
        b_lift = factory.button(south, "+", command=self.lift_window)
        b_panic.grid(row=0, column=0)
        self._lab_status.grid(row=0, column=4, sticky='ew')
        self._lab_extended.grid(row=0,column=5,sticky='e',padx=16)
        self._lab_extended.config(fg="#f1f1cd")
        self._progressbar = Progressbar(south,mode="indeterminate")
        self._progressbar.grid(row=0,column=PROGRESSBAR_COLUMN, sticky='w', padx=8)
        south.config(background=factory.bg())
        main.add(self.bank_editor)
        main.add(east)
        self.list_channel = None
        self.list_keytab = None
        self.var_transpose = StringVar()
        self.var_keyrange_low = StringVar()
        self.var_keyrange_high = StringVar()
        self.var_bendrange = StringVar()
        self._init_midi_tab(self.notebook)
        self._init_map1_tab(self.notebook) # MIDI controllers and pitchwheel
        self._init_map2_tab(self.notebook) # velocity, aftertouch, keynumber
        self._init_info_tab(self.notebook)
        self._child_editors = {}
        self.update_progressbar(100, 0)
예제 #24
0
    def __init__(self, title, txt):
        LabelFrame.__init__(self, text=title)
        # Bar of global progress
        Label(self, text = 'Global progress').grid(row=1, column = 0)
        self.proglob = Progressbar(self,
                                orient = HORIZONTAL,
                                max = 50,
                                length = 200,
                                mode = 'determinate')
        # Bar of attributes progress
        Label(self, text = 'Attributes progress').grid(row=3, column = 0)
        self.progatt = Progressbar(self,
                                orient = HORIZONTAL,
                                max = 50,
                                length = 200,
                                mode = 'determinate')

        # Widgets placement
        self.proglob.grid(row=2, column = 0,  sticky = N+S+W+E,
                          padx = 2, pady = 2)
        self.progatt.grid(row=4, column = 0,  sticky = N+S+W+E,
                          padx = 2, pady = 2)
    def init_ui(self):
        MyFrame.init_ui(self)

        self.columnconfigure(0, weight=2, minsize=150)
        self.columnconfigure(1, weight=3, minsize=100)

        self.file_name      = TextEntry(self, 'Recorded file name')
        self.record_time    = TextEntry(self, 'Record time')
        self.progress_bar   = Progressbar(self, orient='horizontal', mode='determinate')

        self.progress_bar.grid(columnspan=2, sticky='NESW')

        Button(self, text='Record', command=self.threaded_record).grid(columnspan=2, sticky='NESW')
예제 #26
0
파일: top_ten.py 프로젝트: monkee52/TopTen
    def get_source(url):
        # Create a popup to display the progress bar
        progress_popup = Toplevel(window)

        progress_popup.title("Loading...")

        display_url = url

        # Shorten the URL if it is too long
        if len(display_url) > 50:
            display_url = display_url[:47] + "..."

        # Display the URL
        label = Label(progress_popup, text="Downloading %s" % display_url)

        label.pack(padx=PADDING, pady=PADDING)

        if "Progressbar" in globals():
            # Create a progress bar
            bar = Progressbar(progress_popup,
                              orient=HORIZONTAL,
                              mode="indeterminate")

            bar.pack(expand=True,
                     fill=BOTH,
                     side=TOP,
                     padx=PADDING,
                     pady=PADDING)
            bar.start()

        window.config(cursor="wait")
        window.update()

        # Lock the window
        progress_popup.focus_set()
        progress_popup.grab_set()
        progress_popup.transient(window)

        downloader = GetSource(url)

        downloader.start()

        # Wait for the file to finish downloading
        while downloader.is_alive():
            # Keep the main thread updated to avoid a not responding window
            window.update_idletasks()
            window.update()

            downloader.join(0.0001)

        # Close the popup dialog
        progress_popup.destroy()

        window.config(cursor="")
        window.update()

        # Return the data to the calling function
        return downloader.data
 def init_widgets(self):
     self.content_wrapper = Frame(self)
     self.content_wrapper.configure(background="white")
     self.screen_title = Header1Label(
         self.content_wrapper, text="Scanning video for information...\n")
     self.progress_bar = Progressbar(self.content_wrapper,
                                     orient=HORIZONTAL,
                                     mode="indeterminate",
                                     length=WINDOW_WIDTH / 2)
     self.wait_text = PLabel(
         self.content_wrapper,
         text="\nThis might take a few minutes."
         "\nPlease do not change the video files while this is running.\n")
     self.left_frames_count = PLabel(self.content_wrapper,
                                     text=LEFT_FRAMES_COUNT_PREFIX + "0")
     self.right_frames_count = PLabel(self.content_wrapper,
                                      text=RIGHT_FRAMES_COUNT_PREFIX + "0")
     self.elapsed_time_label = PLabel(self.content_wrapper)
     self.empty_space = PLabel(self.content_wrapper, text=" ")
     self.next_button = Button(
         self.content_wrapper,
         text="Next",
         state=DISABLED,
         command=lambda: self.controller.show_next_frame())
예제 #28
0
    def load_progress_bar(self):
        """
        Load progress bar method used with root.after.
        If root.after not used, gui will not load.
        """
        self.progress_bar_style.layout("progress_bar", [
            ("progress_bar.trough", {
                "children": [("progress_bar.pbar", {
                    "side": "left",
                    "sticky": "ns"
                }), ("progress_bar.label", {
                    "sticky": ""
                })],
                "sticky":
                "nswe",
            })
        ])

        self.progress_bar = Progressbar(self.progress_frame,
                                        orient="horizontal",
                                        style="progress_bar")
        self.progress_bar.pack(expand=1,
                               fill="x",
                               side="left",
                               padx=10,
                               ipadx=3,
                               ipady=3)
        self.progress_bar["value"] = 0

        self.progress_bar_style.configure("progress_bar",
                                          background="deepskyblue",
                                          font=('Helvetica', 8),
                                          pbarrelief="flat",
                                          troughrelief="flat",
                                          troughcolor="ghostwhite")
        self.update_progress_label("Press Start to Launch Automation")
예제 #29
0
파일: tk_appwindow.py 프로젝트: plewto/Llia
 def _init_status_panel(self):
     south = self._main.south
     south.configure(padx=4, pady=4)
     self._lab_status = factory.label(south, "", modal=False)
     b_panic = factory.panic_button(south)
     b_down = factory.button(south, "-")
     b_up = factory.button(south, "+")
     b_panic.grid(row=0, column=0)
     self._progressbar = Progressbar(south,mode="indeterminate")
     self._progressbar.grid(row=0,column=PROGRESSBAR_COLUMN, sticky='w', padx=8)
     self._lab_status.grid(row=0,column=4, sticky='w')
     south.config(background=factory.bg())
     b_down.configure(command=lambda: self.root.lower())
     b_up.configure(command=lambda: self.root.lift())
     self.update_progressbar(100, 0)
예제 #30
0
    def __init__(self, master, _ndpi_file):
        self.master = master

        # For WBC-hunt
        self.hunter = False

        # Call the super constructor
        Canvas.__init__(self, master)
        #self.canvas = Canvas(self, master)

        # Zoom or roi mode (defaults to roi)
        self.mode = "roi"

        # Setup the input file
        self.ndpi_file = _ndpi_file
        self.im = None              # Actual PhotoImage object of the image
        self.rgba_im = None         # This is needed as a kept reference so that we can resize image on user action

        self.current_level = None   # Scale space level currently used for viewing (for handling zoom etc)

        self.image_handle = None    # Used to delete and recreate images
        self.setup_image()



        # Stuff for box selection
        self.init_box_pos = None            # In WINDOW coordinates
        self.curr_box_bbox = None           # Also in current WINDOW coordinates
        self.last_selection_region = None   # This is in level 0 coordinates
        self.zoom_level = 0     # How many times have we zoomed?
        self.zoom_region = []   # Stack of regions in level 0 coords that tells us where the zoom is, needed for transforming

        # Since we want multiple ROIs, save them in this list
        self.roi_list = []      # Contains Triple: (ROInumber, ROI_imagedata, (bbox, [sub_rois_list]))
        self.roi_counter = 0
        self.progress = Progressbar(self, orient="horizontal", length=100, mode="determinate", value=0)
        # ProgressBar to show user what is going on. Only one active at a time

        # Bind some event happenings to appropriate methods
        self.bind('<Configure>', self.resize_image)
        self.bind('<B1-Motion>', self.select_box)
        self.bind('<Button-1>', self.set_init_box_pos)
        self.bind('<ButtonRelease-1>', self.set_box)
        self.bind('<Button-3>', self.zoom_out)
        self.bind('<Left>', self.move_up)

        # DEBUG
        self.counter = 0
예제 #31
0
    def __init__(self, parent=None, **kwargs):
        Frame.__init__(self, parent)
        self.parent = parent
        self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL)
        self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll)
        self.job_list_xscroll['command'] = self.job_list.xview
        self.job_list_yscroll['command'] = self.job_list.yview
        self.new_job_frame = Frame(self)
        add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None
        if add_icon_filename == None:
            self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add)
        else:
            add_icon = PhotoImage(file=add_icon_filename)
            self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add)
        self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove)
        self.progress_frame = Frame(self)
        self.progress_value = Tkinter.IntVar()
        self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value)
        self.button_frame = Frame(self)
        self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs)
        self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows)

        self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None

        self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None

        self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None

        self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs)
        self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs)
        self.bind('<<CreatePlotGUI>>', self.create_plot_gui)
        self.parent.bind('<ButtonPress>', self.on_press)
        self.parent.bind('<Configure>', self.on_resize)

        self.reinit_variables()

        self.top_level_windows = list()

        # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized,
        # the resize option will be disabled for this window
        self.parent.resizable(width=False, height=False)

        self.lift()
예제 #32
0
파일: main.py 프로젝트: offtirael/MuBlas
 def __init__(self):
     
     root.title("MuBlas")
     
     self.lab1 = Label(root, text="Music directory")
     self.lab1.grid(row = 0, column = 0)
     
     self.music_entry = Entry(root,width=50,bd=1)
     self.music_entry.grid(row = 1, column = 0)
     
     self.m_dir_but = Button(root)
     self.m_dir_but["text"] = "Choose directory"
     self.m_dir_but.grid(row = 1, column = 1)
     self.m_dir_but.bind("<Button-1>", self.ask_mus_dir)
     
     self.lab3 = Label(root, text="Size in MBytes")
     self.lab3.grid(row = 2, column = 0)
     
     self.size_entry = Entry(root,width=5,bd=1)
     self.size_entry.grid(row = 2, column = 1)
     
     self.lab2 = Label(root, text="Destination directory")
     self.lab2.grid(row = 3, column = 0)
     
     self.destination_entry = Entry(root,width=50,bd=1)
     self.destination_entry.grid(row = 4, column = 0)
     
     self.dest_dir_but = Button(root)
     self.dest_dir_but["text"] = "Choose directory"
     self.dest_dir_but.grid(row = 4, column = 1)
     self.dest_dir_but.bind("<Button-1>", self.ask_out_dir)
     
     self.process_but = Button(root)
     self.process_but["text"] = "Run"
     self.process_but.grid(row = 6, column = 0)
     self.process_but.bind("<Button-1>", self.start)
     
     self.exit_but = Button(root)
     self.exit_but["text"] = "Exit"
     self.exit_but.grid(row = 6, column = 1)
     self.exit_but.bind("<Button-1>", self.exit_app)
     
     self.pr_bar = Progressbar(root, mode='indeterminate')
     self.pr_bar.grid(row = 5, column = 0, sticky = "we", columnspan = 2)
예제 #33
0
class App(Tk):

    def __init__(self):
        Tk.__init__(self)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.progress_bar = None
        self.prog_win = None

        self.working_folder = None

        self.main_container = Frame(
            self,
            highlightbackground="black",
            highlightcolor="black",
            highlightthickness=1
        )
        self.frames = {}

        self.main_container.grid(row=0, column=0, sticky="nsew")
        self.main_container.grid_rowconfigure(0, weight=1)
        self.main_container.grid_columnconfigure(0, weight=1)

        for F in (Steps, DTType, UploadMul, AnnotateMul, PreDataMul, TrainingMul, Upload, Annotate, SingleDetection, SingleTracking, Mul_Object_Detection, References):
            frame = F(self.main_container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(Steps)

    def show_frame(self, frame):
        self.frames[frame].tkraise()
        self.frames[frame].event_generate("<<ShowFrame>>")

    def show_progress(self, start):
        if start:
            self.prog_win = Toplevel(self.main_container, padx=8, pady=8)
            self.prog_win.transient(self)
            self.prog_win.title('Working...')
            self.prog_win.resizable(0, 0)
            self.progress_bar = Progressbar(self.prog_win,
                                            orient=HORIZONTAL,
                                            mode='indeterminate',
                                            length=250,
                                            takefocus=True)
            self.progress_bar.grid()
            self.progress_bar.start()
        else:
            self.progress_bar.stop()
            self.prog_win.destroy()
예제 #34
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")
예제 #35
0
class MPExportApp(object):
    """docstring for MPExportApp"""
    def __init__(self, master):
        super(MPExportApp, self).__init__()
        self.master = master
        self.export_type = StringVar()

        master.columnconfigure(1, weight=1)

        export_type_label = Label(master, text="Data Type: ")
        export_type_label.grid(row=0, column=0, sticky=E)

        radio_group_frame = Frame(master)
        radio_group_frame.grid(row=0, column=1, sticky=W)

        self.events_radio_button = Radiobutton(radio_group_frame, text='Events', value='events', variable=self.export_type,
                                               command=self.radio_button_changed)

        self.events_radio_button.select()
        self.events_radio_button.grid(row=0, column=0)

        self.people_radio_button = Radiobutton(radio_group_frame, text='People', value='people', variable=self.export_type,
                                               command=self.radio_button_changed)
        self.people_radio_button.grid(row=0, column=1)

        api_key_label = Label(master, text="API Key: ")
        api_key_label.grid(row=1, column=0, sticky=E)

        self.api_key_entry = Entry(master)
        self.api_key_entry.grid(row=1, column=1, columnspan=2, sticky=(E,W))

        api_secret_label = Label(master, text="API Secret: ")
        api_secret_label.grid(row=2, column=0, sticky=E)

        self.api_secret_entry = Entry(master)
        self.api_secret_entry.grid(row=2, column=1, columnspan=2, sticky=(E, W))

        self.project_token_label = Label(master, text="Project Token: ", state=DISABLED)
        self.project_token_label.grid(row=3, column=0, sticky=E)

        self.project_token_entry = Entry(master, state=DISABLED)
        self.project_token_entry.grid(row=3, column=1, columnspan=2, sticky=(E, W))

        self.events_label = Label(master, text="Events: ")
        self.events_label.grid(row=4, column=0, sticky=E)

        self.events_entry = Entry(master)
        self.events_entry.insert(0, 'Event A,Event B,Event C')
        self.events_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.events_entry))
        self.events_entry.grid(row=4, column=1, columnspan=2, sticky=(E, W))

        where_label = Label(master, text="Where: ")
        where_label.grid(row=5, column=0, sticky=E)
        self.where_entry = Entry(master)
        self.where_entry.grid(row=5, column=1, columnspan=2, sticky=(E, W))

        self.from_date_label = Label(master, text="From Date: ")
        self.from_date_label.grid(row=6, column=0, sticky=E)

        self.from_date_entry = Entry(master)
        self.from_date_entry.insert(0, 'YYYY-MM-DD')
        self.from_date_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.from_date_entry))
        self.from_date_entry.grid(row=6, column=1, columnspan=2, sticky=(E, W))

        self.to_date_label = Label(master, text="To Date: ")
        self.to_date_label.grid(row=7, column=0, sticky=E)

        self.to_date_entry = Entry(master)
        self.to_date_entry.insert(0, 'YYYY-MM-DD')
        self.to_date_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.to_date_entry))
        self.to_date_entry.grid(row=7, column=1, columnspan=2, sticky=(E, W))

        export_button = Button(master, text="EXPORT", fg="green", command=self.export)
        export_button.grid(row=8, column=1, sticky=(E, W))

        self.delete_button = Button(master, text="DELETE", fg='red', state=DISABLED,
                                    command=lambda: threading.Thread(target=self.delete_people).start())
        self.delete_button.grid(row=9, column=1, sticky=(E, W))

        self.progress_bar = Progressbar(master)
        self.progress_bar_value = IntVar()
        self.progress_bar.config(mode='determinate', orient='horizontal', variable=self.progress_bar_value)
        self.progress_bar.grid(row=10, column=0, columnspan=3, sticky=(E, W))


    def clear_placeholder_text(self, entry, event):
        entry_text = entry.get()
        if entry_text == 'Event A,Event B,Event C' or entry_text == 'YYYY-MM-DD':
            entry.delete(0, END)

    def make_events_string(self, events):
        events = events.replace(', ', ',')
        events = events.split(',')
        events_string = '['
        for x in range(0, len(events)):
            events_string += '"' + events[x] + '"'
            if x != len(events)-1:
                events_string += ','
            else:
                events_string += ']'
        return events_string

    def radio_button_changed(self):
        if self.export_type.get() == 'people':
            self.project_token_label.config(state=NORMAL)
            self.project_token_entry.config(state=NORMAL)
            self.events_label.config(state=DISABLED)
            self.events_entry.config(state=DISABLED)
            self.from_date_label.config(state=DISABLED)
            self.from_date_entry.config(state=DISABLED)
            self.to_date_label.config(state=DISABLED)
            self.to_date_entry.config(state=DISABLED)
            self.delete_button.config(state=NORMAL)
        elif self.export_type.get() == 'events':
            self.project_token_label.config(state=DISABLED)
            self.project_token_entry.config(state=DISABLED)
            self.events_label.config(state=NORMAL)
            self.events_entry.config(state=NORMAL)
            self.from_date_label.config(state=NORMAL)
            self.from_date_entry.config(state=NORMAL)
            self.to_date_label.config(state=NORMAL)
            self.to_date_entry.config(state=NORMAL)
            self.delete_button.config(state=DISABLED)

    def export(self):
        if self.api_key_entry.get() == '':
            print 'API Key Required!'
            return
        elif self.api_secret_entry.get() == '':
            print 'API Secret Required!'
            return

        self.output_dir = askdirectory(title='Choose output directory', mustexist=True, parent=self.master)
        if not self.output_dir:
            return
        print 'Output directory is ' + self.output_dir

        self.progress_bar.start()
        if self.export_type.get() == 'people':
            self.export_thread = threading.Thread(target=self.export_people)
        elif self.export_type.get() == 'events':
            self.export_thread = threading.Thread(target=self.export_events)

        self.export_thread.start()

    def export_people(self):

        mixpanel = Mixpanel(
            api_key=self.api_key_entry.get(),
            api_secret=self.api_secret_entry.get(),
            endpoint=API_ENDPOINT
            )

        '''Here is the place to define your selector to target only the users that you're after'''
        '''parameters = {'selector':'(properties["$email"] == "Albany") or (properties["$city"] == "Alexandria")'}'''
        selector = self.where_entry.get()

        parameters = {}

        if selector:
            parameters['selector'] = selector

        response = mixpanel.request(['engage'], parameters)

        try:
            result = '\nAPI ERROR! - ' + json.loads(response)['error'] + '\n'
            if result:
                print result
                self.progress_bar.stop()
                self.progress_bar_value.set(0)
                return
        except KeyError, e:
            pass

        parameters['session_id'] = json.loads(response)['session_id']
        parameters['page'] = 0
        global_total = json.loads(response)['total']
        if global_total == 0:
            print 'Query returned 0 profiles!'
            self.progress_bar.stop()
            self.progress_bar_value.set(0)
            return

        print "Session id is %s \n" % parameters['session_id']
        print "Here are the # of people %d" % global_total
        filename = self.output_dir + "/people_export_"+str(int(time.time()))
        jsonfile = filename + ".json"
        csvfile = filename + ".csv"
        has_results = True
        total = 0
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            with open(jsonfile, 'w') as j:
                j.write('[')
                while has_results:
                    responser = json.loads(response)['results']
                    response_count = len(responser)
                    total += response_count
                    has_results = response_count == 1000
                    i = 0
                    for data in responser:
                        dump = json.dumps(data)
                        temp.write(dump + '\n')
                        j.write(dump)
                        i += 1
                        if i != response_count:
                            j.write(',')

                    print "%d / %d" % (total,global_total)
                    parameters['page'] += 1
                    if has_results:
                        j.write(',')
                        response = mixpanel.request(['engage'], parameters)
                    else:
                        j.write(']')

                print 'JSON saved to ' + j.name
                j.close()

        mixpanel.people_json_to_csv(csvfile, temp.name)
        temp.close()
        os.remove(temp.name)
        self.progress_bar.stop()
        self.progress_bar_value.set(0)
예제 #36
0
class ScreenShooterGui(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title("WebSite ScreenShooter")
        self.geometry("390x420")

        self.mainFrame = Frame(self)
        self.mainFrame.pack(pady=5, padx=5)

        self.urlLabelFrame = Frame(self.mainFrame)
        self.urlLabelFrame.pack(pady=5, side=TOP, fill=X)
        self.urlImportLabel = Label(self.urlLabelFrame, text="web URLs:")
        self.urlImportLabel.pack(side=LEFT, padx=5)

        self.importTextFrame = Frame(self.mainFrame)
        self.importTextFrame.pack(pady=5, side=TOP, fill=X)
        self.yTextScrollbar = Scrollbar(self.importTextFrame)
        self.yTextScrollbar.pack(side=RIGHT, fill=Y)
        self.xTextScrollbar = Scrollbar(self.importTextFrame,
                                        orient=HORIZONTAL)
        self.xTextScrollbar.pack(side=BOTTOM, fill=X)
        self.importUrlsText = Text(self.importTextFrame,
                                   padx=5,
                                   pady=5,
                                   wrap=NONE,
                                   width=50,
                                   height=10,
                                   yscrollcommand=self.yTextScrollbar.set,
                                   xscrollcommand=self.xTextScrollbar.set)
        self.importUrlsText.pack(side=TOP, padx=5, pady=5, fill=X)
        self.yTextScrollbar.config(command=self.importUrlsText.yview)
        self.xTextScrollbar.config(command=self.importUrlsText.xview)

        self.outputLabelFrame = Frame(self.mainFrame)
        self.outputLabelFrame.pack(pady=5, side=TOP, fill=X)
        self.outputFileLabel = Label(self.outputLabelFrame,
                                     text="Path to the output folder:")
        self.outputFileLabel.pack(side=LEFT, padx=5)

        self.outputFieldFrame = Frame(self.mainFrame)
        self.outputFieldFrame.pack(pady=5, side=TOP, fill=X)
        self.outputFieldEntry = Entry(self.outputFieldFrame,
                                      name="outputFile",
                                      width=30)
        self.outputFieldEntry.pack(side=LEFT, padx=5)
        self.btnBrowse = Button(self.outputFieldFrame,
                                height=1,
                                width=6,
                                text="Browse...",
                                command=self.browse)
        self.btnBrowse.pack(side=RIGHT, padx=5)

        self.controlsFrame = Frame(self.mainFrame)
        self.controlsFrame.pack(pady=5, side=TOP, fill=X)
        self.btnClose = Button(self.controlsFrame,
                               height=1,
                               width=6,
                               text="Close",
                               command=self.close)
        self.btnClose.pack(side=LEFT, padx=5)
        self.btnRun = Button(self.controlsFrame,
                             height=1,
                             width=6,
                             text="Run",
                             command=self.run)
        self.btnRun.pack(side=RIGHT, padx=5)

        # *** PROGRESS BAR ***
        self.status = Progressbar(self.mainFrame,
                                  orient='horizontal',
                                  length=310,
                                  mode='determinate',
                                  value=0,
                                  maximum=100)
        self.status.pack(pady=5, padx=5, side=BOTTOM)

    def browse(self):
        outputPath = tkFileDialog.askdirectory(parent=self)
        self.outputFieldEntry.delete(0, last=END)
        self.outputFieldEntry.insert(0, outputPath)

    def close(self):
        self.destroy()

    def run(self):
        textUrls = self.importUrlsText.get('1.0', 'end')
        # creating a list ignoring empty values
        listOfUrls = [x for x in textUrls.split("\n") if x]
        stepAmount = 100 / len(listOfUrls)
        for i, url in enumerate(listOfUrls):
            url = url.strip()
            # dirty solution to find ebay items ids
            item_ids = re.findall(r'\/[1-4]\d{11,12}', url, re.I)
            if len(item_ids) > 0:
                output = '{root_path}/{url_base}_eBayItem-{item}.png'.format(
                    root_path=self.outputFieldEntry.get(),
                    url_base=url.split("/")[2],
                    item=str(item_ids[0][1:]))
            else:
                output = '{root_path}/{url_base}.png'.format(
                    root_path=self.outputFieldEntry.get(),
                    url_base=url.split("/")[2])

            # check if file already exists:
            if os.path.isfile(output):
                file_ver = '-({ver}).png'.format(ver=i)
                output = re.sub(r'\.png$', file_ver, output)

            screenshot(url, output)
            add_url_time(url, output)
            self.status.step(stepAmount)
            self.update()

    def mainloop(self):
        Tk.mainloop(self)
예제 #37
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        
    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")

     
    # Clear what is in the text box.   
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []
        
    # On click methods for scan me and scan others.
    def onClick(self, button_id):
        
        if button_id == 1:
            
            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground = "blue")    
                
            # Check to see if ports button is marked   
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()                
                        message, total = scan_my_ports(int(starting_port), int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")
                    
                    time = "The TCP port scan completed in: " + str(total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")
                
            # Check to see if IP button is marked     
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)
            
            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0. new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        # If Scan other button is clicked. 
        elif button_id == 2:
            
            # Check other IP's 
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()
                        
                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address, ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(i,"is UP\n")
                                self.area.insert(0.0, new_message)
                        
                        total_time =  "Range scanned: " + str(starting_ipv4_address) +" to " + str(ending_ipv4_address) + "\n" + "The IP scan completed in:  " + str(time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground = "red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")
                
                
            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        
                        
                        message, time = scan_ports_other(int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i +"\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"
                    
                    total_time = "TCP Port scan completed in: " + str(time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                    
                else:
                    self.area.insert(0.0, "No Port range specified.")
            
            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected 
                if message:
                    for i in message:
                        new_message = "Host name: "+ str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)
                    
                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)
                    
                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)
                    
                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        else:
            pass
예제 #38
0
# Initial attempt at a display of random numbers over time on a pi
from Tkinter import *
from ttk import Progressbar
from ttk import Style
import random
import time

window = Tk()
text = StringVar()
text.set('loading...')
status = IntVar()
window.configure(background='black')
window.wm_attributes('-type', 'splash')
window.geometry('350x200')
def changeText():
    randomNum = random.randrange(1,15, 1)
    text.set(randomNum)
    progress['value'] = randomNum * .15 * 100
    window.after(100, changeText)

lbl = Label(window, compound=CENTER, textvariable=text, bg="black", fg="orange", font=("Arial Bold", 50))
lbl.place(x=175, y=100, anchor="center")
style = Style()
style.theme_use('default')
style.configure("orange.Horizontal.TProgressbar", troughcolor='black', foreground='orange', background='orange', troughrelief="flat" )
progress=Progressbar(window, orient=HORIZONTAL, style='orange.Horizontal.TProgressbar', length=200, mode='determinate')
progress.pack()
window.after(100, changeText)
window.mainloop()
예제 #39
0
파일: tk_appwindow.py 프로젝트: plewto/Llia
class TkApplicationWindow(AbstractApplicationWindow):

    def __init__(self, app):
        self.root = Tk()
        self.root.title("Llia")
        self.root.config(background=factory.bg())
        super(TkApplicationWindow, self).__init__(app, self.root)
        self.root.withdraw()
        if app.config()["enable-splash"]:
            splash = TkSplashWindow(self.root, app)
        self.root.deiconify()
        self.root.protocol("WM_DELETE_WINDOW", self.exit_app)
        self.llia_graph = None
        self._main = layout.BorderFrame(self.root)
        self._main.config(background=factory.bg())
        self._main.pack(anchor="nw", expand=True, fill=BOTH)
        self._progressbar = None
        self._init_status_panel()
        self._init_menu()
        self._init_center_frame(self._main.center)
        self.root.minsize(width=665, height=375)
        self.group_windows = []
        self.add_synth_group()
        self._scene_filename = ""
        
    def _init_status_panel(self):
        south = self._main.south
        south.configure(padx=4, pady=4)
        self._lab_status = factory.label(south, "", modal=False)
        b_panic = factory.panic_button(south)
        b_down = factory.button(south, "-")
        b_up = factory.button(south, "+")
        b_panic.grid(row=0, column=0)
        self._progressbar = Progressbar(south,mode="indeterminate")
        self._progressbar.grid(row=0,column=PROGRESSBAR_COLUMN, sticky='w', padx=8)
        self._lab_status.grid(row=0,column=4, sticky='w')
        south.config(background=factory.bg())
        b_down.configure(command=lambda: self.root.lower())
        b_up.configure(command=lambda: self.root.lift())
        self.update_progressbar(100, 0)
        
    def _tab_change_callback(self, event):
        self.llia_graph.sync()
    
    def _init_center_frame(self, master):
        nb = ttk.Notebook(master)
        nb.pack(expand=True, fill="both")
        frame_synths = layout.FlowGrid(nb, 6)
        frame_efx = layout.FlowGrid(nb, 6)
        frame_controllers = layout.FlowGrid(nb, 6)
        self.llia_graph = LliaGraph(nb, self.app)
        nb.add(frame_synths, text = "Synths")
        nb.add(frame_efx, text = "Effects")
        nb.add(frame_controllers, text = "Controllers")
        nb.add(self.llia_graph, text="Graph")
        nb.bind("<Button-1>", self._tab_change_callback)

        def display_info_callback(event):
            sp = event.widget.synth_spec
            msg = "%s:    %s" % (sp["format"],sp["description"])
            self.status(msg)

        def clear_info_callback(*_):
            self.status("")
        
        for st in con.SYNTH_TYPES:
            sp = specs[st]
            ttp = "Add %s Synthesizer (%s)" % (st, sp["description"])
            b = factory.logo_button(frame_synths, st, ttip=ttp)
            b.synth_spec = sp
            b.bind("<Button-1>", self._show_add_synth_dialog)
            b.bind("<Enter>", display_info_callback)
            b.bind("<Leave>", clear_info_callback)
            frame_synths.add(b)
        for st in con.EFFECT_TYPES:
            sp = specs[st]
            ttp = "Add %s Effect (%s)" % (st, sp["description"])
            b = factory.logo_button(frame_efx, st, ttip=ttp)
            b.synth_spec = sp
            b.bind("<Button-1>", self._show_add_efx_dialog)
            b.bind("<Enter>", display_info_callback)
            b.bind("<Leave>", clear_info_callback)
            frame_efx.add(b)
        for st in con.CONTROLLER_SYNTH_TYPES:
            sp = specs[st]
            ttp = "Add %s Effect (%s)" % (st, sp["description"])
            b = factory.logo_button(frame_controllers, st, ttip=ttp)
            b.synth_spec = sp
            b.bind("<Button-1>", self._show_add_controller_dialog)
            b.bind("<Enter>", display_info_callback)
            b.bind("<Leave>", clear_info_callback)
            frame_controllers.add(b)
    
    @staticmethod
    def menu(master):
        m = Menu(master, tearoff=0)
        m.config(background=factory.bg(), foreground=factory.fg())
        return m
    
    def _init_menu(self):
        main_menu = self.menu(self.root)
        self.root.config(menu=main_menu)
        file_menu = self.menu(main_menu)
        osc_menu = self.menu(main_menu)
        midi_menu = self.menu(main_menu)
        bus_menu = self.menu(main_menu)
        #buffer_menu = self.menu(main_menu)
        tune_menu = self.menu(main_menu)
        help_menu = self.menu(main_menu)
        main_menu.add_cascade(label="File", menu=file_menu)
        main_menu.add_cascade(label="OSC", menu=osc_menu)
        main_menu.add_cascade(label="MIDI", menu=midi_menu)
        #main_menu.add_cascade(label="Buses", menu=bus_menu)
        #main_menu.add_cascade(label="Buffers", menu=buffer_menu)
        #main_menu.add_cascade(label="Tune", menu=tune_menu)
        #main_menu.add_cascade(label="Help", menu=help_menu)
        self._init_file_menu(file_menu)
        self._init_osc_menu(osc_menu)
        self._init_midi_menu(midi_menu)
        self._init_bus_menu(bus_menu)
        #self._init_buffer_menu(buffer_menu)
        self._init_tune_menu(tune_menu)
        self._init_help_menu(help_menu)

    def _init_file_menu(self, fmenu):
        fmenu.add_command(label="Save Scene", command = self.save_scene)
        fmenu.add_command(label="Load Scene", command = self.load_scene)
        fmenu.add_separator()
        fmenu.add_command(label="Lliascript (Legacy)", command = self.show_history_editor)
        fmenu.add_separator()
        fmenu.add_command(label="New Synth Group", command = self._add_synth_group)
        fmenu.add_separator()
        fmenu.add_command(label="Restart", command = self._interactive_tabula_rasa)
        fmenu.add_command(label="Quit", command = self.exit_app)

    def _init_osc_menu(self, iomenu):
        iomenu.add_command(label="Ping", command = self.ping_global)
        iomenu.add_command(label="Dump", command = self.app.proxy.dump)
        iomenu.add_command(label="Toggle OSC Trace", command = self.toggle_osc_trace)

    def _init_midi_menu(self, mmenu):
        map_menu = self.menu(mmenu)
        mmenu.add_command(label = "Channel Names", command = self.show_channel_name_dialog)
        mmenu.add_command(label = "Controller Names", command = self.show_controller_name_dialog)
        mmenu.add_cascade(label = "MIDI Maps", menu = map_menu)
        mmenu.add_command(label = "Toggle MIDI Input Trace", command = self.toggle_midi_input_trace)
        mmenu.add_command(label = "Toggle MIDI Output Trace", command = self.toggle_midi_output_trace)
        mmenu.add_command(label = "Toggle Program Pretty Printer", command = self.toggle_program_pretty_printer)
        
    def _init_bus_menu(self, bmenu):
        bmenu.add_command(label="Audio", command=self.show_audiobus_dialog)
        bmenu.add_command(label="Control", command=self.show_controlbus_dialog)
        
    # def _init_buffer_menu(self, bmenu):
    #     bmenu.add_command(label="View Buffers", command=self.show_bufferlist_dialog)

    def _init_tune_menu(self, tmenu):
        tmenu.add_command(label = "FIX ME: Nothing to see here")

    def _init_help_menu(self, hmenu):
        pass
        
    def exit_gui(self):
        try:
            self.root.destroy()
        except:
            pass

    def confirm_exit(self):
        return tkMessageBox.askyesno("Exit Llia", "Exit Llia?")
        
    def exit_app(self):
        self.app.exit_()

    def as_widget(self):
        return self.root
        
    def status(self, msg):
        self._lab_status.config(text=str(msg))

    def warning(self, msg):
        msg = "WARNING: %s" % msg
        self._lab_status.config(text=msg)
        
    def clear_status(self):
        self.status("")
                                              
    def start_gui_loop(self):
        self.root.mainloop()

    def show_about_dialog(self):
        from llia.gui.tk.tk_about_dialog import TkAboutDialog
        dialog = TkAboutDialog(self.root, self.app)
        self.root.wait_window(dialog)

    def display_help(self, topic=None):
        pass
        
    def show_history_editor(self):
        from llia.gui.tk.tk_history import TkHistoryEditor
        dialog = TkHistoryEditor(self.root, self.app)
        self.root.wait_window(dialog)

    def ping_global(self):
        try:
            rs = self.app.proxy.ping()
            if rs:
                self.status("Ping OK")
            else:
                self.warning("Ping Error")
        except LliaPingError as err:
            self.warning(err.message)

    def toggle_osc_trace(self):
        LliaProxy.trace = not LliaProxy.trace
        if LliaProxy.trace:
            self.status("OSC transmission trace enabled")
        else:
            self.status("OSC transmission trace disabled")

    def show_channel_name_dialog(self):
        from llia.gui.tk.tk_channel_name_editor import TkChannelNameEditor
        dialog = TkChannelNameEditor(self.root, self.app)
        self.root.wait_window(dialog)
  
    def show_controller_name_dialog(self):
        from llia.gui.tk.tk_controller_name_editor import TkControllerNameEditor
        dialog = TkControllerNameEditor(self.root, self.app)
        self.root.wait_window(dialog)
    
    def toggle_midi_input_trace(self):
        flag = not self.app.midi_in_trace
        self.app.midi_in_trace = flag
        self.app.midi_receiver.enable_trace(flag)
        if flag:
            self.status("MIDI input trace enabled")
        else:
            self.status("MIDI output trace disabled")

    def toggle_midi_output_trace(self):
        self.status("MIDI output not available") # FIX ME

    def toggle_program_pretty_printer(self):
        self.app.pp_enabled = not self.app.pp_enabled
        if self.app.pp_enabled:
            self.status("Pretty printer enabled")
        else:
            self.status("Pretty printer disabled")
        
    def show_audiobus_dialog(self):
        from llia.gui.tk.tk_audiobus_editor import TkAudiobusEditor
        dialog = TkAudiobusEditor(self.root, self.app)
        self.root.wait_window(dialog)

    def show_controlbus_dialog(self):
        from llia.gui.tk.tk_controlbus_editor import TkControlbusEditor
        dialog = TkControlbusEditor(self.root, self.app)
        self.root.wait_window(dialog)

    # def show_bufferlist_dialog(self):
    #     from llia.gui.tk.tk_buffer_info import TkBufferListDialog
    #     dialog = TkBufferListDialog(self.root, self.app)
    #     self.root.wait_window(dialog)

    def _show_add_synth_dialog(self, event):
        w = event.widget
        st = w.config()["text"][-1]
        dialog = TkAddSynthDialog(self.root, self.app, st, False)
        self.root.wait_window(dialog)
        
    def _show_add_efx_dialog(self, event):
        w = event.widget
        st = w.config()["text"][-1]
        dialog = TkAddSynthDialog(self.root, self.app, st, is_efx=True, is_controller=False)
        self.root.wait_window(dialog)

    def _show_add_controller_dialog(self, event):
        w = event.widget
        st = w.config()["text"][-1]
        dialog = TkAddSynthDialog(self.root, self.app, st, is_efx=False, is_controller=True)
        self.root.wait_window(dialog)
        
    def _add_synth_group(self):
        sh = self.app.ls_parser.synthhelper
        sh.new_group()
        
    def add_synth_group(self, name=None):
        gw = GroupWindow(self.app, self.root, name)
        # gw.transient(self.root)  # If executed keeps main app window behind all other windows.
        self.group_windows.append(gw)
        self.status("Added new Synth Group Window")
        return gw

    def display_synth_editor(self, sid):
        try:
            swin = self[sid]
            grpid = swin.group_index
            grp = self.group_windows[grpid]
            #grp.deiconify()
            grp.show_synth_editor(sid)
        except (KeyError, IndexError):
            msg = "Can not find editor for %s" % sid
            self.warning(msg)

    def update_progressbar(self, count, value):
        self._progressbar.config(mode="determinate", maximum=count)
        self._progressbar.step()
        self.root.update_idletasks()
            
    def busy(self, flag, message=""):
        if message:
            self.status(message)
        self._progressbar.config(mode="indeterminate")
        if flag:
            self._progressbar.grid(row=0, column=PROGRESSBAR_COLUMN, sticky='w', padx=8)
            self._progressbar.start()
        else:
            self._progressbar.stop()
            # self._progressbar.grid_remove()
        self.root.update_idletasks()

    def save_scene(self, *_):
        options = {'defaultextension' : '.llia',
                   'filetypes' : [('Llia Scenes', '*.llia'),
                                  ('all files', '*')],
                   'initialfile' : self._scene_filename,
                   'parent' : self.root,
                   'title' : "Save Llia Scene"}
        filename = tkFileDialog.asksaveasfilename(**options)
        if filename:
            try:
                self.app.ls_parser.save_scene(filename)
                self._scene_filename = filename
                self.status("Scene saved as '%s'" % filename)
            except Exception as ex:
                self.warning(ex.message)
        else:
            self.status("Scene save canceld")    

    def load_scene(self, *_):
        options = {'defaultextension' : '.llia',
                   'filetypes' : [('Llia Scenes', '*.llia'),
                                  ('all files', '*')],
                   'initialfile' : self._scene_filename,
                   'parent' : self.root,
                   'title' : "Load Llia Scene"}
        filename = tkFileDialog.askopenfilename(**options)
        if filename:
            try:
                self.app.ls_parser.load_scene(filename)
                self.status("Scene '%s' loaded" % filename)
                self._scene_filename = filename
            except Exception as ex:
                self.warning(ex.message)
        else:
            self.status("Load scene canceld")
            
    def tabula_rasa(self):
        for grp in self.group_windows:
            grp.tabula_rasa()
        self.group_windows = []

    def _interactive_tabula_rasa(self, *_):
        # ISSUE: Check config and ask user confirmation before existing
        self.app.ls_parser.tabula_rasa()
예제 #40
0
class FdaAltimeterControl(tk.Toplevel):

    PORT_SELECTION_FRAME_HEIGHT = 80
    SUB_FRAME_X_PADDING = 20

    def __init__(self, parent):
        tk.Toplevel.__init__(self)
        self.parent = parent

        # Do not let user to close this window
        # is a communication with the Altimeter
        # is taking place.
        self.communicating = False
        self.protocol("WM_DELETE_WINDOW", self.close_asked)

        # Setup window content.
        self.initialize()

    def initialize(self):
        self.title(_(u'FlyDream Altimeter - Device Controller'))

        # Set fixed size.
        self.minsize(640, 320)
        self.resizable(False, False)

        # Altimeter local device.
        frame = tk.Frame(self, height=self.PORT_SELECTION_FRAME_HEIGHT)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        tk.Label(frame, text=_(u'Altimeter plugged on:')).pack(side=tk.LEFT)

        self.detect = tk.Button(frame, text=_(u'Refresh'),
                command=self.refresh_serial_ports)
        self.detect.pack(side=tk.RIGHT)

        self.port = tk.StringVar(self)
        self.ports = tk.OptionMenu(frame, self.port,
                _(u'Detecting serial ports...'))
        self.ports.pack(fill=tk.X, expand=tk.YES)

        # Update possible serial ports.
        self.refresh_serial_ports()

        # Upload altimeter flight data.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Upload'))
        label.pack(side=tk.TOP, fill=tk.X)

        # Setup bold font for titles.
        f = Font(font=label['font'])
        f['weight'] = 'bold'
        label['font'] = f.name

        Separator(frame).pack(fill=tk.X)

        self.progressbar = Progressbar(frame, orient='horizontal',
                mode='determinate')
        self.progressbar.pack(side=tk.BOTTOM, fill=tk.X)

        # Do not show progressbar
        # unless data is uploaded.
        self.hide_progressbar()

        self.upload_info = tk.StringVar()
        self.upload_info.set('/')
        self.info_label = tk.Label(frame, anchor=tk.NE, fg='darkgrey',
                textvariable=self.upload_info)
        self.info_label.pack(side=tk.BOTTOM, fill=tk.BOTH)

        self.label = tk.Label(frame, anchor=tk.W,
                text=_(u'Tell the altimeter to send flight '
                    'data to your computer'))
        self.label.pack(side=tk.LEFT)

        self.upload = tk.Button(frame, text=_(u'Upload data'),
                command=self.upload)
        self.upload.pack(side=tk.RIGHT)

        # Erase altimeter flight data.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Clear'))
        label['font'] = f.name
        label.pack(side=tk.TOP, fill=tk.X)

        Separator(frame).pack(fill=tk.X)

        label = tk.Label(frame, anchor=tk.W,
                text=_(u'Delete all the flight data from your altimeter'))
        label.pack(side=tk.LEFT)

        self.erase = tk.Button(frame, text=_(u'Erase data'),
                command=self.erase)
        self.erase.pack(side=tk.RIGHT)

        # Setup altimeter sampling frequency.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Configure'))
        label['font'] = f.name
        label.pack(side=tk.TOP, fill=tk.X)

        Separator(frame).pack(fill=tk.X)

        self.frequency = tk.StringVar(self)
        self.frequency.set('1')
        self.frequencies = tk.OptionMenu(frame, self.frequency,
                '1', '2', '4', '8')
        self.frequencies.pack(side=tk.LEFT)

        label = tk.Label(frame, text=_(u'records per second'))
        label.pack(side=tk.LEFT)

        self.setup = tk.Button(frame, text=_(u'Set sampling frequency'),
                command=self.set_frequency)
        self.setup.pack(side=tk.RIGHT)

    def allow_user_interactions(self, allow=True):
        state = tk.NORMAL if allow else tk.DISABLED
        self.ports.configure(state=state)
        self.detect.configure(state=state)
        self.upload.configure(state=state)
        self.erase.configure(state=state)
        self.frequencies.configure(state=state)
        self.setup.configure(state=state)

    def close_asked(self):
        if not self.communicating:
            self.destroy()
            return
        else:
            showwarning(_(u'Warning'),
                    _(u"""The application is communicating with the altimeter.

Please wait until communication is finished before closing this window."""))

    def hide_progressbar(self):
        self.progressbar.prev_pack = self.progressbar.pack_info()
        self.progressbar.pack_forget()

        self.update()

        # Reset progressbar for next upload.
        self.progressbar['value'] = 0

    def show_progressbar(self):
        # Well, Tkinter pack does not seem to
        # make it easy to simply hide a widget...
        #
        # I may be missing something.
        prev_info_label_packinfo = self.info_label.pack_info()
        prev_label_packinfo = self.label.pack_info()
        prev_upload_packinfo = self.upload.pack_info()

        self.info_label.pack_forget()
        self.label.pack_forget()
        self.upload.pack_forget()

        self.progressbar.pack(self.progressbar.prev_pack)

        self.info_label.pack(prev_info_label_packinfo)
        self.label.pack(prev_label_packinfo)
        self.upload.pack(prev_upload_packinfo)

        self.update()

    def upload_progressed(self, read, total):
        self.progressbar['maximum'] = total
        self.progressbar['value'] = read

        info = _(u'Please wait, %d bytes read out of %d') % (read, total)
        self.upload_info.set(info)

        self.update()

    def default_filename(self):
        return time.strftime('%Y-%m-%d %H-%M-%S', time.localtime()) \
                + '_flight'

    def upload(self):
        # TODO Add please wait message.

        # Update window state.
        self.show_progressbar()
        self.allow_user_interactions(False)
        self.communicating = True

        # Get flight data.
        port = self.port.get()
        altimeter = Altimeter(port)
        try:
            raw_data = altimeter.upload(self.upload_progressed)
        except FlyDreamAltimeterSerialPortError:
            self.show_unfound_altimeter(port)
        except (FlyDreamAltimeterReadError, FlyDreamAltimeterWriteError) as e:
            self.show_readwrite_error(port, e.message)
        except FlyDreamAltimeterProtocolError as e:
            self.show_protocol_error(port, e.message)
        else:
            # Check received data.
            if len(raw_data.data) == 0:
                showinfo(_(u'Upload Data'),
                        _(u'Altimeter contains no data.'))
            else:
                filename = self.write_flight_data(raw_data)
                self.suggest_open_in_viewer(filename)
        finally:
            # Restore window state.
            self.communicating = False
            self.allow_user_interactions()
            self.hide_progressbar()

        # TODO Update altimeter information.
        self.upload_info.set(_(u'Done'))

    def write_flight_data(self, raw_data):
        # Let user choose a file name.
        #
        # When cancelled, None is returned.
        fname = asksaveasfilename(
                    filetypes=((_(u'Flydream Altimeter Data'), '*.fda'),
                               (_(u'All files'), '*.*')),
                    title=_(u'Save flight data...'),
                    initialdir='~',
                    initialfile=self.default_filename(),
                    defaultextension=RAW_FILE_EXTENSION)

        if fname:
            # Try to remove previous file.
            #
            # User has been warned by asksaveasfilename
            # if she picked an existing file name.
            try:
                os.remove(fname)
            except OSError as e:
                # errno.ENOENT is 'no such file or directory'.
                #
                # Raise if another kind of error occurred.
                if e.errno != errno.ENOENT:
                    raise

            # This method raises an exception if file already exists.
            raw_data.to_file(fname)

        return fname

    def suggest_open_in_viewer(self, filename):
        # User may want to see latest uploaded data.
        if filename:
            reply = askokcancel(_(u'Open in viewer'),
                _(u'Open saved flight data in file viewer?'))
            if reply:
                self.parent.load_file(filename)

    def erase(self):
        reply = askokcancel(_(u'Erase flight data'),
                _(u'Really erase all flight data in your altimeter?'))
        if reply:
            self.do_erase()

    def do_erase(self):
        # TODO Make message stay while erasing is performed.
        showwarning(_(u'Erasing...'),
                _(u'Do not disconnect USB until altimeter blue LED '
                'lights again.'))

        # Update window state.
        self.allow_user_interactions(False)
        self.communicating = True

        # Reset altimeter content.
        port = self.port.get()
        altimeter = Altimeter(port)
        try:
            altimeter.clear()
        except FlyDreamAltimeterSerialPortError:
            self.show_unfound_altimeter(port)
        except (FlyDreamAltimeterReadError, FlyDreamAltimeterWriteError) as e:
            self.show_readwrite_error(port, e.message)
        except FlyDreamAltimeterProtocolError as e:
            self.show_protocol_error(port, e.message)
        else:
            # Update altimeter information.
            self.upload_info.set(_(u'Altimeter content erased'))
        finally:
            # Restore window state.
            self.communicating = False
            self.allow_user_interactions()

    def set_frequency(self):
        # This request is almost immediate,
        # so let's not bother user with yet
        # another message box.

        # Update window state.
        self.allow_user_interactions(False)
        self.communicating = True

        # Change altimeter sampling frequency.
        freq = int(self.frequency.get())
        port = self.port.get()
        altimeter = Altimeter(port)
        try:
            altimeter.setup(freq)
        except FlyDreamAltimeterSerialPortError:
            self.show_unfound_altimeter(port)
        except (FlyDreamAltimeterReadError, FlyDreamAltimeterWriteError) as e:
            self.show_readwrite_error(port, e.message)
        except FlyDreamAltimeterProtocolError as e:
            self.show_protocol_error(port, e.message)
        else:
            # Update altimeter information.
            self.upload_info.set(_(u'Altimeter sampling frequency set'))
        finally:
            # Restore window state.
            self.communicating = False
            self.allow_user_interactions()

    def show_unfound_altimeter(self, port):
        showwarning(_(u'Sampling Frequency'),
                    _(u"""Can not open port: %s

Please ensure that:
 - your altimeter is plugged to the USB adapter.
 - the USB adapter is plugged to your computer.
 - the choosen port is correct.
 - the USB adapter driver is properly installed on your computer, see
   http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx""")
                    % port)

    def show_readwrite_error(self, port, message):
        showwarning(_(u'Read/Write error'),
                    _(u"""With device on: %s

Internal error message: %s

Please ensure that:
 - the choosen port is correct.
 - your altimeter is plugged to the USB adapter.
 - the USB adapter is plugged to your computer.
 - you did not unplugged the altimeter while it was communicating.""")
                    % (port, message))

    def show_protocol_error(self, port, message):
        showwarning(_(u'Protocol error'),
                    _(u"""With device on: %s

Internal error message: %s

Please ensure that:
 - your altimeter is plugged to the USB adapter.
 - you did not unplugged the altimeter while it was communicating.""")
                    % (port, message))

    def refresh_serial_ports(self):
        # Build port list.
        port_list = self.detect_serial_ports()

        # Remove previous items in combobox.
        menu = self.ports['menu']
        menu.delete(0, tk.END)

        # Add new items in combobox.
        self.port.set(port_list[0])
        for pr in port_list:
            menu.add_command(label=pr, command=lambda p=pr: self.port.set(p))

    def detect_serial_ports(self):
        # Try to detect system serial devices.
        port_list = []
        try:
            # Convert to filenames.
            port_list = [info[0].replace('cu', 'tty')
                    for info in list_ports.comports()]
        except Exception as e:
            showwarning(_(u'Serial Ports Detection'),
                    _(u'Error while detecting serial ports: %s') % e.message)

        # Insert default port as first entry.
        default = Altimeter().port
        try:
            # Try to remove default one to prevent duplication.
            port_list.remove(default)
        except ValueError:
            pass
        port_list.insert(0, default)

        return port_list
예제 #41
0
    def initialize(self):
        self.title(_(u'FlyDream Altimeter - Device Controller'))

        # Set fixed size.
        self.minsize(640, 320)
        self.resizable(False, False)

        # Altimeter local device.
        frame = tk.Frame(self, height=self.PORT_SELECTION_FRAME_HEIGHT)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        tk.Label(frame, text=_(u'Altimeter plugged on:')).pack(side=tk.LEFT)

        self.detect = tk.Button(frame, text=_(u'Refresh'),
                command=self.refresh_serial_ports)
        self.detect.pack(side=tk.RIGHT)

        self.port = tk.StringVar(self)
        self.ports = tk.OptionMenu(frame, self.port,
                _(u'Detecting serial ports...'))
        self.ports.pack(fill=tk.X, expand=tk.YES)

        # Update possible serial ports.
        self.refresh_serial_ports()

        # Upload altimeter flight data.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Upload'))
        label.pack(side=tk.TOP, fill=tk.X)

        # Setup bold font for titles.
        f = Font(font=label['font'])
        f['weight'] = 'bold'
        label['font'] = f.name

        Separator(frame).pack(fill=tk.X)

        self.progressbar = Progressbar(frame, orient='horizontal',
                mode='determinate')
        self.progressbar.pack(side=tk.BOTTOM, fill=tk.X)

        # Do not show progressbar
        # unless data is uploaded.
        self.hide_progressbar()

        self.upload_info = tk.StringVar()
        self.upload_info.set('/')
        self.info_label = tk.Label(frame, anchor=tk.NE, fg='darkgrey',
                textvariable=self.upload_info)
        self.info_label.pack(side=tk.BOTTOM, fill=tk.BOTH)

        self.label = tk.Label(frame, anchor=tk.W,
                text=_(u'Tell the altimeter to send flight '
                    'data to your computer'))
        self.label.pack(side=tk.LEFT)

        self.upload = tk.Button(frame, text=_(u'Upload data'),
                command=self.upload)
        self.upload.pack(side=tk.RIGHT)

        # Erase altimeter flight data.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Clear'))
        label['font'] = f.name
        label.pack(side=tk.TOP, fill=tk.X)

        Separator(frame).pack(fill=tk.X)

        label = tk.Label(frame, anchor=tk.W,
                text=_(u'Delete all the flight data from your altimeter'))
        label.pack(side=tk.LEFT)

        self.erase = tk.Button(frame, text=_(u'Erase data'),
                command=self.erase)
        self.erase.pack(side=tk.RIGHT)

        # Setup altimeter sampling frequency.
        frame = tk.Frame(self, padx=self.SUB_FRAME_X_PADDING)
        frame.pack(fill=tk.BOTH, expand=tk.YES)

        label = tk.Label(frame, anchor=tk.W, text=_(u'Configure'))
        label['font'] = f.name
        label.pack(side=tk.TOP, fill=tk.X)

        Separator(frame).pack(fill=tk.X)

        self.frequency = tk.StringVar(self)
        self.frequency.set('1')
        self.frequencies = tk.OptionMenu(frame, self.frequency,
                '1', '2', '4', '8')
        self.frequencies.pack(side=tk.LEFT)

        label = tk.Label(frame, text=_(u'records per second'))
        label.pack(side=tk.LEFT)

        self.setup = tk.Button(frame, text=_(u'Set sampling frequency'),
                command=self.set_frequency)
        self.setup.pack(side=tk.RIGHT)
예제 #42
0
  def _add_frames(self):
    # Adding Answer Backup Frame
    f1 = Frame(self)
    f1.grid(column=0, row=0, sticky="NWES")
    for i in range(4):
      f1.grid_rowconfigure(i, weight=0, pad=5)
    f1.grid_rowconfigure(4, weight=1, pad=5)
    for i in range(4):
      f1.grid_columnconfigure(i, weight=1, pad=5)

    Label(f1, anchor='e', text='Answers Count : ').grid(column=0, row=0, sticky='EWNS')
    self.answer_count = StringVar(value=len(self.crawler.answer_list))
    Label(f1, anchor='w', textvariable=self.answer_count).grid(column=1, row=0, sticky='EWNS')
    Label(f1, anchor='e', text='User Name : ').grid(column=2, row=0, sticky='EWNS')
    self.user = StringVar(value='Unknown')
    Label(f1, anchor='w', textvariable=self.user).grid(column=3, row=0, sticky='EWNS')

    tf_col = '#e6e6e6'
    tf = Tkinter.Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=0, sticky='EWNS')
    Label(tf, text='Quora User Options', bg=tf_col, anchor='c').grid(column=0, row=0, columnspan=2, sticky='EWNS')
    Button(tf, text='Login', command=lambda : self.thread('login'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Logout', command=lambda : self.thread('logout'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    tf = Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=2, sticky='EWNS')
    Label(tf, text='Answer List Option', bg=tf_col, anchor='c').grid(column=0, columnspan=2, row=0, sticky='EWNS')
    Button(tf, text='Reset', command=lambda : self.thread('reset'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Update', command=lambda : self.thread('update'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    # Add Progress Bar
    self.backup_progress = Progressbar(f1, orient="horizontal", length=100, mode="determinate")
    self.backup_progress.grid(row=2, columnspan=4, column=0, sticky='EWNS')

    # Adding Status Pane
    self.backup_status = StringVar(value='Ready')
    Label(f1, textvariable=self.backup_status, anchor='w').grid(row=3, column=0, columnspan=4, sticky='EWNS')

    # Adding The list of all answers
    tree = Treeview(f1, columns=('sno', 'date', 'question'))
    tree.heading('sno', text='S. No')
    tree.heading('date', text='Date')
    tree.heading('question', text='Question')

    tree.column("#0", width=0, stretch=False)
    tree.column('sno', width=40, stretch=False, anchor='center')
    tree.column('date', width=120, stretch=False, anchor='center')
    tree.column('question', stretch=True, anchor='w')
    tree.grid(column=0, columnspan=4, row=4, sticky='EWNS')
    tree.bind("<Double-1>", self.tree_item_click)
    self.answer_tree = tree
    self.populate_tree()

    f2 = Frame(self)
    self.add(f1, text='Answer Backup', underline=7)
    self.add(f2, text='Analytics')
예제 #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")
예제 #44
0
class QuoraAnalyticsUI(Notebook):

  def __init__(self):
    self.parent = Tkinter.Tk()
    Notebook.__init__(self, self.parent)
    #self.parent.title('Quora Analytics')
    self.parent.title('Quora Backup and Analytics')
    self.parent.wm_title('Quora Backup and Analytics')
    self.parent.grid_rowconfigure(0, weight=1)
    self.parent.grid_columnconfigure(0, weight=1)
    self.parent.resizable(True, True)
    self.grid_rowconfigure(0, weight=1)
    self.grid_columnconfigure(0, weight=1)
    self.crawler = QuoraCrawler(driver=QuoraCrawler.CHROME_DRIVER)
    self._add_frames()
    self.pack(fill='both', expand=True)

  def _add_frames(self):
    # Adding Answer Backup Frame
    f1 = Frame(self)
    f1.grid(column=0, row=0, sticky="NWES")
    for i in range(4):
      f1.grid_rowconfigure(i, weight=0, pad=5)
    f1.grid_rowconfigure(4, weight=1, pad=5)
    for i in range(4):
      f1.grid_columnconfigure(i, weight=1, pad=5)

    Label(f1, anchor='e', text='Answers Count : ').grid(column=0, row=0, sticky='EWNS')
    self.answer_count = StringVar(value=len(self.crawler.answer_list))
    Label(f1, anchor='w', textvariable=self.answer_count).grid(column=1, row=0, sticky='EWNS')
    Label(f1, anchor='e', text='User Name : ').grid(column=2, row=0, sticky='EWNS')
    self.user = StringVar(value='Unknown')
    Label(f1, anchor='w', textvariable=self.user).grid(column=3, row=0, sticky='EWNS')

    tf_col = '#e6e6e6'
    tf = Tkinter.Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=0, sticky='EWNS')
    Label(tf, text='Quora User Options', bg=tf_col, anchor='c').grid(column=0, row=0, columnspan=2, sticky='EWNS')
    Button(tf, text='Login', command=lambda : self.thread('login'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Logout', command=lambda : self.thread('logout'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    tf = Frame(f1, relief=GROOVE, borderwidth='2p')
    tf.grid(row=1, columnspan=2, column=2, sticky='EWNS')
    Label(tf, text='Answer List Option', bg=tf_col, anchor='c').grid(column=0, columnspan=2, row=0, sticky='EWNS')
    Button(tf, text='Reset', command=lambda : self.thread('reset'),
      highlightbackground=tf_col).grid(column=0, row=1, sticky='EWNS')
    Button(tf, text='Update', command=lambda : self.thread('update'),
      highlightbackground=tf_col).grid(column=1, row=1, sticky='EWNS')
    tf.grid_rowconfigure(0, weight=1, pad=5)
    tf.grid_rowconfigure(1, weight=1, pad=5)
    tf.grid_columnconfigure(0, weight=1, pad=5)
    tf.grid_columnconfigure(1, weight=1, pad=5)

    # Add Progress Bar
    self.backup_progress = Progressbar(f1, orient="horizontal", length=100, mode="determinate")
    self.backup_progress.grid(row=2, columnspan=4, column=0, sticky='EWNS')

    # Adding Status Pane
    self.backup_status = StringVar(value='Ready')
    Label(f1, textvariable=self.backup_status, anchor='w').grid(row=3, column=0, columnspan=4, sticky='EWNS')

    # Adding The list of all answers
    tree = Treeview(f1, columns=('sno', 'date', 'question'))
    tree.heading('sno', text='S. No')
    tree.heading('date', text='Date')
    tree.heading('question', text='Question')

    tree.column("#0", width=0, stretch=False)
    tree.column('sno', width=40, stretch=False, anchor='center')
    tree.column('date', width=120, stretch=False, anchor='center')
    tree.column('question', stretch=True, anchor='w')
    tree.grid(column=0, columnspan=4, row=4, sticky='EWNS')
    tree.bind("<Double-1>", self.tree_item_click)
    self.answer_tree = tree
    self.populate_tree()

    f2 = Frame(self)
    self.add(f1, text='Answer Backup', underline=7)
    self.add(f2, text='Analytics')

  def tree_item_click(self, event):
    idx_clicked = self.answer_tree.identify_row(event.y)
    if idx_clicked:
      print "Tree Item Clicked - ", idx_clicked

  def show_busy_dialog(self):
    tkMessageBox.showerror(
      title='Task in Progress',
      message=BUSY_MSG,
      icon=tkMessageBox.INFO
    )

  def thread(self, task):
    print "Starting a new Thread for " + task
    if self.backup_status.get() != 'Ready': self.show_busy_dialog()
    else:
      self.backup_status.set('Starting a new Task...')
      task_ids = (
        ('login', self.login_crawler),
        ('logout', self.logout_crawler),
        ('update', self.update_answer_list),
        ('reset', self.reset_answer_list)
      )

      for task_relation in task_ids:
        if task == task_relation[0]: Thread(target=task_relation[1]).start()

  def reset_answer_list(self):
    confirm = tkMessageBox.askquestion(
      title='Confirm Reset',
      message=RESET_MSG,
      icon='warning'
    )
    if confirm == 'yes':
      self.backup_status.set('Reseting Answer List...')
      self.backup_progress.start(interval=500)
      self.crawler.reset_answer_list()
      self.answer_count.set(len(self.crawler.answer_list))
      self.populate_tree()

    self.backup_status.set('Ready')
    self.backup_progress.stop()
    self.backup_progress['value'] = 0

  def update_answer_list(self):
    try:
      self.backup_status.set('Checking Login Status...')
      self.backup_progress.start(interval=500)
      if not self.crawler.check_login(self.backup_progress, self.backup_status):
        self.backup_status.set('Logged Out !! Cannot continue')
        tkMessageBox.showerror(
          title='Login Required',
          message=LOGIN_REQ_MSG,
          icon=tkMessageBox.INFO
        )
      else:
        self.backup_progress['value'] = 10
        self.backup_status.set('Updating Answer List...It may take few minutes')
        self.crawler.update_answer_list(self.backup_progress, self.backup_status)
        self.answer_count.set(len(self.crawler.answer_list))
        self.populate_tree()
    except STException:
      tkMessageBox.showerror(
        title='Operation Aborted',
        message=TIMEOUT_MSG,
        icon=tkMessageBox.ERROR
      )

    self.backup_status.set('Ready')
    self.backup_progress.stop()
    self.backup_progress['value'] = 0

  def login_crawler(self):
    try:
      self.backup_status.set('Checking Login Status...')
      self.backup_progress.start(interval=500)
      self.backup_progress['value'] = 10
      if self.crawler.check_login(self.backup_progress, self.backup_status):
        self.backup_progress['value'] = 100
        self.backup_progress.stop()
        tkMessageBox.showinfo(
          title='Login Successful',
          message=ALREADY_LOGIN_MSG,
          icon=tkMessageBox.INFO
        )
        self.user.set(self.crawler.get_user_name())
      else:
        # Opening Pop Up
        self.backup_status.set('Waiting For Credentials...')
        self.backup_progress['value'] = 40
        self.loginpop = PasswordPopUp(self)
        self.loginpop.grab_set() # To lock parent window when child is shown
        self.parent.wait_window(self.loginpop)
        self.loginpop.grab_release() # Reactivate parent window
        email = self.loginpop.uname.strip()
        passw = self.loginpop.passw.strip()
        if len(email) > 0 and len(passw) > 0:
          try:
            self.backup_status.set('Trying to log in with ' + email + ' ...')
            self.backup_progress['value'] = 60
            self.crawler.login(email, passw, self.backup_progress, self.backup_status)
            self.user.set(self.crawler.get_user_name())
          except QuoraCrawler.InvalidCredentialException, e:
            self.backup_status.set('Login Unsuccessful')
            self.backup_progress['value'] = 100
            self.backup_progress.stop()
            tkMessageBox.showerror(
              title='Invalid Credentials',
              message=e.message,
              icon=tkMessageBox.ERROR
            )
    except STException:
      tkMessageBox.showerror(
        title='Operation Aborted',
        message=TIMEOUT_MSG,
        icon=tkMessageBox.ERROR
      )

    self.backup_status.set('Ready')
    self.backup_progress.stop()
    self.backup_progress['value'] = 0

  def logout_crawler(self):
    try:
      self.backup_progress.start(interval=500)
      self.backup_status.set('Trying to Logging Out')
      self.crawler.logout(self.backup_progress, self.backup_status)
      self.user.set('Logged Out')
    except STException:
      tkMessageBox.showerror(
        title='Operation Aborted',
        message=TIMEOUT_MSG,
        icon=tkMessageBox.ERROR
      )
    self.backup_status.set('Ready')
    self.backup_progress.stop()
    self.backup_progress['value'] = 0

  def populate_tree(self):
    for i in self.answer_tree.get_children():
        self.answer_tree.delete(i)
    for idx, answer in enumerate(self.crawler.answer_list):
      self.answer_tree.insert('', 'end', idx + 1,
                              value=((idx + 1, answer[1], answer[2])))

  def destroy(self):
    self.crawler.quit()
    Notebook.destroy(self)
예제 #45
0

def extractgz(progressbar):  # Linux
    archive = tarfile.open("update.gz")
    archive.extractall()


if os.path.exists("update." + ext[platform.system()]):
    window = Tk()
    window.title("AO2XP updater")
    window.wm_resizable(0, 0)
    window.geometry("256x64")
    lb = Label(window)
    lb.pack()
    pb = Progressbar(window,
                     orient=HORIZONTAL,
                     length=100,
                     mode="indeterminate")
    pb.pack(fill="x")
    pb.start()

    def extractThread():
        time.sleep(0.1)
        lb["text"] = "Waiting 3 seconds for AO2XP to close..."
        time.sleep(3)
        pb.stop()
        pb["value"] = 0
        pb["mode"] = "determinate"
        lb["text"] = "Extracting update." + ext[platform.system()] + "..."
        globals()["extract" + ext[platform.system()]](
            pb)  # call the extract function according to OS
        lb["text"] = "Done!\nYou can now start AO2XP."
예제 #46
0
 def progressbar(self):
     root2 = tk.Tk()
     pb = Progressbar(root2, orient="horizontal", length=200, mode="determinate")
     pb.pack()
     pb.start()
     root2.mainloop()
예제 #47
0
    def __init__(self, master):
        super(MPExportApp, self).__init__()
        self.master = master
        self.export_type = StringVar()

        master.columnconfigure(1, weight=1)

        export_type_label = Label(master, text="Data Type: ")
        export_type_label.grid(row=0, column=0, sticky=E)

        radio_group_frame = Frame(master)
        radio_group_frame.grid(row=0, column=1, sticky=W)

        self.events_radio_button = Radiobutton(radio_group_frame, text='Events', value='events', variable=self.export_type,
                                               command=self.radio_button_changed)

        self.events_radio_button.select()
        self.events_radio_button.grid(row=0, column=0)

        self.people_radio_button = Radiobutton(radio_group_frame, text='People', value='people', variable=self.export_type,
                                               command=self.radio_button_changed)
        self.people_radio_button.grid(row=0, column=1)

        api_key_label = Label(master, text="API Key: ")
        api_key_label.grid(row=1, column=0, sticky=E)

        self.api_key_entry = Entry(master)
        self.api_key_entry.grid(row=1, column=1, columnspan=2, sticky=(E,W))

        api_secret_label = Label(master, text="API Secret: ")
        api_secret_label.grid(row=2, column=0, sticky=E)

        self.api_secret_entry = Entry(master)
        self.api_secret_entry.grid(row=2, column=1, columnspan=2, sticky=(E, W))

        self.project_token_label = Label(master, text="Project Token: ", state=DISABLED)
        self.project_token_label.grid(row=3, column=0, sticky=E)

        self.project_token_entry = Entry(master, state=DISABLED)
        self.project_token_entry.grid(row=3, column=1, columnspan=2, sticky=(E, W))

        self.events_label = Label(master, text="Events: ")
        self.events_label.grid(row=4, column=0, sticky=E)

        self.events_entry = Entry(master)
        self.events_entry.insert(0, 'Event A,Event B,Event C')
        self.events_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.events_entry))
        self.events_entry.grid(row=4, column=1, columnspan=2, sticky=(E, W))

        where_label = Label(master, text="Where: ")
        where_label.grid(row=5, column=0, sticky=E)
        self.where_entry = Entry(master)
        self.where_entry.grid(row=5, column=1, columnspan=2, sticky=(E, W))

        self.from_date_label = Label(master, text="From Date: ")
        self.from_date_label.grid(row=6, column=0, sticky=E)

        self.from_date_entry = Entry(master)
        self.from_date_entry.insert(0, 'YYYY-MM-DD')
        self.from_date_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.from_date_entry))
        self.from_date_entry.grid(row=6, column=1, columnspan=2, sticky=(E, W))

        self.to_date_label = Label(master, text="To Date: ")
        self.to_date_label.grid(row=7, column=0, sticky=E)

        self.to_date_entry = Entry(master)
        self.to_date_entry.insert(0, 'YYYY-MM-DD')
        self.to_date_entry.bind('<FocusIn>', partial(self.clear_placeholder_text, self.to_date_entry))
        self.to_date_entry.grid(row=7, column=1, columnspan=2, sticky=(E, W))

        export_button = Button(master, text="EXPORT", fg="green", command=self.export)
        export_button.grid(row=8, column=1, sticky=(E, W))

        self.delete_button = Button(master, text="DELETE", fg='red', state=DISABLED,
                                    command=lambda: threading.Thread(target=self.delete_people).start())
        self.delete_button.grid(row=9, column=1, sticky=(E, W))

        self.progress_bar = Progressbar(master)
        self.progress_bar_value = IntVar()
        self.progress_bar.config(mode='determinate', orient='horizontal', variable=self.progress_bar_value)
        self.progress_bar.grid(row=10, column=0, columnspan=3, sticky=(E, W))
예제 #48
0
class AudioJackGUI(object):
    def __init__(self, master):
        self.root = master
        self.searching = False
        self.can_download = True
        audiojack.set_useragent('AudioJack', '1.0')
        self.frame = ScrollableFrame(self.root)
        self.frame.setconfig(bg='#0D47A1', width=1280, height=720)
        self.frame.pack(side=TOP, fill=BOTH, expand=1)
        self.label = Label(self.frame.mainframe, text='AudioJack', fg='#ffffff', bg=self.frame.mainframe['background'], font=('Segoe UI', 48))
        self.label.pack()
        self.url_entry = Entry(self.frame.mainframe, width=48, font=('Segoe UI', 20), bg='#1565C0', bd=2, highlightthickness=1, highlightcolor='#1565C0', highlightbackground='#0D47A1', fg='#ffffff', insertbackground='#ffffff', relief=FLAT, insertwidth=1)
        self.url_entry.pack()
        self.submit_button = Button(self.frame.mainframe, width=60, font=('Segoe UI', 16), text='Go!', bd=0, bg='#1E88E5', fg='#ffffff', activebackground='#2196F3', activeforeground='#ffffff', relief=SUNKEN, cursor='hand2', command=self.submit)
        self.submit_button.pack()

        self.search_progress = Progressbar(self.frame.mainframe, orient='horizontal', length=720, maximum=100 ,mode='indeterminate')

        self.error_info = Label(self.frame.mainframe, fg='#ff0000', bg=self.frame.mainframe['background'])

        # Use pack_forget on this to reset the view
        self.contents = Frame(self.frame.mainframe, bg=self.frame.mainframe['background'])

        # Contains results and custom tag options
        self.select_frame = Frame(self.contents, bg=self.frame.mainframe['background'])
        self.select_frame.pack()

        #Search results
        self.results_label = Label(self.select_frame, text='Results:', fg='#ffffff', bg=self.frame.mainframe['background'])
        self.results_frame = Frame(self.select_frame, bg=self.frame.mainframe['background'])
        self.results_label.pack()
        self.results_frame.pack()

        # Downloads
        self.file_label = Label(self.contents, fg='#ffffff', bg=self.frame.mainframe['background'])

    def submit(self):
        self.searching = True

        self.error_info.pack_forget()
        self.error_info.config(text='')
        self.contents.pack_forget()
        self.reset_results_frame()
        self.file_label.config(text='')

        self.results_queue = Queue.Queue()
        t = Thread(target=self.search)
        t.daemon = True
        t.start()
        self.submit_button.pack_forget()
        self.search_progress.pack()
        self.search_progress.start(10)
        self.root.after(100, self.handle_results)

    def search(self):
        url = self.url_entry.get()
        try:
            self.results_queue.put(audiojack.get_results(url))
        except Exception as e:
            self.results_queue.put([])

    def handle_results(self):
        try:
            results = self.results_queue.get(0)
            self.reset_results_frame()
            self.search_progress.pack_forget()
            self.submit_button.pack()
            if results == []:
                self.error_info.config(text='No results found.')
                self.error_info.pack()
            else:
                for i, entry in enumerate(results):
                    self.get_result_box(entry).grid(row=i / 4, column=i % 4)
                self.contents.pack()
                self.select_frame.pack()
        except Queue.Empty:
            self.root.after(100, self.handle_results)

    def reset_results_frame(self):
        for result in self.results_frame.winfo_children():
            result.destroy()

    def get_result_box(self, entry):
        try:
            text ='%s\n%s\n%s' % (entry['title'], entry['artist'], entry['album'])
            raw_image = Image.open(BytesIO(entry['img'].decode('base64')))
            side = self.frame.mainframe.winfo_reqwidth() / 4
            image_data = raw_image.resize((side, side), Image.ANTIALIAS)
            image = ImageTk.PhotoImage(image=image_data)
            frame = Frame(self.results_frame)
            button = Button(frame, fg='#ffffff', text=text, image=image, compound=CENTER, bg=self.frame.mainframe['background'], command=lambda: self.select(entry))
            button.image = image
            button.pack(fill=BOTH, expand=1)
            return frame
        except Exception as e:
            print e
            print type(e)

    def select(self, entry):
        if self.can_download:
            self.can_download = False
            self.searching = False
            self.download_queue = Queue.Queue()
            t = Thread(target=lambda: self.get_select(entry))
            t.daemon = True
            t.start()
            self.root.after(100, self.handle_download)

    def get_select(self, entry):
        try:
            self.download_queue.put(audiojack.select(entry))
        except Exception:
            self.download_queue.put('')

    def handle_download(self):
            try:
                file = self.download_queue.get(0)
                self.can_download = True
                if not self.searching:
                    label_text = 'Downloaded %s' % file
                    self.select_frame.pack_forget()
                    self.file_label.config(text=label_text)
                    self.file_label.pack()
                    self.contents.pack()
            except Queue.Empty:
                self.root.after(100, self.handle_download)
예제 #49
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    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")

    # Clear what is in the text box.
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []

    # On click methods for scan me and scan others.
    def onClick(self, button_id):

        if button_id == 1:

            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground="blue")

            # Check to see if ports button is marked
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        message, total = scan_my_ports(int(starting_port),
                                                       int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")

                    time = "The TCP port scan completed in: " + str(
                        total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")

            # Check to see if IP button is marked
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)

            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0.new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        # If Scan other button is clicked.
        elif button_id == 2:

            # Check other IP's
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()

                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address,
                                                      ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(
                                    i, "is UP\n")
                                self.area.insert(0.0, new_message)

                        total_time = "Range scanned: " + str(
                            starting_ipv4_address) + " to " + str(
                                ending_ipv4_address
                            ) + "\n" + "The IP scan completed in:  " + str(
                                time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")

            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()

                        message, time = scan_ports_other(
                            int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i + "\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"

                    total_time = "TCP Port scan completed in: " + str(
                        time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Port range specified.")

            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected
                if message:
                    for i in message:
                        new_message = "Host name: " + str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)

                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground="red")

            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)

                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        else:
            pass
예제 #50
0
class InteractionWindow(Canvas):
    def __init__(self, master, _ndpi_file):
        self.master = master

        # For WBC-hunt
        self.hunter = False

        # Call the super constructor
        Canvas.__init__(self, master)
        #self.canvas = Canvas(self, master)

        # Zoom or roi mode (defaults to roi)
        self.mode = "roi"

        # Setup the input file
        self.ndpi_file = _ndpi_file
        self.im = None              # Actual PhotoImage object of the image
        self.rgba_im = None         # This is needed as a kept reference so that we can resize image on user action

        self.current_level = None   # Scale space level currently used for viewing (for handling zoom etc)

        self.image_handle = None    # Used to delete and recreate images
        self.setup_image()



        # Stuff for box selection
        self.init_box_pos = None            # In WINDOW coordinates
        self.curr_box_bbox = None           # Also in current WINDOW coordinates
        self.last_selection_region = None   # This is in level 0 coordinates
        self.zoom_level = 0     # How many times have we zoomed?
        self.zoom_region = []   # Stack of regions in level 0 coords that tells us where the zoom is, needed for transforming

        # Since we want multiple ROIs, save them in this list
        self.roi_list = []      # Contains Triple: (ROInumber, ROI_imagedata, (bbox, [sub_rois_list]))
        self.roi_counter = 0
        self.progress = Progressbar(self, orient="horizontal", length=100, mode="determinate", value=0)
        # ProgressBar to show user what is going on. Only one active at a time

        # Bind some event happenings to appropriate methods
        self.bind('<Configure>', self.resize_image)
        self.bind('<B1-Motion>', self.select_box)
        self.bind('<Button-1>', self.set_init_box_pos)
        self.bind('<ButtonRelease-1>', self.set_box)
        self.bind('<Button-3>', self.zoom_out)
        self.bind('<Left>', self.move_up)

        # DEBUG
        self.counter = 0

    # Handles initial setup of the input image
    def setup_image(self):

        # Select best scale space level and get its size

        # First get current canvas size, to determine the downsampling factor'
        self.master.update()  # Redraw screen so that the sizes are correct
        factor = float(self.ndpi_file.level_dimensions[0][0])/float(self.winfo_width())

        self.current_level = self.ndpi_file.get_best_level_for_downsample(factor)

        self.rgba_im = self.ndpi_file.read_region((0, 0), self.current_level,
                                                  self.ndpi_file.level_dimensions[self.current_level])

        self.rgba_im = self.rgba_im.resize((self.winfo_width(), self.winfo_height()))

        # Use TKs PhotoImage to show the image (needed for selecting ROIs)
        self.im = itk.PhotoImage(self.rgba_im)
        self.image_handle = self.create_image(0, 0, image=self.im, anchor=NW)

    # Whenever all ROIs and subROIs need to be redrawn, call this
    def redraw_ROI(self):
        # Start with drawing all main (red) rois
        for num, roi_container, bbox_container in self.roi_list:
            sub_rois = bbox_container[1]
            bbox = bbox_container[0]
            if len(sub_rois) is not 0:
                for sub_roi in sub_rois:
                    self.draw_rectangle(sub_roi, "green", 5, "subroi" + str(num))
            self.draw_rectangle(bbox, "red", 4, "roi"+str(num))

    # Method that ensures automatic resize in case the windows is resized by the user
    def resize_image(self, event):
        try:
            new_width = event.width
            new_height = event.height
        except AttributeError:
            #print "Attribute error in resize. Trying tuple variant. You are most probably in zoom mode so don't worry."
            new_width = event[0]
            new_height = event[1]

        self.master.update()  # Redraw screen so that the sizes are correct
        if self.last_selection_region is not None:
            factor = float(self.last_selection_region[1][1])/float(self.winfo_width())
        else:
            factor = float(self.ndpi_file.level_dimensions[0][0])/float(self.winfo_width())

        print "Factor: " + str(factor)
        self.current_level = self.ndpi_file.get_best_level_for_downsample(factor)
        print "Current level: " + str(self.current_level)

        # We have to make sure that we only show the zoomed-in area
        if self.last_selection_region is not None:# and self.mode is "zoom":
            self.render_status_text((100, 100), "Zooming...", 0, 50)
            # Need to transform l0 coordinates to coordinates of current_level, but only width and height!
            width, height = self.transform_to_arb_level(self.last_selection_region[1][0],
                                                        self.last_selection_region[1][1],
                                                        self.current_level)

            self.rgba_im = self.ndpi_file.read_region(self.last_selection_region[0], # The x and y needs to be in l0...
                                                      self.current_level,
                                                      (int(width), int(height)))
        else:
            self.rgba_im = self.ndpi_file.read_region((0, 0), self.current_level,
                                                      self.ndpi_file.level_dimensions[self.current_level])

        self.rgba_im = self.rgba_im.resize((new_width, new_height))

        self.im = itk.PhotoImage(self.rgba_im)
        self.delete(self.image_handle)
        self.create_image(0, 0, image=self.im, anchor=NW)
        self.clear_status_text()

    def set_init_box_pos(self, event):
        # If we are in clear mode, make sure that we handle it correctly.
        if self.mode is "clear":

            # First transform the coordinates to level 0
            (mouse_x, mouse_y) = self.transform_to_level_zero(event.x, event.y)

            # Loop through roi_list and see if we clicked on one of them
            for num, roi, bbox_container in self.roi_list:
                bbox = bbox_container[0]
                if bbox[0][0] < mouse_x < bbox[0][0]+bbox[1][0]:
                    if bbox[0][1] < mouse_y < bbox[0][1]+bbox[1][1]:
                        # Found a ROI!
                        self.delete("roi"+str(num))
                        self.delete("boxselector")
                        self.delete("subroi"+str(num))
                        self.roi_list.remove((num, roi, bbox_container))
                        break
        else:
            self.init_box_pos = (event.x, event.y)

    # From level 0 to arbitrary level coordinates
    def transform_to_arb_level(self, x_coord, y_coord, to_level):
        # We know that x and y are in level 0.
        factor = self.ndpi_file.level_downsamples[to_level]
        return float(x_coord)/factor, float(y_coord)/factor

    # From window coordinates to level 0 coordinates
    def transform_to_level_zero(self, x_coord, y_coord):

        x_percent = float(x_coord)/self.winfo_width()
        y_percent = float(y_coord)/self.winfo_height()

        if self.zoom_level is 0:
            ld = self.ndpi_file.level_dimensions[0]
            return x_percent*ld[0], y_percent*ld[1]
        else:
            ld = self.zoom_region[-1]
            return x_percent*ld[1][0]+ld[0][0], y_percent*ld[1][1]+ld[0][1]

    # Member function for clearing all ROI
    def clear_all_roi(self):
        for num, roi_container, bbox_container in self.roi_list:
            sub_rois = bbox_container[1]
            if len(sub_rois) is not 0:
                self.delete("subroi" + str(num))
            self.delete("roi"+str(num))
        self.roi_list = []
        self.roi_counter = 0
        self.delete("boxselector")

    def select_box(self, event):
        bbox = (event.x, event.y)
        self.curr_box_bbox = (self.init_box_pos, bbox)
        self.delete("boxselector")

        # Depending on the mode, we get different colors on the box
        if self.mode is "roi":
            width = self.curr_box_bbox[1][0]
            height = self.curr_box_bbox[1][1]
            topx = self.curr_box_bbox[0][0]
            topy = self.curr_box_bbox[0][1]

            l0_width, l0_height = self.transform_to_level_zero(width, height)
            l0_topx, l0_topy = self.transform_to_level_zero(topx, topy)

            # Get absolute pixel differences
            l0_width = abs(l0_width - l0_topx)
            l0_height = abs(l0_height - l0_topy)
            if (l0_width > 1000) or (l0_height > 1000):
                self.create_rectangle(self.curr_box_bbox, outline="red", tags="boxselector")
            else:
                self.create_rectangle(self.curr_box_bbox, outline="yellow", tags="boxselector")
        elif self.mode is "zoom":
            self.create_rectangle(self.curr_box_bbox, outline="green", tags="boxselector")

    # Lets us render a status bar, letting users know how far something has gotten
    def render_status_text(self, position, text, percentage, length):
        percentage = int(percentage*100.0)
        x = position[0]
        y = position[1]

        self.progress["length"] = length
        self.progress["value"] = percentage
        self.progress.place(x=x, y=y)

        self.create_text(x, y, text=text, anchor=SW, font=("Purisa", 16), tags="progresstext", fill="white")

        self.master.update()

    def clear_status_text(self):
        self.progress.place_forget()
        self.delete("progresstext")
        self.master.update()

    def set_box(self, event):
        # This is executed when the user has dragged a selection box (either zoom or ROI) and he/she has now let go of
        # the mouse. Our goal here is to get the level 0 coordinates of this box and then pass this box on depending
        # on what we want to do.
        width = self.curr_box_bbox[1][0]
        height = self.curr_box_bbox[1][1]
        topx = self.curr_box_bbox[0][0]
        topy = self.curr_box_bbox[0][1]

        l0_width, l0_height = self.transform_to_level_zero(width, height)
        l0_topx, l0_topy = self.transform_to_level_zero(topx, topy)

        # Get absolute pixel differences
        l0_width = abs(l0_width - l0_topx)
        l0_height = abs(l0_height - l0_topy)

        # We need to be able to access this region in the resize function
        self.last_selection_region = [(int(l0_topx), int(l0_topy)), (int(l0_width), int(l0_height))]

        #entire_roi = numpy.array(self.ndpi_file.read_region((int(l0_topx), int(l0_topy)), 0, (int(l0_width), int(l0_height))), dtype=numpy.uint8)
        # Multiply percentages of totals and transform to high res level
        # ------------------NEW----------------
        # Code below is ugly, might be able to reduce it to single double loop
        # Check if the ROI is too big, in that case split it and put into list
        box = []
        sub_rois = []   # Needed for drawing the subrois later on

        if not self.hunter:
            """
            if self.mode is "roi" and (l0_width > 1000 or l0_height > 1000):
                fixed_size = 500.0
                no_of_x_subrois = math.floor(float(l0_width)/float(fixed_size))
                no_of_y_subrois = math.floor(float(l0_height)/float(fixed_size))
                total = (no_of_x_subrois+1.0)*(no_of_y_subrois+1.0)   # The total number of subrois needed to be done
                counter = 0                                         # Used for knowing how far we've gotten in the loops

                for curr_x in range(int(no_of_x_subrois)):
                    for curr_y in range(int(no_of_y_subrois)):
                        curr_topx = l0_topx + fixed_size*float(curr_x)
                        curr_topy = l0_topy + fixed_size*float(curr_y)

                        box.append(numpy.array(self.ndpi_file.read_region((int(curr_topx), int(curr_topy)), 0, (int(fixed_size), int(fixed_size))), dtype=numpy.uint8))
                        # For now, just print boxes to show where we cut it
                        roi = [(int(curr_topx), int(curr_topy)), (int(fixed_size), int(fixed_size))]
                        sub_rois.append(roi)
                        # Render a status text aswell
                        counter += 1
                        self.render_status_text((topx, topy-20), "Reading data...", float(counter)/total, width-topx)

                # Now we need to handle the rest of the ROI that didn't fit perfectly into the fixed_size boxes
                # Remember, this also sort of needs to loop
                # Idea: Fix x or y, loop through the other one

                # Start with looping over x, y is fixed
                topy_rest = float(l0_topy) + no_of_y_subrois*fixed_size
                height_rest = (float(l0_topy) + float(l0_height)) - float(topy_rest)
                for curr_x in range(int(no_of_x_subrois)):
                    curr_topx = l0_topx + fixed_size*float(curr_x)
                    box.append(numpy.array(self.ndpi_file.read_region((int(curr_topx), int(topy_rest)), 0, (int(fixed_size), int(height_rest))), dtype=numpy.uint8))

                    roi = [(int(curr_topx), int(topy_rest)), (int(fixed_size), int(height_rest))]
                    sub_rois.append(roi)
                    # Render a status text aswell
                    counter += 1
                    self.render_status_text((topx, topy-20), "Reading data...", float(counter)/total, width-topx)

                # Now loop over y and x is fixed
                topx_rest = float(l0_topx) + no_of_x_subrois*fixed_size
                width_rest = (float(l0_topx) + float(l0_width)) - float(topx_rest)
                for curr_y in range(int(no_of_y_subrois)):
                    curr_topy = l0_topy + fixed_size*float(curr_y)
                    box.append(numpy.array(self.ndpi_file.read_region((int(topx_rest), int(curr_topy)), 0, (int(width_rest), int(fixed_size))), dtype=numpy.uint8))

                    roi = [(int(topx_rest), int(curr_topy)), (int(width_rest), int(fixed_size))]
                    sub_rois.append(roi)
                    # Render a status text aswell
                    counter += 1
                    self.render_status_text((topx, topy-20), "Reading data...", float(counter)/total, width-topx)

                # This is the last one, in the lower right corner
                topx_rest = float(l0_topx) + no_of_x_subrois*fixed_size
                topy_rest = float(l0_topy) + no_of_y_subrois*fixed_size
                width_rest = (float(l0_topx) + float(l0_width)) - float(topx_rest)
                height_rest = (float(l0_topy) + float(l0_height)) - float(topy_rest)
                roi = [(int(topx_rest), int(topy_rest)), (int(width_rest), int(height_rest))]
                sub_rois.append(roi)
                # Render a status text aswell
                counter += 1
                self.render_status_text((topx, topy-20), "Reading data...", float(counter)/total, width-topx)

                tmp = self.ndpi_file.read_region((int(topx_rest), int(topy_rest)), 0, (int(width_rest), int(height_rest)))
                box.append(numpy.array(tmp, dtype=numpy.uint8))
            """
            # Now depending on the mode, do different things
            if self.mode is "roi": # This is the case that the ROI selected is small enough to be alone
                box.append(numpy.array(self.ndpi_file.read_region((int(l0_topx), int(l0_topy)), 0, (int(l0_width), int(l0_height))), dtype=numpy.uint8))

        if self.mode is "roi":
            print "No of subboxes in roi you just selected: " + str(len(box))
            if self.hunter:
                box.append(numpy.array(self.ndpi_file.read_region((int(l0_topx), int(l0_topy)), 0, (int(l0_width), int(l0_height))), dtype=numpy.uint8))
            self.set_roi(box, sub_rois)
        elif self.mode is "zoom":
            self.zoom()
        self.delete("boxselector")
        self.clear_status_text()

    def set_roi(self, box, sub_rois):
        # Add the ROI to our list
        if not self.hunter:
            self.roi_list.append((self.roi_counter, box, (self.last_selection_region, sub_rois)))
        else:
            new_region = [self.last_selection_region[0], (500, 500)]
            self.roi_list.append((self.roi_counter, box, (new_region, sub_rois)))

        # Keep drawing the ROIs
        self.redraw_ROI()
        self.roi_counter += 1

        #self.create_text(self.curr_box_bbox[0][0], self.curr_box_bbox[0][1], text=str(len(self.roi_list)),
        #                 anchor=SW, font=("Purisa", 16), tags="roi"+str(len(self.roi_list)))

    def draw_rectangle(self, level_0_coords, outline, line_width, tag):
        # We need to transform the level 0 coords to the current window
        #factor = 1.0/self.ndpi_file.level_downsamples[self.current_level]
        top_x = level_0_coords[0][0]
        top_y = level_0_coords[0][1]
        width = level_0_coords[1][0]
        height = level_0_coords[1][1]

        # Get the percentages
        if self.zoom_level is 0:
            ld = self.ndpi_file.level_dimensions[0]
        else:
            ld = self.zoom_region[-1][1]
            top_x = top_x - self.zoom_region[-1][0][0]
            top_y = top_y - self.zoom_region[-1][0][1]

        top_x_percent = float(top_x)/ld[0]
        top_y_percent = float(top_y)/ld[1]
        width_percent = float(width)/ld[0]
        height_percent = float(height)/ld[1]

        top_x_view = top_x_percent*self.winfo_width()
        top_y_view = top_y_percent*self.winfo_height()
        width_view = width_percent*self.winfo_width()
        height_view = height_percent*self.winfo_height()

        box = [(top_x_view, top_y_view), (width_view+top_x_view, height_view+top_y_view)]

        self.create_rectangle(box, outline=outline, tags=tag, width=line_width)

    def zoom(self):
        # Set the zoom_region in level 0 coords
        x, y = self.transform_to_level_zero(self.curr_box_bbox[0][0], self.curr_box_bbox[0][1])
        width, height = self.transform_to_level_zero(self.curr_box_bbox[1][0], self.curr_box_bbox[1][1])

        self.zoom_region.append([(int(x), int(y)), (int(width-x), int(height-y))])
        self.zoom_level += 1

        self.resize_image((self.winfo_width(), self.winfo_height()))

        # We also need to make sure that the ROIs are (visually) transformed to the new zoom level
        self.redraw_ROI()

    def move_up(self, event):
        print "HEEEEJ"
        self.move(self.image_handle, 0, 10)

    # Right click zooms to previous zoom level
    def zoom_out(self, event):
        if self.zoom_level is not 0:
            if self.zoom_level is 1:
                self.reset_zoom()
            else:
                # Pop one off of the stack and reduce the zoom level by 1
                self.zoom_region.pop()
                self.zoom_level -= 1

                # The selection_region is used when resizing, so simulate that we just selected a region that is further
                # down the zoom stack
                self.last_selection_region = self.zoom_region[-1]
                self.resize_image((self.winfo_width(), self.winfo_height()))
        self.redraw_ROI()

    def reset_zoom(self):
        self.last_selection_region = None
        self.zoom_region = []
        self.zoom_level = 0
        self.resize_image((self.winfo_width(), self.winfo_height()))

        self.redraw_ROI()

    def run_roi(self):

        if not self.hunter:
            # Loop through the roi list and do segmentation and classification for each roi
            cell_list = []
            # Initial loop to get the total amount of rois to do, for the progress bar
            total_no_of_rois = 0
            for num, rois, bbox_container in self.roi_list:
                for roi in rois:
                    test = ImageShower(self, roi, "Before segmentation, roi number " + str(num))
                    #scipy.misc.imsave('testttttttt.png', roi)
                    im = Image.fromarray(roi)
                    im.save('../results/before_segmentation_roi_' + str(num) + '.png')
                    total_no_of_rois += 1
            print "Total no of rois to do: " + str(total_no_of_rois)

            # Counter for the progress bar
            counter = 0
            for num, rois, bbox_container in self.roi_list:
                #rois = roi_container[1]
                for roi in rois:
                    tmp_list, new_roi = rbc_seg.segment_and_remove_from_roi(roi)
                    cell_list = cell_list + tmp_list

                    # Show a segmented version of the ROI, "intermediate result"
                    test = ImageShower(self, new_roi, "After segmentation, roi number " + str(num))
                    im = Image.fromarray(new_roi)
                    im.save('../results/after_segmentation_roi_' + str(num) + '.png')
                    # Also make a progress bar
                    counter += 1
                    self.render_status_text((100, 100), "Running segmentation...", float(counter/float(total_no_of_rois)), 100)
            self.clear_status_text()

            # Call the classification
            if len(cell_list) is 0:
                show_msg("No WBC", self, "Only RBCs were detected in this/these roi/rois.")
            else:
                prediction = classer.predict_cells(cell_list)
                print "No of classified unknowns: " + str(len(prediction))
                #numpy.save("red_shit2.npy", self.roi_list[len(self.roi_list)-1][1][0])

                test = ResultDisplayer(cell_list, prediction)

        """
        testimg = cv2.imread("../npyimages/only_whites_3.png")
        testimg = cv2.cvtColor(testimg, cv2.COLOR_BGR2RGB)
        cell_list = rbc_seg.segmentation(testimg)
        prediction = classer.predict_cells(cell_list)
        test = ResultDisplayer(cell_list, prediction)
        #fff = open('../only_smeared.pik', 'w+')
        #pickle.dump(cell_list, fff)"""

        if self.hunter:
            for num, rois, bbox_container in self.roi_list:
                #rois = roi_container[1]
                for roi in rois:
                    numpy.save("../npyimages/c_test" + str(self.counter) + ".npy", roi)
                    self.counter += 1
예제 #51
0
class JobList(Frame):
    # NOTE: job_params contains information about a Job in the Joblist
    # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created

    def __init__(self, parent=None, **kwargs):
        Frame.__init__(self, parent)
        self.parent = parent
        self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL)
        self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll)
        self.job_list_xscroll['command'] = self.job_list.xview
        self.job_list_yscroll['command'] = self.job_list.yview
        self.new_job_frame = Frame(self)
        add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None
        if add_icon_filename == None:
            self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add)
        else:
            add_icon = PhotoImage(file=add_icon_filename)
            self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add)
        self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove)
        self.progress_frame = Frame(self)
        self.progress_value = Tkinter.IntVar()
        self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value)
        self.button_frame = Frame(self)
        self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs)
        self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows)

        self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None

        self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None

        self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None

        self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs)
        self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs)
        self.bind('<<CreatePlotGUI>>', self.create_plot_gui)
        self.parent.bind('<ButtonPress>', self.on_press)
        self.parent.bind('<Configure>', self.on_resize)

        self.reinit_variables()

        self.top_level_windows = list()

        # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized,
        # the resize option will be disabled for this window
        self.parent.resizable(width=False, height=False)

        self.lift()

    def reinit_variables(self):
        self.job_params = dict()

        self.last_job_id = -1

        self.job_outcomes = list()

        self.plot_args = list()

        self.on_button = False

    def add_job_params(self, input_args):
        self.job_params = input_args
        # Add each element to the job list
        for job in self.job_params:
            self.add_job(job)

    def add_job(self, job):
        try:
            index_end = job['input_directory'].rindex('/')
            index_start = job['input_directory'].rindex('/', 0, index_end)
            input_directory_text = job['input_directory']
            list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\''
            if job['start'] != None:
                list_text += ' ' + str(job['start'])
                if job['end'] != None:
                    list_text += ' to'
            if job['end'] != None:
                list_text += ' ' + str(job['end'])

            if job['job_id'] > self.last_job_id:
                self.last_job_id = job['job_id']

            self.job_list.insert(Tkinter.END, list_text)

            # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose)
            job['list_text'] = list_text

            # The line number is used wrt the GUI to indicate which job in the job list is being currently executed.
            job['line_number'] = self.job_list.size() - 1
            #print str(job['line_number'])

            self.job_params[job['job_id']] = job
        except KeyError as ke:
            # Should show some error message indicating that there is a problem.
            pass

        #print str(self.job_params)
        #print 'Added Job ' + str(job['job_id'])

    def ask_to_clear_jobs(self, event):
        for job in self.job_params.itervalues():
            line_number = job['line_number']
            self.job_list.itemconfig(line_number, foreground='black')

        # Update parent to refresh widget appearance
        self.parent.update()

        # Reactivate process button
        self.process_button.config(state = Tkinter.NORMAL)

        # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared.

        clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed.  Would you like to clear the job list?', master=self)
        if clearList:
            self.clear_list()

    def ask_to_plot_graphs(self, event):
        # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot'
        plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self)

        if not plotGraphs:
            return

        # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs
        if self.create_plots != None:
            output_files_list = list()
            for job_outcome in self.job_outcomes:
                for output_outcomes in job_outcome[2]:
                    (station, output_directory, output_files) = output_outcomes
                    for output_files_tuple in output_files:
                        for output_file_tuple in output_files_tuple:
                            (output_file, output_file_success) = output_file_tuple
                            if output_file_success:
                                # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list
                                if len(job_outcome) == 4:
                                    output_files_list.append([output_file, job_outcome[3]])
                                else:
                                    output_files_list.append([output_file])

            plots_thread = PlotsThread(self.create_plots, output_files_list, self)
            plots_thread.start()

    def add_plot(self, args=dict()):
        self.plot_args.append(args)

    def finished_adding_plots(self):
        self.event_generate('<<CreatePlotGUI>>', when='tail')

    def create_plot_gui(self, event):
        # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another
        graph_names = list()
        for args in self.plot_args:
            graph_name = args['output_file']
            graph_names.append(graph_name)
        dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui)

    # This is the entry point for the
    def finish_creating_plot_gui(self, plot_labels):
        graph_count = 1
        for plot_label in plot_labels:
            for args in self.plot_args:
                #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label
                #print 'The plot label is: ' + plot_label
                #print 'The output file is: ' + args['output_file']
                if plot_label == args['output_file']:
                    #print 'Creating graph ' + str(graph_count)
                    graph_count += 1
                    graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename)
                    graph_window.set_grid()
                    self.top_level_windows.append(graph_window)
        #print 'Creating plot GUI

        # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read
        # them and create the appropriate plot graph windows
        self.reinit_variables()

    # Clear all the elements in the list
    def clear_list(self):

        # Save plot args because they are need later in this run
        plot_args = self.plot_args
        self.reinit_variables()
        # Restore the plot args
        self.plot_args = plot_args

        self.job_list.delete(0, self.job_list.size())
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_add(self):
        single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self)
        single_job.set_grid()

    def on_remove(self):
        selection = self.job_list.curselection()
        for line_number in selection:
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            job = self.job_params.pop(job_id)
            self.job_list.delete(line_number)
            print 'Removed Job ' + str(job['job_id'])
        # Fix line number
        for line_number in range(self.job_list.size()):
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number)
            self.job_params[job_id]['line_number'] = line_number

    def set_grid(self):
        self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4)
        self.columnconfigure(0, minsize=600)
        self.rowconfigure(0, minsize=300)
        self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W)
        self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W)
        self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N)
        self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W)
        self.remove_job_button.grid(row=0, column=0)
        self.add_job_button.grid(row=0, column=1)
        self.progress_frame.grid(row=3, column=0, pady=3)
        self.progress_frame.columnconfigure(0, minsize=600)
        self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.columnconfigure(0, minsize=300)
        self.button_frame.columnconfigure(1, minsize=300)
        self.process_button.pack(side=Tkinter.RIGHT)
        self.quit_button.pack(side=Tkinter.RIGHT)

    def start_jobs(self):
        # If there are no queued jobs then simply return
        if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0:
            return
        # Deactivate the process button
        self.process_button.config(state = Tkinter.DISABLED)
        # Initialize the progress bar
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()
        # Start process thread
        jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume)
        jobs_thread.start()
        self['cursor'] = 'wait'

    def on_update(self, status, line_number, step):
        if status == 'init':
            self.job_list.itemconfig(line_number, foreground='green')
            self.job_list.activate(line_number)
        elif status == 'success':
            self.job_list.itemconfig(line_number, foreground='blue')
        elif status == 'fail':
            self.job_list.itemconfig(line_number, foreground='red')
        self.progress_value.set(step)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_resume(self, job_outcomes=list()):
        self.progress_value.set(100)
        self.job_outcomes = job_outcomes
        self.event_generate('<<AskToClearJobs>>', when='tail')
        self.event_generate('<<AskToPlotGraphs>>', when='tail')
        self['cursor'] = 'arrow'

    def close_top_level_windows(self):
        #print 'Closing other top level windows'
        for top_level_window in self.top_level_windows:
            if top_level_window:
                top_level_window.withdraw()
                top_level_window.destroy()

    def notify_of_close(self, top_level_window):
        if top_level_window in self.top_level_windows:
            #print 'Removing top level window'
            self.top_level_windows.remove(top_level_window)

    def on_press(self, event):
        self.on_button = True
        self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num)
        self.parent.bind(self.release_pattern, self.on_release)

    def on_release(self, event):
        self.on_button = False

    def on_resize(self, event):
        self.parent.lift()

        if self.on_button:

            self.set_grid()

    def on_close(self):
        self.plot_args = list()
        self.withdraw()
        self.destroy()
class VideoScanProgressScreen(GuiBaseFrame):
    def __init__(self, parent, controller, **kw):
        GuiBaseFrame.__init__(self, parent, controller, **kw)
        self.counting_left_frames = None

    def init_widgets(self):
        self.content_wrapper = Frame(self)
        self.content_wrapper.configure(background="white")
        self.screen_title = Header1Label(
            self.content_wrapper, text="Scanning video for information...\n")
        self.progress_bar = Progressbar(self.content_wrapper,
                                        orient=HORIZONTAL,
                                        mode="indeterminate",
                                        length=WINDOW_WIDTH / 2)
        self.wait_text = PLabel(
            self.content_wrapper,
            text="\nThis might take a few minutes."
            "\nPlease do not change the video files while this is running.\n")
        self.left_frames_count = PLabel(self.content_wrapper,
                                        text=LEFT_FRAMES_COUNT_PREFIX + "0")
        self.right_frames_count = PLabel(self.content_wrapper,
                                         text=RIGHT_FRAMES_COUNT_PREFIX + "0")
        self.elapsed_time_label = PLabel(self.content_wrapper)
        self.empty_space = PLabel(self.content_wrapper, text=" ")
        self.next_button = Button(
            self.content_wrapper,
            text="Next",
            state=DISABLED,
            command=lambda: self.controller.show_next_frame())

    def add_widgets_to_frame(self):
        self.screen_title.pack()
        self.progress_bar.pack()
        self.wait_text.pack()
        self.left_frames_count.pack()
        self.right_frames_count.pack()
        self.elapsed_time_label.pack()
        self.empty_space.pack()
        self.next_button.pack()
        self.content_wrapper.place(relx=SCREENS_REL_X,
                                   rely=SCREEN_REL_Y_45,
                                   anchor=CENTER)

    def on_show_frame(self):
        self.start_time = time.time()
        self.progress_bar.start()
        self.frame_count_thread = threading.Thread(
            target=self.controller.video_frame_loader.count_frames_in_videos,
            kwargs={"controller": self.controller})
        self.frame_count_thread.start()
        self.master.after(50, self.check_thread)

    def update_frame(self, data):
        if LEFT_FRAMES_COUNT_PREFIX in data:
            self.left_frames_count.configure(text=data)
        if RIGHT_FRAMES_COUNT_PREFIX in data:
            self.right_frames_count.configure(text=data)

        self.elapsed_time_label.configure(
            text=ELAPSED_TIME_PREFIX +
            str(datetime.timedelta(seconds=int(time.time() -
                                               self.start_time))))

    def on_hide_frame(self):
        self.progress_bar.stop()

    def check_thread(self):
        if self.frame_count_thread.is_alive():
            self.master.after(50, self.check_thread)
        else:
            self.progress_bar.stop()
            self.wait_text.configure(text="\nDone!\nPress Next to continue.\n")
            self.next_button.configure(state=NORMAL)
예제 #53
0
class InstallationFrame(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("FLE - KA Lite Setup - Start installation")
        self.loadImages()
        self.configureLayout()
        self.drawLayout()

    def loadImages(self):
        """Loads the images. The size must be the exact size of the image."""

        self.kaliteleaf_photo = PhotoImage(file="images/kaliteleaf.gif", width=16, height=16)

    def configureLayout(self):

        self.top_frame = Frame(self, relief=RAISED, borderwidth=1)

        self.tip_label_text = StringVar()
        self.tip_label = Label(self.top_frame, textvariable=self.tip_label_text)
        self.tip_label_text.set("Install KA Lite")

        self.kaliteleaf_label = Label(self.top_frame, image=self.kaliteleaf_photo, width=16, height=16)
        self.kaliteleaf_label.image = self.kaliteleaf_photo

        self.info_label_text = StringVar()
        self.info_label_frame = Frame(self)
        self.info_label = Label(self.info_label_frame, textvariable=self.info_label_text)
        self.info_label_text.set("Ready to start...")

        self.progress_bar_frame = Frame(self)
        self.progress_bar_value = IntVar()
        self.progress_bar = Progressbar(self.progress_bar_frame, mode="indeterminate", variable=self.progress_bar_value, length=400)

        self.bottom_space_frame = Frame(self)

        self.install_button_frame = Frame(self)
        self.install_button = Button(self.install_button_frame, text="Install", command=self.startInstallation, width=15, height=2)

        self.quit_button = Button(self.install_button_frame, text="Quit", state=DISABLED, command=quitInstaller, width=15, height=2)

    def drawLayout(self):

        self.pack(fill=BOTH, expand=True)
        self.top_frame.pack(fill=X)
        self.tip_label.pack(fill=X, side=LEFT, padx=5, pady=5)
        self.kaliteleaf_label.pack(fill=X, side=RIGHT, padx=5, pady=5)

        self.info_label_frame.pack(fill=X)
        self.info_label.pack(fill=X, expand=True, padx=10, pady=10)

        self.progress_bar_frame.pack(fill=X)
        self.progress_bar.pack(fill=X, expand=True, padx=15, pady=15)

        self.bottom_space_frame.pack(fill=BOTH, expand=True)

        self.quit_button.pack(fill=X, side=RIGHT)

        self.install_button_frame.pack(fill=X, padx=5, pady=5)
        self.install_button.pack(fill=X, side=RIGHT, padx=5)

    def startInstallation(self):
        global TARGET_PATH
        if not TARGET_PATH:
            return
        src = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ka-lite")
        self.progress_bar.start(10)
        self.number_of_files = 0
        t1 = FuncThread(self.startInstall, src, self.progress_bar, self.number_of_files, self.progress_bar_value, self.tip_label_text, self.info_label_text, self.install_button, self.quit_button)
        t1.start()

    def startInstall(self, src, progress_bar, number_of_files, progress_bar_value, tip_label_text, info_label_text, install_button, quit_button):
        install_button.config(state=DISABLED)
        tip_label_text.set("Preparing to install KA Lite...")
        info_label_text.set("Calculating the number of files to copy...")

        files = []     
        if os.path.isdir(src):
            for path, dirs, filenames, in os.walk(src):
                files.extend(filenames)
        number_of_files = len(files)
        
        progress_bar.stop()
        progress_bar.config(maximum=number_of_files, mode="determinate", length=400)
        progress_bar_value.set(0)
        count = 0

        tip_label_text.set("Installing...")
        info_label_text.set(str(count)+" of "+str(number_of_files)+" copied.")
        
        list = []
        for path, dirs, filenames in os.walk(src):
            list.append((path, dirs, filenames))
        if not os.path.exists(TARGET_PATH):
            os.makedirs(TARGET_PATH)

        for t in list:
            for directory in t[1]:
                destDir = t[0].replace(src,TARGET_PATH)
                if not os.path.exists(os.path.join(destDir, directory)):
                    os.makedirs(os.path.join(destDir, directory))

            for sfile in t[2]:
                srcFile = os.path.join(t[0], sfile) 
                destFile = os.path.join(t[0].replace(src, TARGET_PATH), sfile)             
                shutil.copy(srcFile, destFile)
                count+=1
                info_label_text.set(str(count)+" of "+str(number_of_files)+" copied.")
                progress_bar_value.set(count)

        quit_button.config(state=NORMAL)
        tip_label_text.set("Installation complete.")
        info_label_text.set("All files were sucessfuly copied.")
        return
예제 #54
0
    def __init__(self):
        Tk.__init__(self)
        self.title("WebSite ScreenShooter")
        self.geometry("390x420")

        self.mainFrame = Frame(self)
        self.mainFrame.pack(pady=5, padx=5)

        self.urlLabelFrame = Frame(self.mainFrame)
        self.urlLabelFrame.pack(pady=5, side=TOP, fill=X)
        self.urlImportLabel = Label(self.urlLabelFrame, text="web URLs:")
        self.urlImportLabel.pack(side=LEFT, padx=5)

        self.importTextFrame = Frame(self.mainFrame)
        self.importTextFrame.pack(pady=5, side=TOP, fill=X)
        self.yTextScrollbar = Scrollbar(self.importTextFrame)
        self.yTextScrollbar.pack(side=RIGHT, fill=Y)
        self.xTextScrollbar = Scrollbar(self.importTextFrame,
                                        orient=HORIZONTAL)
        self.xTextScrollbar.pack(side=BOTTOM, fill=X)
        self.importUrlsText = Text(self.importTextFrame,
                                   padx=5,
                                   pady=5,
                                   wrap=NONE,
                                   width=50,
                                   height=10,
                                   yscrollcommand=self.yTextScrollbar.set,
                                   xscrollcommand=self.xTextScrollbar.set)
        self.importUrlsText.pack(side=TOP, padx=5, pady=5, fill=X)
        self.yTextScrollbar.config(command=self.importUrlsText.yview)
        self.xTextScrollbar.config(command=self.importUrlsText.xview)

        self.outputLabelFrame = Frame(self.mainFrame)
        self.outputLabelFrame.pack(pady=5, side=TOP, fill=X)
        self.outputFileLabel = Label(self.outputLabelFrame,
                                     text="Path to the output folder:")
        self.outputFileLabel.pack(side=LEFT, padx=5)

        self.outputFieldFrame = Frame(self.mainFrame)
        self.outputFieldFrame.pack(pady=5, side=TOP, fill=X)
        self.outputFieldEntry = Entry(self.outputFieldFrame,
                                      name="outputFile",
                                      width=30)
        self.outputFieldEntry.pack(side=LEFT, padx=5)
        self.btnBrowse = Button(self.outputFieldFrame,
                                height=1,
                                width=6,
                                text="Browse...",
                                command=self.browse)
        self.btnBrowse.pack(side=RIGHT, padx=5)

        self.controlsFrame = Frame(self.mainFrame)
        self.controlsFrame.pack(pady=5, side=TOP, fill=X)
        self.btnClose = Button(self.controlsFrame,
                               height=1,
                               width=6,
                               text="Close",
                               command=self.close)
        self.btnClose.pack(side=LEFT, padx=5)
        self.btnRun = Button(self.controlsFrame,
                             height=1,
                             width=6,
                             text="Run",
                             command=self.run)
        self.btnRun.pack(side=RIGHT, padx=5)

        # *** PROGRESS BAR ***
        self.status = Progressbar(self.mainFrame,
                                  orient='horizontal',
                                  length=310,
                                  mode='determinate',
                                  value=0,
                                  maximum=100)
        self.status.pack(pady=5, padx=5, side=BOTTOM)
예제 #55
0
class InterfaceGauche(LabelFrame):
    """Left frame of the GUI, giving the buttons and the current price and winner"""
    def __init__(self, tk_frame, police, **kwargs):
        LabelFrame.__init__(self, tk_frame, text="Tirage", font=police, **kwargs)
        self.waiting_time = 10

        self.message = Label(self, text="Appuyez sur le bouton pour lancer le tirage", font=police)
        self.message.grid(column=0, row=0, columnspan=2)

        self.bouton_quitter = Button(self, text="Quitter", command=self.quit, font=police)
        self.bouton_quitter.grid(column=0, row=1, pady=10)

        self.bouton_cliquer = Button(self, text="Lancer!", fg="red",
                                     command=self.click, font=police)
        self.bouton_cliquer.grid(column=1, row=1)

        self.message_price = Label(self, text="Tirage pour:", font=police)
        self.price = Label(self, text='', bg="white", width=40, height=1, font=police)
        self.message_price.grid(column=0, row=3)
        self.price.grid(column=1, row=3, columnspan=1, padx=10, pady=10)

        self.message_name = Label(self, text="Le gagnant est:", font=police)
        self.name = Label(self, text="", bg="white", width=40, height=1, font=police)
        self.message_name.grid(column=0, row=4)
        self.name.grid(column=1, row=4, columnspan=1, pady=10)
        
        self.parent_name = self.winfo_parent()
        self.parent = self._nametowidget(self.parent_name)

        # Part waiting time
        self.interval = Label(self, text="Intervalle entre tirages (s)", font=police)
        self.interval.grid(column=0, row=6, columnspan=1, pady=10)
        self.v = StringVar()
        self.v.set(self.waiting_time)
        self.interval_length = Entry(self, textvariable=self.v,  width=5, justify=CENTER, font=police)
        self.interval_length.grid(column=1, row=6, columnspan=1)
        self.progress_bar = Progressbar(self, length=300)
        self.progress_bar.grid(column=0, row=8, columnspan=2, pady=10)
        self.nb_players_text = Label(self, text="Nombre de joueurs", font=police)
        self.nb_players_text.grid(column=0, row=10, columnspan=1, pady=10)
        self.nb_players = Label(self, text="0", font=police)
        self.nb_players.grid(column=1, row=10, columnspan=1, pady=10)
        self.nb_prices_text = Label(self, text="Nombre de prix restants", font=police)
        self.nb_prices_text.grid(column=0, row=11, columnspan=1, pady=10)
        self.nb_prices = Label(self, text="0", font=police)
        self.nb_prices.grid(column=1, row=11, columnspan=1, pady=10)

        # police=tkFont.Font(self, size=12)#, family='Courier')
        # self.config(, font=police)
        # for i in range(5):
        # self.grid_rowconfigure(2, weight=1)
        # self.grid_rowconfigure(5, weight=1)
        # self.grid_rowconfigure(7, weight=1)
        # self.grid_rowconfigure(9, weight=1)
        for i in range(2):
            self.grid_columnconfigure(i, weight=1)

    def click(self):
        """When click is selected, the tombola starts"""
        try:
            self.waiting_time = int(self.v.get())
        except ValueError:
            showerror("Error", "L'intervalle doit être un nombre")
            return
        self.progress_bar['maximum'] = self.waiting_time+0.01
        self.interval_length.config(state=DISABLED)
        self.parent.draw_tombola(self.waiting_time)

        if not self.parent.list_prices:
            self.bouton_cliquer.config(state=DISABLED)
            self.price["text"] = "Tous les lots ont été tirés"
            self.name["text"] = ""
            self.update()
            
    def update_nb_players(self):        
        self.nb_players["text"] = len(self.parent.list_names)
        self.nb_players.update()
        
    def update_nb_prices(self):        
        self.nb_prices["text"] = len(self.parent.list_prices)
        self.nb_prices.update()
예제 #56
0
 def __init__(self, master, **options):
     Progressbar.__init__(self, master, **options)
     self.queue = Queue.Queue()
     self.check_queue()
예제 #57
0
class FindServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.selected = "";
        self.controller = controller
        label = Label(self, text="Select server", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label.pack(side="top", fill="x", pady=10)
        
        self.button1 = Button(self, text="Next",state="disabled", command=self.callback_choose)
        button2 = Button(self, text="Refresh", command=self.callback_refresh)        
        button3 = Button(self, text="Back", command=self.callback_start)
        
        scrollbar = Scrollbar(self)
        self.mylist = Listbox(self, width=100, yscrollcommand = scrollbar.set )
        self.mylist.bind("<Double-Button-1>", self.twoClick)

        self.button1.pack()
        button2.pack()
        button3.pack()
        # create list with a scroolbar
        scrollbar.pack( side = "right", fill="y" )
        self.mylist.pack( side = "top", fill = "x", ipadx=20, ipady=20, padx=20, pady=20 )
        scrollbar.config( command = self.mylist.yview )
        # create a progress bar
        label2 = Label(self, text="Refresh progress bar", justify='center', anchor='center')
        label2.pack(side="top", fill="x")
        
        self.bar_lenght = 200
        self.pb = Progressbar(self, length=self.bar_lenght, mode='determinate')
        self.pb.pack(side="top", anchor='center', ipadx=20, ipady=20, padx=10, pady=10)
        self.pb.config(value=0)

    # to select he server user must double-click on it
    def twoClick(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        self.selected = value
        self.button1.config(state="normal")
        # save the selected server in a global variable
        SELECTED_SERV = SERVER_LIST[selection[0]]
        set_globvar(SELECTED_SERV)      
    
    # listen for broadcasts from port 8192
    def listen_broadcasts(self, port, timeout):
        # Set the progress bar to 0
        self.pb.config(value=0)
        step_size = ((self.bar_lenght/(MAX_NR_OF_SERVERS+1))/2)
        list_of_servers = []
        # Initialize the listener
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(('', port))
        s.settimeout(LISTENING_TIMEOUT)
        # Listen for a number of times to get multiple servers
        for _ in range(MAX_NR_OF_SERVERS + 1):
            # Update the progress bar
            self.pb.step(step_size)
            self.pb.update_idletasks()
            try:
                message, address = s.recvfrom(8192) 
                m_split = message.split(';')
                if m_split[0] == '\HELLO':
                    server_id = (m_split[1], address)
                    # Check if the server has not yet broadcasted itself.
                    if server_id not in list_of_servers:
                        list_of_servers.append(server_id)              
            except:
                pass
        # Close the socket
        s.close()
        if not list_of_servers:
            # If no server found, pop a warning message.
            tkMessageBox.showwarning("Find Servers", "No servers found. Refresh or create a new game.")
        # Set the progress bar back to 0
        self.pb.config(value=0)
        # Return the whole list of available servers
        return list_of_servers
    
    # service the refresh button
    def callback_refresh(self):
        global SERVER_LIST
        self.mylist.delete(0,END)
        SERVER_LIST = self.listen_broadcasts(BROADCASTING_PORT, LISTENING_TIMEOUT)
        for server_el in SERVER_LIST:
            self.mylist.insert(END,(" "+str(server_el[0])+"  IP: "+str(server_el[1])+"  Time: "+str(time.asctime())))
    
    def callback_choose(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("ChooseType")
        
    def callback_start(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("StartPage")
예제 #58
0
class GUI:
    def __init__(self, master):
        ################-GLOBAL-VARS-############################
        self.version = 1.1
        self.loadingMsg = "Loading......................."
        self.driver = ""
        self.tupleDates = []
        self.roomTimeList = []
        self.roomIndex = 0
        self.outputTimeArray = []
        self.userInfo = []
        self.master = master
        self.outputEmail = ""

        ###############-WINDOW-SETUP-############################
        self.master.title("LibCal Booker v" + str(self.version))
        self.master.resizable(width=False, height=False)
        self.master.protocol("WM_DELETE_WINDOW", self.window_close)
        self.master.createcommand('exit', self.window_close)
        self.master.bind('<Return>', self.submit_click)

        ###############-LOAD-FILE-###############################
        # TODO: Check fields of json, if do not match, transfer over files
        try:
            with open("userInfo.json") as data_file:
                self.userInfo = json.load(data_file)
        except:
            print "No existing user"
            with open("userInfo.json", "w+") as data_file:
                self.userInfo = dict(version=self.version,
                                     first="Mitchell",
                                     last="Pynn",
                                     email="*****@*****.**",
                                     override=0,
                                     confirm=1,
                                     browser=0,
                                     firstLoad=True,
                                     authEmail="")
                json.dump(self.userInfo, data_file)

        ###################-DATE SELECTION-######################
        # set up availDates
        self.availDates = [self.loadingMsg]
        # set up chosen date and give default value
        self.chosenDate = StringVar(self.master)
        self.chosenDate.set(self.loadingMsg)
        # set up dateOptionMenu
        self.dateOptionMenu = OptionMenu(self.master,
                                         self.chosenDate,
                                         *self.availDates,
                                         command=self.date_click)
        self.dateOptionMenu.grid(row=0,
                                 column=0,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 pady=(8, 0),
                                 padx=(5, 0))

        ##################-ROOM SELECTION-######################
        # set up availRooms
        self.availRooms = [
            'LI 1004', 'LI 1006', 'LI 1007', 'LI 1008', 'LI 1009', 'LI 1010',
            'LI 4001', 'LI 4002', 'LI 4003', 'LI 4004', 'LI 4005', 'LI 4006',
            'LI 4007', 'LI 4008', 'LI 4009', 'LI 4010'
        ]
        self.availTimes = [
            '8:00am - 8:30am', '8:30am - 9:00am', '9:00am - 9:30am',
            '9:30am - 10:00am', '10:00am - 10:30am', '10:30am - 11:00am',
            '11:00am - 11:30am', '11:30am - 12:00pm', '12:00pm - 12:30pm',
            '12:30pm - 1:00pm', '1:00pm - 1:30pm', '1:30pm - 2:00pm',
            '2:00pm - 2:30pm', '2:30pm - 3:00pm', '3:00pm - 3:30pm',
            '3:30pm - 4:00pm', '4:00pm - 4:30pm', '4:30pm - 5:00pm',
            '5:00pm - 5:30pm', '5:30pm - 6:00pm', '6:00pm - 6:30pm',
            '6:30pm - 7:00pm', '7:00pm - 7:30pm', '7:30pm - 8:00pm',
            '8:00pm - 8:30pm', '8:30pm - 9:00pm', '9:00pm - 9:30pm',
            '9:30pm - 10:00pm', '10:00pm - 10:30pm', '10:30pm - 11:00pm',
            '11:00pm - 11:30pm', '11:30pm - 11:59pm'
        ]
        # set up chosen room and give default value
        self.chosenRoom = StringVar(self.master)
        self.chosenRoom.set(self.availRooms[0])
        # set up roomOptionMenu
        self.roomOptionMenu = OptionMenu(self.master,
                                         self.chosenRoom,
                                         *self.availRooms,
                                         command=self.room_click)
        self.roomOptionMenu.grid(row=1,
                                 column=0,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 padx=(5, 0),
                                 pady=(5, 0))

        ##################-TIME SELECTION-####################
        self.timeOptionList = Listbox(self.master,
                                      selectmode=EXTENDED,
                                      height=20,
                                      exportselection=0,
                                      takefocus=0)
        self.timeOptionList.grid(row=2,
                                 column=0,
                                 rowspan=200,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 padx=(5, 0),
                                 pady=5)
        self.timeOptionList.insert(0, self.loadingMsg)
        self.timeOptionList.config(state=DISABLED)

        #################-BUTTONS-##########################
        # user info
        self.infoLabel = Label(self.master,
                               text="[ U S E R  I N F O ]",
                               font=("Helvetica", 16, "bold"))
        self.infoLabel.grid(row=0, column=1, columnspan=2, sticky=E + W)

        # first Name label and input
        self.fnameLabel = Label(self.master,
                                text="First: ",
                                font=("Helvetica", 12, "bold"))
        self.fnameLabel.grid(row=1, column=1, sticky=W)

        self.fnameEntry = Entry(self.master)
        self.fnameEntry.grid(row=1, column=2, stick=E + W, padx=(0, 5))
        self.fnameEntry.insert(0, self.userInfo["first"])

        # last name label and input
        self.lnameLabel = Label(self.master,
                                text="Last: ",
                                font=("Helvetica", 12, "bold"))
        self.lnameLabel.grid(row=2, column=1, sticky=W)

        self.lnameEntry = Entry(self.master)
        self.lnameEntry.grid(row=2, column=2, stick=E + W, padx=(0, 5))
        self.lnameEntry.insert(0, self.userInfo["last"])

        # email label and entry
        self.emailLabel = Label(self.master,
                                text="Email: ",
                                font=("Helvetica", 12, "bold"))
        self.emailLabel.grid(row=3, column=1, sticky=W)

        self.emailEntry = Entry(self.master)
        self.emailEntry.grid(row=3, column=2, stick=E + W, padx=(0, 5))
        self.emailEntry.insert(0, self.userInfo["email"])

        # showBrowser checkbox
        self.browserVal = IntVar(self.master)
        self.browserVal.set(self.userInfo["browser"])
        self.browser = Checkbutton(self.master,
                                   text="Show web browser",
                                   variable=self.browserVal,
                                   command=self.browser_show,
                                   onvalue=1,
                                   offvalue=0,
                                   font=("Helvetica", 12),
                                   takefocus=0)
        self.browser.grid(row=4, column=2, sticky=W)

        # override checkbox
        self.overrideVal = IntVar(self.master)
        self.overrideVal.set(self.userInfo["override"])
        self.override = Checkbutton(self.master,
                                    text="Override 2hr max",
                                    variable=self.overrideVal,
                                    onvalue=1,
                                    offvalue=0,
                                    font=("Helvetica", 12),
                                    takefocus=0)
        self.override.grid(row=5, column=2, sticky=W)

        # confirm checkbox
        self.confirmVal = IntVar(self.master)
        self.confirmVal.set(self.userInfo["confirm"])
        self.confirm = Checkbutton(self.master,
                                   text="Enable confirm dialog",
                                   variable=self.confirmVal,
                                   onvalue=1,
                                   offvalue=0,
                                   font=("Helvetica", 12),
                                   takefocus=0)
        self.confirm.grid(row=6, column=2, sticky=W)

        # submit button
        self.submit = Button(self.master,
                             text="Submit",
                             command=self.submit_click,
                             takefocus=0)
        self.submit.grid(row=8,
                         column=2,
                         sticky=(N, S, E, W),
                         padx=(0, 5),
                         pady=(0, 5))
        self.submit["state"] = "disabled"

        # loading bar
        self.loadingBar = Progressbar(self.master,
                                      orient=HORIZONTAL,
                                      length=100,
                                      mode='determinate')
        self.loadingBar.grid(row=9,
                             column=2,
                             sticky=(N, S, E, W),
                             padx=(0, 5),
                             pady=(0, 5))
        self.loadingBar["value"] = 10

        # email
        self.emm = Button(self.master,
                          text="email tester",
                          command=self.test_email_click,
                          takefocus=0)
        self.emm.grid(row=10,
                      column=2,
                      sticky=(N, S, E, W),
                      padx=(0, 5),
                      pady=(0, 5))

        # update skeleton GUI, then load data
        self.master.update()
        self.load_data()

        # make sure window on top
        self.master.lift()

        # show welcome message if first load
        if self.userInfo["firstLoad"]:
            tkMessageBox.showinfo(
                "Welcome",
                "Currently, booking multiple rooms is not permitted. You are limited to only booking one room per session. However, booking multiple time slots per room is permitted.\n\nMake sure to update the [ USER INFO ] section with your own name and email. \n\nCreated by Mitchell Pynn "
            )

    def test_email_click(self):
        self.outputEmail = "*****@*****.**"

    def email_click(self, randVals):
        """
        Shows basic usage of the Gmail API.

        Creates a Gmail API service object and outputs a list of label names
        of the user's Gmail account.
        """
        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        service = discovery.build('gmail', 'v1', http=http)

        userProfile = service.users().getProfile(userId='me').execute()

        # set user JSON auth email
        self.userInfo["authEmail"] = userProfile['emailAddress']

        for idItem in randVals:
            print idItem
            try:
                # please newer_than:1d to: + idItem
                email1 = service.users().messages().list(userId='me',
                                                         q='to:' +
                                                         idItem).execute()
                output = email1['messages']

                text = service.users().messages().get(
                    userId='me', id=output[0]['id']).execute()
                ampFix = text['snippet'].replace('&amp;', '&')


                confirmUrl = \
                re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+|]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', ampFix)[
                    0] + '&m=confirm'
                print(confirmUrl)

                self.driver.execute_script("window.open('" + confirmUrl +
                                           "', 'new_window')")
                self.driver.switch_to.window(self.driver.window_handles[1])
                try:
                    # wait until page is loaded and success element found
                    element = WebDriverWait(self.driver, 5).until(
                        EC.presence_of_element_located(
                            (By.CLASS_NAME, "final_msg")))

                    # close tab and return to main page
                    self.driver.close()
                    self.driver.switch_to.window(self.driver.window_handles[0])

                except:
                    print "Could not book room " + idItem

            except:
                print('An error occurred confirming the room: ????')

    def get_credentials(self):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir,
                                       self.outputEmail + '.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
            flow.user_agent = APPLICATION_NAME
            if flags:
                credentials = tools.run_flow(flow, store, flags)
            else:  # Needed only for compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print('Storing credentials to ' + credential_path)
        return credentials

    def browser_show(self):
        if self.browserVal.get() == 1:
            # hide window/throw in corner
            self.driver.set_window_position(0, 0)
            self.driver.set_window_size(100, 600)
        else:
            # hide window/throw in corner
            self.driver.set_window_position(3000, 3000)
            self.driver.set_window_size(100, 300)

    def save_data(self):
        # update userFile when submitted
        with open("userInfo.json", 'r+') as data_file:
            self.userInfo["first"] = self.fnameEntry.get()
            self.userInfo["last"] = self.lnameEntry.get()
            self.userInfo["email"] = self.emailEntry.get()
            self.userInfo["confirm"] = self.confirmVal.get()
            self.userInfo["override"] = self.overrideVal.get()
            self.userInfo["browser"] = self.browserVal.get()
            self.userInfo["firstLoad"] = False

            data_file.seek(0)
            json.dump(self.userInfo, data_file)
            data_file.truncate()

    def window_close(self):
        # save data
        self.save_data()
        # destroy GUI and quit driver
        self.master.destroy()
        self.driver.quit()

        # clean log files if exist (maybe good to keep?)
        dir = os.listdir(os.getcwd())
        for item in dir:
            if item.endswith(".log"):
                os.remove(os.path.join(os.getcwd(), item))

    # from -> http://stackoverflow.com/a/12578715
    def is_windows_64bit(self):
        if 'PROCESSOR_ARCHITEW6432' in os.environ:
            return True
        return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')

    def load_data(self):
        self.loadingBar["value"] = 25
        self.master.update_idletasks()

        # connect to webdriver - Try Google Chrome, then Firefox
        chrome = False
        try:
            chromeOptions = webdriver.ChromeOptions()
            prefs = {
                "profile.managed_default_content_settings.images": 2,
                "profile.managed_default_content_settings.stylesheet": 2
            }
            chromeOptions.add_experimental_option("prefs", prefs)

            if platform.system() == 'Darwin':
                self.driver = webdriver.Chrome(
                    executable_path=os.getcwd() +
                    '/bin/chrome/chromedriverDarwin',
                    chrome_options=chromeOptions)
            elif platform.system() == 'Windows':
                self.driver = webdriver.Chrome(
                    executable_path=os.getcwd() +
                    '/bin/chrome/chromedriverWindows.exe',
                    chrome_options=chromeOptions)
            elif platform.system() == 'Linux':
                self.driver = webdriver.Chrome(executable_path=os.getcwd() +
                                               '/bin/chrome/chromedriverLinux',
                                               chrome_options=chromeOptions)
            else:
                print "Fatal error - incompatible operating system"
                exit()
            chrome = True
        except:
            print "Could not load Chrome, trying Firefox."

        if not chrome:
            try:
                # setup firefox profile, no images, no css for speed
                firefox_profile = webdriver.FirefoxProfile()
                firefox_profile.add_extension(
                    os.getcwd() + "/bin/ext/quickjava-2.1.2-fx.xpi")
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.curVersion", "2.1.2.1"
                )  ## Prevents loading the 'thank you for installing screen'
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.Images",
                    2)  ## Turns images off
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.AnimatedImage",
                    2)  ## Turns animated images off
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.CSS", 2)  ## CSS
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.Flash",
                    2)  ## Flash
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.Java",
                    2)  ## Java
                firefox_profile.set_preference(
                    "thatoneguydotnet.QuickJava.startupStatus.Silverlight",
                    2)  ## Silverlight

                # load driver according to operating system,
                if platform.system() == 'Darwin':
                    self.driver = webdriver.Firefox(
                        executable_path=os.getcwd() +
                        '/bin/gecko/geckodriverDarwin',
                        firefox_profile=firefox_profile)
                elif platform.system() == 'Windows':
                    if self.is_windows_64bit():
                        self.driver = webdriver.Firefox(
                            executable_path=os.getcwd() +
                            '/bin/gecko/geckodriverWindows64.exe',
                            firefox_profile=firefox_profile)
                    else:
                        self.driver = webdriver.Firefox(
                            executable_path=os.getcwd() +
                            '/bin/gecko/geckodriverWindows.exe',
                            firefox_profile=firefox_profile)
                elif platform.system() == 'Linux':
                    self.driver = webdriver.Firefox(
                        executable_path=os.getcwd() +
                        '/bin/gecko/geckodriverLinux',
                        firefox_profile=firefox_profile)
                else:
                    print "Fatal error - incompatible operating system"
                    exit()
            except:
                # get no firefox exception
                print "You must have Firefox or Google Chrome installed"
                exit(6)

        # hide window/throw in corner or show
        self.browser_show()
        self.master.lift()

        self.loadingBar["value"] = 50
        self.master.update_idletasks()

        # load intial site
        self.driver.get("http://libcal.lakeheadu.ca/rooms_acc.php?gid=13445")
        assert "The Chancellor Paterson Library" in self.driver.title

        # scrape dates, only have to do once
        self.tupleDates = collections.OrderedDict()
        dateWheel = Select(self.driver.find_element_by_id("datei"))
        for date in dateWheel.options:
            self.tupleDates[date.text] = date.get_attribute("value")

        self.loadingBar["value"] = 75
        self.master.update_idletasks()

        # remove loading option, pull dates from tuple to list
        # set chosen date to top entry in date list
        # format: {'Monday June 1st': '06-01-17'}
        self.availDates.remove(self.loadingMsg)
        for key, value in self.tupleDates.iteritems():
            self.availDates.append(key)
        self.chosenDate.set(self.availDates[0])

        # get menu, clear and add dates
        menu = self.dateOptionMenu["menu"]
        menu.delete(0, "end")
        for val in self.availDates:
            menu.add_command(
                label=val, command=lambda pvalue=val: self.date_click(pvalue))

        # update GUI, will show current date in selection
        self.master.update()
        # initial load data
        self.date_click()
        # make sure on top
        self.master.lift()

    def date_click(self, value=""):
        # do nothing if same day clicked
        if value:
            if self.chosenDate.get() == value:
                return
            else:
                self.chosenDate.set(value)
                self.loadingBar["value"] = 20
                self.submit["state"] = "disabled"
                self.master.update_idletasks()

        # clear timeOptionList contents, showing loading message
        self.timeOptionList.delete(0, END)
        self.timeOptionList.insert(0, self.loadingMsg)
        self.timeOptionList.config(state=DISABLED)
        if value:
            self.loadingBar["value"] = 40
        self.master.update()

        # load selected date webpage
        self.driver.get(
            "http://libcal.lakeheadu.ca/rooms_acc.php?gid=13445&d=" +
            self.tupleDates[self.chosenDate.get()] + "&cap=0")

        # does this wait until page is loaded?
        assert "The Chancellor Paterson Library" in self.driver.title
        # make sure loaded?

        # create 2D array of [0]'s
        self.roomTimeList = [[0] for _ in range(16)]

        if value:
            self.loadingBar["value"] = 60
            self.master.update_idletasks()
        self.room_click("room")

    def room_click(self, value=""):
        if value == "room":
            self.loadingBar["value"] = 95
        else:
            self.loadingBar["value"] = 30
            self.submit["state"] = "disabled"
            self.master.update_idletasks()
        # set roomIndex to new room
        self.roomIndex = self.availRooms.index(self.chosenRoom.get())

        # clear timeOptionList contents, showing loading message
        self.timeOptionList.delete(0, END)
        self.timeOptionList.insert(0, self.loadingMsg)
        self.timeOptionList.config(state=DISABLED)
        if value != "room":
            self.loadingBar["value"] = 40
        self.master.update()

        form = self.driver.find_element_by_id("roombookingform")
        if value != "room":
            self.loadingBar["value"] = 60
            self.master.update_idletasks()
        rooms = form.find_elements_by_tag_name("fieldset")
        if value != "room":
            self.loadingBar["value"] = 80
            self.master.update_idletasks()

        # don't scrape again if already loaded
        if self.roomTimeList[self.roomIndex] == [0]:
            for room in rooms:
                # find selected room
                if room.find_element_by_tag_name(
                        "h2").text[:7] != self.chosenRoom.get():
                    continue
                # go through each room, pulling times to array
                times_out = []
                check_boxes = room.find_elements_by_class_name("checkbox")

                for box in check_boxes:
                    # output checkbox text
                    times_out.append(
                        self.availTimes.index(
                            box.find_element_by_tag_name("label").text))
                self.roomTimeList.insert(self.roomIndex, times_out)
                break

        # for the selected room, set time slots
        self.timeOptionList.config(state=NORMAL)
        self.timeOptionList.delete(0, END)
        if len(self.roomTimeList[self.roomIndex]) > 0:
            for timeSlot in self.roomTimeList[self.roomIndex]:
                self.timeOptionList.insert(END, self.availTimes[timeSlot])
        else:
            self.timeOptionList.insert(END, "No times available")
            self.timeOptionList.config(state=DISABLED)

        # update height, update the whole list if it isnt first run
        self.timeOptionList.configure(
            height=len(self.roomTimeList[self.roomIndex]))

        # colorize alternating lines of the listbox
        for i in range(0, len(self.roomTimeList[self.roomIndex]), 2):
            self.timeOptionList.itemconfigure(i, background='#f0f0ff')

        self.loadingBar["value"] = 100
        self.master.update_idletasks()

        # update GUI size and remove loading bar
        self.submit["state"] = "normal"
        self.master.update()

    def submit_click(self, value=""):
        if self.emailEntry.get().strip()[-13:] != "@lakeheadu.ca":
            tkMessageBox.showerror(
                "Email format error",
                "Please make sure to use a valid @lakeheadu.ca email address")
            return

        self.save_data()

        selection = self.timeOptionList.curselection()
        if selection == ():
            return
        if len(selection) > 4 and self.overrideVal.get() != 1:
            tkMessageBox.showerror("2hr Limit",
                                   "Sorry, you can only book 2hrs per day")
            return
        if self.confirmVal.get() == 1:
            outputTimes = ""
            lineBreak = '-' * (len(self.chosenDate.get()) + 2)
            for index in selection:
                pIndex = self.roomTimeList[self.roomIndex][int(index)]
                outputTimes += self.availTimes[pIndex] + "\n"
            if not tkMessageBox.askokcancel(
                    "Please confirm the following times",
                    self.chosenDate.get() + "\n" + lineBreak + "\n" +
                    self.availRooms[self.roomIndex] + "\n" + outputTimes):
                return

        # if output, get times
        self.outputTimeArray = []
        for index in selection:
            pIndex = self.roomTimeList[self.roomIndex][int(index)]
            self.outputTimeArray.append(self.availTimes[pIndex])

        # book rooms
        self.book_times()

        # check if any rooms were unavailable
        if len(self.outputTimeArray) > 0:
            outputText = "The following times were unavailable to book\n----------------------------------------\n"
            for item in self.outputTimeArray:
                outputText += item + "\n"
            tkMessageBox.showerror("Unavailable", outputText)

        # clear booked room time slots,
        self.roomTimeList[self.roomIndex] = [0]
        self.room_click()

    def book_times(self):
        # refresh page
        try:
            self.driver.refresh()
        except:
            print "Could not load the browser"
        assert "The Chancellor Paterson Library" in self.driver.title

        outputText = "Successfully booked the following rooms \n" + self.chosenDate.get(
        ) + "\n" + '-' * (len(self.chosenDate.get()) +
                          2) + "\n" + self.chosenRoom.get()
        outputLength = 0
        outputRandomId = []
        self.outputEmail = self.emailEntry.get().strip(
        )[:-13] + "@lakeheadu.ca"
        while True:
            # get rooms
            form = self.driver.find_element_by_id("roombookingform")
            rooms = form.find_elements_by_tag_name("fieldset")

            for room in rooms:
                # find selected room
                if room.find_element_by_tag_name(
                        "h2").text[:7] != self.availRooms[self.roomIndex]:
                    continue

                consect = 0
                selectedTimes = []
                checkBoxes = room.find_elements_by_class_name("checkbox")
                for box in checkBoxes:
                    # loops through times from start every time, how can I keep place of where left off?
                    timeSlot = box.find_element_by_tag_name("label")
                    if timeSlot.text in self.outputTimeArray:
                        consect += 1
                        # adding another time will not overflow 2hrs, add it
                        if consect <= 4:
                            # check for consecutive, if array is blank, add time regardless
                            # try the simplify
                            if selectedTimes != []:
                                for selectedIndex in selectedTimes:
                                    # check if time is in consecutive order
                                    # can I put or in between two conditions????
                                    if (self.availTimes.index(timeSlot.text) -
                                            1) == selectedIndex or (
                                                self.availTimes.index(
                                                    timeSlot.text) +
                                                1) == selectedIndex:
                                        outputText += "\n" + timeSlot.text
                                        # add to selectedTimes
                                        selectedTimes.append(
                                            self.availTimes.index(
                                                timeSlot.text))
                                        # remove timeSlot from array
                                        self.outputTimeArray.remove(
                                            timeSlot.text)
                                        # click timeSlot
                                        timeSlot.click()
                                        break
                            else:
                                outputText += "\n" + timeSlot.text
                                # add to selectedTimes
                                selectedTimes.append(
                                    self.availTimes.index(timeSlot.text))
                                # remove timeSlot from array
                                self.outputTimeArray.remove(timeSlot.text)
                                # click timeSlot
                                timeSlot.click()

                        # if 4 boxes are selected, break and book the selected rooms
                        else:
                            break
                    # if at least one box is selected, book it, must be consecutive
                    elif consect > 0:
                        break

                break
            if consect > 0:
                # fill info of form
                self.driver.find_element_by_id("fname").send_keys(
                    self.fnameEntry.get())
                self.driver.find_element_by_id("lname").send_keys(
                    self.lnameEntry.get())

                # always uses random_id, override 2hrs just prevents user from booking more
                # then 2hrs at a time
                randId = self.id_generator()
                outputRandomId.append(randId)
                self.driver.find_element_by_id(
                    "email").send_keys(self.emailEntry.get().strip()[:-13] +
                                       "+" + randId + "@lakeheadu.ca")

                # submit
                self.driver.find_element_by_id("s-lc-rm-ac-but").click()

                # assert it is success
                try:
                    # search for success element / fail
                    # handle failure
                    element = WebDriverWait(self.driver, 10).until(
                        EC.visibility_of_element_located(
                            (By.ID, "s-lc-rm-ac-success")))
                except TimeoutException:
                    tkMessageBox.showerror(
                        "ERROR", "Error booking the room. Exiting...")
                    self.driver.quit()
            # refresh page
            self.driver.refresh()

            # if out of times to book or cannot book times, break out
            if len(self.outputTimeArray) <= 0 or len(
                    self.outputTimeArray) == outputLength:
                break

            outputLength = len(self.outputTimeArray)

        # print success message
        if len(self.outputTimeArray) <= 0:
            print outputRandomId
            tkMessageBox.showinfo("Success", outputText)
            # ask to confirm
            # if email used to book rooms does not match email authEmail
            ## show message that redirection is happening
            if tkMessageBox.askyesno(
                    "Confirm times",
                    "Would you like to confirm your booked times?"):
                # check if
                if self.userInfo['authEmail'] != self.outputEmail:
                    tkMessageBox.showinfo(
                        "Redirecting...", "Press OK and login with " +
                        self.outputEmail + " in the browser that will open.")
                self.email_click(outputRandomId)

    # random ID generator -> http://stackoverflow.com/a/2257449
    def id_generator(self,
                     size=8,
                     chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
예제 #59
0
def gdsConv(u, m):
    global mode
    global unit
    global globIm
    global im
    rightFrame.pack_propagate(0)
    if im == None:
        for widget in rightFrame.winfo_children():
            widget.destroy()
        l2 = Label(rightFrame,
                   text=' Import Image first! ',
                   relief=RAISED,
                   font='calibri 15 bold',
                   fg='red').pack(padx=140)
    else:
        if u == "" or (m not in ('2', '4', '8', '16', '32',
                                 '64')) or (not str.isdigit(u)):
            for widget in rightFrame.winfo_children():
                widget.destroy()
            label = Label(rightFrame, image=globIm)
            label.image = globIm
            label.pack(padx=60)
            l2 = Label(rightFrame,
                       text=' Please select valid unit and Layers! ',
                       relief=RAISED,
                       font='calibri 15 bold',
                       fg='red').pack(padx=60, pady=10)
        else:
            saveLoc = tkFileDialog.asksaveasfilename()
            if saveLoc == None or saveLoc == "":
                for widget in rightFrame.winfo_children():
                    widget.destroy()
                label = Label(rightFrame, image=globIm)
                label.image = globIm
                label.pack(padx=60)
                l2 = Label(rightFrame,
                           text=' Select a save location! ',
                           relief=RAISED,
                           font='calibri 15 bold',
                           fg='red').pack(padx=60, pady=10)
            else:
                unit = int(u) * 1e-9
                mode = int(m)
                for widget in rightFrame.winfo_children():
                    widget.destroy()
                # label = Label(rightFrame,image = globIm)
                # label.image = globIm
                # label.pack(padx = 60)
                ###gdsWriter###
                name = fileLoc.split('/')[-1].split('.')[0]
                width, height = im.size
                cell = core.Cell('GDSII')
                layout = core.Layout(name, unit)
                rows = np.arange(height)
                global imArray
                imArray = misc.imread(fileLoc, flatten=1)
                maxVal = np.max(imArray)
                minVal = np.min(imArray)
                bins = []
                levels = mode
                for b in range(levels + 1):
                    interval = (maxVal - minVal + 1) / float(levels)
                    bins.append(minVal + b * interval)
                t = time.time()
                global mask
                mask = np.digitize(imArray, bins)
                ####Shows discritised image###
                digitized = mask * (256 / (levels))
                im = Image.fromarray(digitized.astype('uint8'))
                width, height = im.size
                m = max(width, height)
                if m > 330:
                    scale = 330.0 / m
                else:
                    scale = 1
                globIm = im.resize((int(width * scale), int(height * scale)),
                                   Image.ANTIALIAS)
                globIm = ImageTk.PhotoImage(globIm)
                label = Label(rightFrame, image=globIm)
                label.image = globIm
                label.pack(padx=int((420 - width * scale) / 2))
                l2 = Label(rightFrame,
                           text='Conversion in progress...',
                           relief=RAISED,
                           font='calibri 15 bold',
                           fg='blue').pack(padx=60, pady=10)
                progress_var = DoubleVar(root)
                progress = Progressbar(rightFrame,
                                       orient=HORIZONTAL,
                                       variable=progress_var,
                                       maximum=100,
                                       length=290)
                progress.pack(padx=20)
                for row in rows:
                    k = (float(row) / height) * 100
                    progress_var.set(k)
                    time.sleep(0.001)
                    root.update()
                    r = mask[row]
                    col = 0
                    while col < width:
                        i = 0
                        pres = r[col]
                        if r[col + i] == pres and r[col + i] > 1:
                            while r[col + i] == pres:
                                i = i + 1
                                if col + i > width - 1:
                                    break
                            cell.add(
                                core.Path([(col, height - row),
                                           (col + i, height - row)],
                                          pathtype=0,
                                          layer=pres - 1))
                            col = col + i
                        else:
                            col = col + 1
                layout.add(cell)
                layout.save(saveLoc + '.gds')
                for widget in rightFrame.winfo_children():
                    widget.destroy()
                label = Label(rightFrame, image=globIm)
                label.image = globIm
                label.pack(padx=60)
                l2 = Label(rightFrame,
                           text='Conversion completed.',
                           relief=RAISED,
                           font='calibri 15 bold',
                           fg='blue').pack(padx=60, pady=10)
                tot = int((time.time() - t))
                m = int(tot / 60)
                s = int(tot % 60)
                # message = Listbox(rightFrame,font = 'Times 12', width = 360)
                # message.pack(side = LEFT)
                # message.insert(END,'Time taken: '+str(m)+' minutes and '+str(s)+' seconds')
                # message.insert(END,'Image dimensions: width = '+str(width)+' height = '+str(height))
                # message.insert(END,'Pixel size used: '+str(unit))
                inpSize = os.path.getsize(fileLoc)
                outSize = os.path.getsize(saveLoc + '.gds')
                message = Label(
                    rightFrame,
                    text='Conversion time: ' + str(m) + ' minutes and ' +
                    str(s) + ' seconds\n' + 'Image dimensions: width = ' +
                    str(width) + ' height = ' + str(height) + '\n' +
                    'Pixel size used: ' + str(unit * 1e9) + ' nm\n' +
                    'Input file size: ' + str(inpSize / 1024) +
                    ' KB Output GDSII file size: ' + str(outSize / 1024) +
                    ' KB',
                    anchor=W,
                    justify=LEFT,
                    font='calibri 11 bold')
                message.pack(side=LEFT, padx=5)
예제 #60
0
    def __init__(self, master):
        ################-GLOBAL-VARS-############################
        self.version = 1.1
        self.loadingMsg = "Loading......................."
        self.driver = ""
        self.tupleDates = []
        self.roomTimeList = []
        self.roomIndex = 0
        self.outputTimeArray = []
        self.userInfo = []
        self.master = master
        self.outputEmail = ""

        ###############-WINDOW-SETUP-############################
        self.master.title("LibCal Booker v" + str(self.version))
        self.master.resizable(width=False, height=False)
        self.master.protocol("WM_DELETE_WINDOW", self.window_close)
        self.master.createcommand('exit', self.window_close)
        self.master.bind('<Return>', self.submit_click)

        ###############-LOAD-FILE-###############################
        # TODO: Check fields of json, if do not match, transfer over files
        try:
            with open("userInfo.json") as data_file:
                self.userInfo = json.load(data_file)
        except:
            print "No existing user"
            with open("userInfo.json", "w+") as data_file:
                self.userInfo = dict(version=self.version,
                                     first="Mitchell",
                                     last="Pynn",
                                     email="*****@*****.**",
                                     override=0,
                                     confirm=1,
                                     browser=0,
                                     firstLoad=True,
                                     authEmail="")
                json.dump(self.userInfo, data_file)

        ###################-DATE SELECTION-######################
        # set up availDates
        self.availDates = [self.loadingMsg]
        # set up chosen date and give default value
        self.chosenDate = StringVar(self.master)
        self.chosenDate.set(self.loadingMsg)
        # set up dateOptionMenu
        self.dateOptionMenu = OptionMenu(self.master,
                                         self.chosenDate,
                                         *self.availDates,
                                         command=self.date_click)
        self.dateOptionMenu.grid(row=0,
                                 column=0,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 pady=(8, 0),
                                 padx=(5, 0))

        ##################-ROOM SELECTION-######################
        # set up availRooms
        self.availRooms = [
            'LI 1004', 'LI 1006', 'LI 1007', 'LI 1008', 'LI 1009', 'LI 1010',
            'LI 4001', 'LI 4002', 'LI 4003', 'LI 4004', 'LI 4005', 'LI 4006',
            'LI 4007', 'LI 4008', 'LI 4009', 'LI 4010'
        ]
        self.availTimes = [
            '8:00am - 8:30am', '8:30am - 9:00am', '9:00am - 9:30am',
            '9:30am - 10:00am', '10:00am - 10:30am', '10:30am - 11:00am',
            '11:00am - 11:30am', '11:30am - 12:00pm', '12:00pm - 12:30pm',
            '12:30pm - 1:00pm', '1:00pm - 1:30pm', '1:30pm - 2:00pm',
            '2:00pm - 2:30pm', '2:30pm - 3:00pm', '3:00pm - 3:30pm',
            '3:30pm - 4:00pm', '4:00pm - 4:30pm', '4:30pm - 5:00pm',
            '5:00pm - 5:30pm', '5:30pm - 6:00pm', '6:00pm - 6:30pm',
            '6:30pm - 7:00pm', '7:00pm - 7:30pm', '7:30pm - 8:00pm',
            '8:00pm - 8:30pm', '8:30pm - 9:00pm', '9:00pm - 9:30pm',
            '9:30pm - 10:00pm', '10:00pm - 10:30pm', '10:30pm - 11:00pm',
            '11:00pm - 11:30pm', '11:30pm - 11:59pm'
        ]
        # set up chosen room and give default value
        self.chosenRoom = StringVar(self.master)
        self.chosenRoom.set(self.availRooms[0])
        # set up roomOptionMenu
        self.roomOptionMenu = OptionMenu(self.master,
                                         self.chosenRoom,
                                         *self.availRooms,
                                         command=self.room_click)
        self.roomOptionMenu.grid(row=1,
                                 column=0,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 padx=(5, 0),
                                 pady=(5, 0))

        ##################-TIME SELECTION-####################
        self.timeOptionList = Listbox(self.master,
                                      selectmode=EXTENDED,
                                      height=20,
                                      exportselection=0,
                                      takefocus=0)
        self.timeOptionList.grid(row=2,
                                 column=0,
                                 rowspan=200,
                                 columnspan=1,
                                 sticky=(N, S, E, W),
                                 padx=(5, 0),
                                 pady=5)
        self.timeOptionList.insert(0, self.loadingMsg)
        self.timeOptionList.config(state=DISABLED)

        #################-BUTTONS-##########################
        # user info
        self.infoLabel = Label(self.master,
                               text="[ U S E R  I N F O ]",
                               font=("Helvetica", 16, "bold"))
        self.infoLabel.grid(row=0, column=1, columnspan=2, sticky=E + W)

        # first Name label and input
        self.fnameLabel = Label(self.master,
                                text="First: ",
                                font=("Helvetica", 12, "bold"))
        self.fnameLabel.grid(row=1, column=1, sticky=W)

        self.fnameEntry = Entry(self.master)
        self.fnameEntry.grid(row=1, column=2, stick=E + W, padx=(0, 5))
        self.fnameEntry.insert(0, self.userInfo["first"])

        # last name label and input
        self.lnameLabel = Label(self.master,
                                text="Last: ",
                                font=("Helvetica", 12, "bold"))
        self.lnameLabel.grid(row=2, column=1, sticky=W)

        self.lnameEntry = Entry(self.master)
        self.lnameEntry.grid(row=2, column=2, stick=E + W, padx=(0, 5))
        self.lnameEntry.insert(0, self.userInfo["last"])

        # email label and entry
        self.emailLabel = Label(self.master,
                                text="Email: ",
                                font=("Helvetica", 12, "bold"))
        self.emailLabel.grid(row=3, column=1, sticky=W)

        self.emailEntry = Entry(self.master)
        self.emailEntry.grid(row=3, column=2, stick=E + W, padx=(0, 5))
        self.emailEntry.insert(0, self.userInfo["email"])

        # showBrowser checkbox
        self.browserVal = IntVar(self.master)
        self.browserVal.set(self.userInfo["browser"])
        self.browser = Checkbutton(self.master,
                                   text="Show web browser",
                                   variable=self.browserVal,
                                   command=self.browser_show,
                                   onvalue=1,
                                   offvalue=0,
                                   font=("Helvetica", 12),
                                   takefocus=0)
        self.browser.grid(row=4, column=2, sticky=W)

        # override checkbox
        self.overrideVal = IntVar(self.master)
        self.overrideVal.set(self.userInfo["override"])
        self.override = Checkbutton(self.master,
                                    text="Override 2hr max",
                                    variable=self.overrideVal,
                                    onvalue=1,
                                    offvalue=0,
                                    font=("Helvetica", 12),
                                    takefocus=0)
        self.override.grid(row=5, column=2, sticky=W)

        # confirm checkbox
        self.confirmVal = IntVar(self.master)
        self.confirmVal.set(self.userInfo["confirm"])
        self.confirm = Checkbutton(self.master,
                                   text="Enable confirm dialog",
                                   variable=self.confirmVal,
                                   onvalue=1,
                                   offvalue=0,
                                   font=("Helvetica", 12),
                                   takefocus=0)
        self.confirm.grid(row=6, column=2, sticky=W)

        # submit button
        self.submit = Button(self.master,
                             text="Submit",
                             command=self.submit_click,
                             takefocus=0)
        self.submit.grid(row=8,
                         column=2,
                         sticky=(N, S, E, W),
                         padx=(0, 5),
                         pady=(0, 5))
        self.submit["state"] = "disabled"

        # loading bar
        self.loadingBar = Progressbar(self.master,
                                      orient=HORIZONTAL,
                                      length=100,
                                      mode='determinate')
        self.loadingBar.grid(row=9,
                             column=2,
                             sticky=(N, S, E, W),
                             padx=(0, 5),
                             pady=(0, 5))
        self.loadingBar["value"] = 10

        # email
        self.emm = Button(self.master,
                          text="email tester",
                          command=self.test_email_click,
                          takefocus=0)
        self.emm.grid(row=10,
                      column=2,
                      sticky=(N, S, E, W),
                      padx=(0, 5),
                      pady=(0, 5))

        # update skeleton GUI, then load data
        self.master.update()
        self.load_data()

        # make sure window on top
        self.master.lift()

        # show welcome message if first load
        if self.userInfo["firstLoad"]:
            tkMessageBox.showinfo(
                "Welcome",
                "Currently, booking multiple rooms is not permitted. You are limited to only booking one room per session. However, booking multiple time slots per room is permitted.\n\nMake sure to update the [ USER INFO ] section with your own name and email. \n\nCreated by Mitchell Pynn "
            )