def load_to_serv(self): """ Загрузить что-то на сервер """ try: file_name: str = filedialog.askopenfilename( initialdir="/home/snorcros", title="Select a File", filetypes=(("Text files", "*.txt*"), ("all files", "*.*"))) if file_name: print(file_name) progressbar = Progressbar(self, orient='horizontal', length=200, mode='indeterminate') progressbar.grid(row=2, column=2) progressbar.config(maximum=100, value=0) load_thread = threading.Thread(target=self.client.load, args=(file_name, )) load_thread.start() progressbar.start(interval=50) while load_thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) file_name = file_name.split(sep='/')[-1] progressbar.stop() progressbar.destroy() ft_done("File " + file_name + " was load to server") self.add_file_to_root(file_name) except ConnectionResetError: ft_error("Server died :c") self.disconnect() except Exception as e: ft_error(e)
def save(self, file_name, row): """ Скачать что-то с сервера """ try: path: str = filedialog.askdirectory( initialdir="/home/snorcros", title="Select a dir for download", mustexist=1) if path: progressbar = Progressbar(self, orient='horizontal', length=150, mode='indeterminate') progressbar.grid(row=row, column=4) progressbar.config(maximum=100, value=0) save_thread = threading.Thread(target=self.client.save, args=(file_name, path)) save_thread.start() progressbar.start(interval=50) while save_thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) progressbar.stop() progressbar.destroy() ft_done("File " + file_name + " was download to " + path) except ConnectionResetError: ft_error("Server died :c") self.disconnect() except Exception as e: ft_error(e)
def moveFiles(): # creating the folders if images: createIfNotExist(f'{filePath}/Images') if zips: createIfNotExist(f'{filePath}/Zip') if docs: createIfNotExist(f'{filePath}/Docs') if medias: createIfNotExist(f'{filePath}/Media') if softwares: createIfNotExist(f'{filePath}/Software') if extras: createIfNotExist(f'{filePath}/Extras') # moving files to respective folders for image in images: shutil.move(f"{filePath}/{image}", f"{filePath}/Images/{image}") for zip in zips: shutil.move(f"{filePath}/{zip}", f"{filePath}/Zip/{zip}") for doc in docs: shutil.move(f"{filePath}/{doc}", f"{filePath}/Docs/{doc}") for media in medias: shutil.move(f"{filePath}/{media}", f"{filePath}/Media/{media}") for software in softwares: shutil.move(f"{filePath}/{software}", f"{filePath}/Software/{software}") for extra in extras: shutil.move(f"{filePath}/{extra}", f"{filePath}/Extras/{extra}") progress = Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.place(x=70, y=300) for i in range(1, 100, 1): progress['value'] = i root.update_idletasks() time.sleep(0.02) progress['value'] = 100 progress.destroy() doneLabel = Label(root, image=tickPhoto, bg="white") doneLabel.place(x=180, y=320) resultLabel = Label(root, text="Done !!", font=('arial', 16, 'bold'), bg="white", fg="green") resultLabel.place(x=180, y=380)
def readFile(filename, master): """Reads from filename and converts it into a list of strings.""" # progress bar to show progress to user progress = Progressbar(master, orient='horizontal', length=400, mode='determinate') progress.pack(side=BOTTOM, padx=5, pady=5) # Placment and padding progress['value'] = 25 # update progress bar value master.update() # update the window list = pdfparser(filename) # get PDF formatted as text progress['value'] = 50 # update the value after 50% of work completed master.update() # update the window # fill in spaces to the PDF text for x in range(0, len(list)): if len(list) > x and filter(list[x]): list = list[0:x:] + ' ' + list[x + 1::] progress['value'] = 75 # update value to 75% completion master.update() # update the window list = list.split() progress['value'] = 100 # update to 100% completion master.update() # update window time.sleep(5) # sleep so user can see completion rate of 100% progress.destroy() # destroy progress bar master.update() # update the window return list
def create_npz(): #the size of the pictures target_size = (112, 112) source = filedialog.askdirectory(title="select source image folder") + "/" files = [('npz Files', '*.npz')] destination = filedialog.asksaveasfile(filetypes=files, defaultextension=files) # get all the file names file_list = glob.glob(source + '*.jpg') file_list.extend(glob.glob(source + '*.jpeg')) file_list.extend(glob.glob(source + '*.png')) # set up the image and names array images = [] file_names = [] list_length = len(file_list) #set up temporary progress bar and message temp_lbl = Label(console_frame, text="creating npz file") temp_lbl.grid(column=0, row=8, padx=5, pady=5) progress = Progressbar(console_frame, orient=HORIZONTAL, length=600, mode='determinate') progress.grid(column=0, row=9, padx=5, pady=5) for i in range(list_length): print(str(i), str(i / list_length) + "% done") #update progress bar done = int((i / list_length) * 60) progress['value'] = done window.update() try: read = cv2.imread(file_list[i]) shape_length = len(np.shape(read)) #if image is grayscale if shape_length < 3: img_arr = cv2.cvtColor(read, cv2.COLOR_GRAY2BGR) #if image is a png elif shape_length > 3: img_arr = read[:, :, 0:3] #if regular jpg image else: img_arr = read resize = cv2.resize(img_arr, target_size) images += [resize] file_names += [file_list[i]] except: print("image read error trying another image") continue #remove tempory windows progress.destroy() temp_lbl.configure(text="converting images to numpy arrays") image = np.array(images) temp_lbl.configure(text="converting file paths to numpy arrays") file_names = np.array(file_names) temp_lbl.configure(text="saving arrays") np.savez(destination.name, images=images, file_names=file_names) temp_lbl.destroy()
def ipFinder(self, text, Lookup_ipaddr, ip): Lookup_ipaddr.destroy() # ip = input(" Adresse IP: ") # Progress bar widget progress = Progressbar(self, orient=HORIZONTAL, length=200, mode='determinate') progress.place(x=350, y=300) l2 = Label(self, text=" Locating {0}...".format(ip)) l2.place(x=350, y=200) # print("\n"+wait+" Locating '%s'..." % (ip)) TABLE_DATA = [] url = "http://ip-api.com/json/" data = requests.get(url + ip).content.decode('utf-8') values = json.loads(data) progress['value'] = 20 self.update_idletasks() time.sleep(0.1) status = values['status'] if status != "success": messagebox.showerror("Invalid!", " Adresse IP invalid.") progress['value'] = 50 self.update_idletasks() time.sleep(0.1) progress.destroy() l2.destroy() else: text.insert(END, "[ %s ]" % (ip)) text.insert(END, "\n IP: " + ip) # text.insert(END,"\n Hostname: " + values['ipName']) text.insert(END, "\n ISP: " + values['isp']) text.insert(END, "\n Organisation: " + values['org']) text.insert(END, "\n Pays: " + values['country']) text.insert(END, "\n Region: " + values['region']) text.insert(END, "\n Ville: " + values['city']) localisation = str(values['lat']) + ',' + str(values['lon']) text.insert(END, "\n Localisation: " + localisation) text.insert( END, "\n Maps: https://www.google.fr/maps?q=%s" % (localisation)) progress['value'] = 100 self.update_idletasks() time.sleep(0.1) progress.destroy() l2.destroy()
def progress(self, column, thread): progressbar = Progressbar(self, orient='horizontal', length=150, mode='indeterminate') progressbar.grid(column=column) progressbar.config(maximum=100, value=0) progressbar.start() while thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) progressbar.stop() progressbar.destroy()
def uploadFiles(): progbar = Progressbar(main, orient=HORIZONTAL, length=200, mode='determinate') progbar.grid(row=5, columnspan=3, pady=10) for i in range(50): if progbar['value'] == 66 or progbar['value'] == 90: time.sleep(0.5) root.update_idletasks() progbar['value'] += 2 time.sleep(0.02) progbar.destroy() tkinter.Label(main, text='Upload Successful!', fg='green').grid(row=5, columnspan=3, pady=10)
class LoadingContainer(ttk.Frame): def __init__(self, parent, model): super(LoadingContainer, self).__init__(parent) self.model = model self.progressBar = Progressbar(self, orient=ttk.HORIZONTAL, length=self.model.getMaxValue(), mode='determinate', style="red.Horizontal.TProgressbar") self.progressBar.pack(side=ttk.TOP, fill=ttk.X, expand=1) def refresh(self): self.progressBar["value"] = self.model.getValue() def destroy(self): print("destroy") self.progressBar.destroy()
def callback(): progress = Progressbar(root, orient=HORIZONTAL, length=100, mode='determinate') progress.pack() progress.place(x=10, y=200) request = urllib.request.urlopen(url) filename = str( file_name_field.get()) ##filename will be the basepath of url meta = request.info( ) ## get information from request object used for determining size of content file_size = int(meta['Content-Length']) buffer_size = file_size / segments file_name1.configure(text="Filename: " + filename) print("File size : {0:.2f}".format(float( (file_size / 1024) / 1024))) ## get file size in MB file_download_size.configure( text="File Size: {0:.2f} MB".format((file_size / 1024) / 1024)) total_download = 0 fd = open(filename, 'wb') ## save file to current working directory while total_download != file_size: buffer = request.read( int(buffer_size)) ## reading files upto buffer_size fd.write(buffer) total_download += len(buffer) cur_download.configure(text="Downloaded {0}%".format( math.trunc((int(total_download) / int(file_size)) * 100))) progress['value'] = math.trunc( (int(total_download) / int(file_size)) * 100) ## To retrieve percentage of download print("Download success") fd.close() file_download_size.destroy() file_name1.destroy() progress.destroy() cur_download.destroy() messagebox.showinfo( "File Downloaded", "Your file {0} has been saved in current directory".format( filename))
def initialize(): progressbar = Progressbar(root, orient=HORIZONTAL, length=100, mode='indeterminate') progressbar.pack() progressbar.start(10) print("starting") try: filepath = open("path.txt") file = open(filepath.read()) except: file = open(easygui.fileopenbox()) filepath = open("path.txt", "w") filepath.write(file.name) print("threading url") with concurrent.futures.ThreadPoolExecutor() as exe: exe.map(create_urls, file) print("done creating urls") with concurrent.futures.ThreadPoolExecutor() as exe: exe.map(update_printers, printers) print("done") finish = time.perf_counter() print(f'finished in {round(finish-start,2)} seconds') root_frame.title(f'Printer Stats {datetime.now()}') print(len(root.winfo_children())) for frames in printer_frames: frames.destroy() printer_frames.clear() create_frames() progressbar.stop() progressbar.destroy()
class MainWindow(tk.Tk): def __init__(self): super().__init__() self.title('School Lookup') self.geometry("300x130") self.protocol("WM_DELETE_WINDOW", self.on_exit) self.grid_columnconfigure(0, weight=1) # self.container = tk.Frame(self) choice_label = tk.Label(background='blue', text='Choose the type of school', fg='white', font=('Helvetica', 20)).grid(sticky='ew') self.buttons() self.percent_str = tk.StringVar(self, "In progress... ") self.percent = tk.Label(self, textvariable=self.percent_str, anchor=tk.W).grid(row=2, column=0) self.progress = Progressbar(self, orient=tk.HORIZONTAL, maximum=100, mode='indeterminate', length=150) self.progress.grid(row=3, column=0, rowspan=True) self.progress.start() self.update() mp.set_start_method('spawn') self.q = mp.Queue() self.ca_schools_process = mp.Process(target=self.q.put( get_CA_college_schools()), name="ca_schools_process") start = time.time( ) # assigns the time we start thread of fetching schools self.ca_schools_process.start() self.ca_schools_process.join() print("Elapsed time: {:.10f}s".format(time.time() - start)) self.after(1000, self._close_progress_bar()) self.update() self.CA_colleges = self.q.get(0) def on_exit(self): ''' This function opens a message box asking if the user wants to quit Then quits out of the program if the user clicks yes ''' if tkmb.askyesno("Exit", "Do you want to quit the application?"): self.quit() def _close_progress_bar(self): ''' This function gets rid of the progress bar in the main and puts the state of the buttons back to normal ''' self.progress.stop() self.progress.destroy() self.percent_str.set("Done ...") self.config(cursor="") self.by_public_button["state"] = "normal" self.by_private_button["state"] = "normal" self.by_both_botton["state"] = "normal" def buttons(self): ''' This function creates the buttons for the Main Window Buttons are intially disabled until the progressbar is destroyed ''' buttons_frame = tk.Frame(self) buttons_frame.grid_columnconfigure(0, weight=1) buttons_frame.grid_rowconfigure(1, weight=1) buttons_frame.grid(row=1, column=0, padx=10, pady=10) self.by_public_button = tk.Button(buttons_frame, text='Public', command=self._public_schools_logic, state="disabled") self.by_public_button.grid(row=0, column=1, sticky='ew', padx=15, pady=10) self.by_private_button = tk.Button(buttons_frame, text='Private', command=self._private_schools_logic, state="disabled") self.by_private_button.grid(row=0, column=2, sticky='ew', padx=15, pady=10) self.by_both_botton = tk.Button( buttons_frame, text="Both", command=self._by_both_school_types_logic, state="disabled") self.by_both_botton.grid(row=0, column=3, sticky='ew', padx=15, pady=10) self.but_about = tk.Button(buttons_frame, text="About", command=self._about_info) self.but_about.grid(row=0, column=4, sticky='ew', padx=15, pady=10) # button1 logic def _public_schools_logic(self): ''' function call for public schools button ''' self.by_public_button['state'] = 'disabled' self.config(cursor="wait") self.update() public_schools = [ (str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self.CA_colleges if i['school.ownership'] == 1 ] public_schools = sorted(public_schools) # print(public_schools) # print(len(public_schools)) # 31 dialogWin = DialogWin(self, *public_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_process(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_public_button['state'] = 'normal' # button2 logic def _private_schools_logic(self): ''' function call for private schools button ''' self.by_private_button['state'] = 'disabled' self.config(cursor="wait") self.update() private_schools = [ (str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self.CA_colleges if i['school.ownership'] == 2 ] private_schools = sorted(private_schools) # print(private_schools) # print(len(private_schools)) # 22 dialogWin = DialogWin(self, *private_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_process(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_private_button['state'] = 'normal' # button3 logic def _by_both_school_types_logic(self): ''' function call for all schools button ''' self.by_both_botton['state'] = 'disabled' self.config(cursor="wait") self.update() all_schools = [(str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self.CA_colleges] all_schools = sorted(all_schools) # print(all_schools) # print(len(all_schools)) # 58 dialogWin = DialogWin(self, *all_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_process(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_both_botton['state'] = 'normal' # button4 logic def _about_info(self): ''' button to credit the developers ''' credits = "Credits:\nSergio Chairez\nMaksym Sagadin" tkmb.showinfo("Credits", credits) def school_process(self, id_list): ''' function that will thread the list of schools and add to a queue, append to a list and return a list of schools after being threaded ''' self.temp_list = [] pool = mp.Pool(processes=len(id_list)) if len(id_list) != 0: results = pool.map(get_one_school_info, id_list) pool.close() pool.join() self.temp_list.append(results) return results
def searchAdresse(self, text, Lookup_addr, adresse, codemonpays): Lookup_addr.destroy() # adresse = input(" Adresse: ") # clear() # Progress bar widget progress = Progressbar(self, orient=HORIZONTAL, length=200, mode='determinate') progress.place(x=600, y=300) l2 = Label(self, text=" Searching {0}...".format(adresse)) l2.place(x=350, y=200) # print("\n"+wait+" Recherche '%s'..." % (adresse)) headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'referrer': 'https://google.com', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9', 'Pragma': 'no-cache' } progress['value'] = 20 self.update_idletasks() time.sleep(0.1) if codemonpays == "FR": # search PageBlanche url = "https://www.pagesjaunes.fr/pagesblanches/recherche?quoiqui=&ou=" requete = requests.get(url + adresse, headers=headers) searchPJ(progress, self, text, requete) progress['value'] = 80 self.update_idletasks() time.sleep(0.1) elif codemonpays == "CH": # search tel.local.hc url = "https://tel.local.ch/fr/q?ext=1&name=&company=&street={}&city=&area=" searchLocalCH(progress, self, text, url.format(adresse)) progress['value'] = 80 self.update_idletasks() time.sleep(0.1) else: # Recherche FR url = "https://www.pagesjaunes.fr/pagesblanches/recherche?quoiqui=&ou=" requete = requests.get(url + adresse, headers=headers) searchPJ(progress, self, text, requete) progress['value'] = 60 self.update_idletasks() time.sleep(0.1) # Recherche CH url = "https://tel.local.ch/fr/q?ext=1&name=&company=&street={}&city=&area=" searchLocalCH(progress, self, text, url.format(adresse)) progress['value'] = 80 self.update_idletasks() time.sleep(0.1) progress['value'] = 100 self.update_idletasks() time.sleep(0.1) progress.destroy() l2.destroy()
def ow_frames(input_criteria, opened_files, data_frames, auto_open_var, output_type, file_list, root2=False, func=0, file_name='default'): """ Search Open Files by Input Criteria and output file :param input_criteria: Search Column and Search Item(s) :param opened_files: List of opened files with Checkbutton variables :param data_frames: list of open files(classes) :param auto_open_var: Main window Checkbutton variable for Auto-Open :param output_type: type of output - set to xlsx for a while :param file_list: Search Order List """ def get_checked_l(): checked_list = [] for file in file_list: # Iterate through DataFrames using i as index ind = file_list.index(file) if opened_files[ind][2].get() == 1: checked_list.append(file) return checked_list start = time.time() new_output = [] # Search results per DataFrame if not _test: root = Frame(root2) progress = Progressbar(root, orient=HORIZONTAL, length=300, mode='determinate') progress.pack(fill=X) v = StringVar() Label(root, textvariable=v).pack() root.pack() if func == 0 or func == 3: if func == 0: print('Searching:\n' + input_criteria[1][1].get()) search_column = (input_criteria[0][1].get()).strip() out_d_and_n, zeros_dict, font_type_size, col_width, dec_rules,\ dec_place = GenFuncs.get_out_opts(input_criteria, search_column,output_type) # Load Settings elif func == 3: out_d_and_n, zeros_dict, font_type_size, col_width, dec_rules,\ dec_place = GenFuncs.get_out_opts(input_criteria, input_criteria[0],output_type, func=1, file_name=file_name) # Load Settings checked_l = get_checked_l() for file in checked_l: ind = file_list.index(file) if not _test: progress_bar_ind = checked_l.index(file) progress['value'] = (( (progress_bar_ind + 1) / len(checked_l)) * 100) / 2 v.set("Searching : " + GenFuncs.strip_dir(file)) root.update_idletasks() if func != 3: results = data_frames[ind].search_col( search_column, input_criteria[1][1].get(), zeros_dict) # <-need to move else: results = data_frames[ind].search_col( input_criteria[0], input_criteria[1], zeros_dict) try: if not results.empty: new_output.append(results) except AttributeError: pass else: new_new_output = opened_files output_type = 'xlsx' out_d_and_n, zeros_dict, font_type_size, \ col_width, dec_rules, dec_place = GenFuncs.get_out_opts("", "",output_type, func=1, file_name=file_name) # Load Settings output_directory = os.path.dirname(out_d_and_n) for FP_out in os.listdir( output_directory): # Clean output folder of past search items if FP_out.endswith("FP_out.xlsx"): try: os.remove(os.path.join(output_directory, FP_out)) except PermissionError: pass if dec_place != False: dec_var = '%.' + str(dec_place) + 'f' else: dec_var = "%.2f" if not _test: v.set("Formatting Output") root.update_idletasks() try: if func == 0 or func == 3: try: new_new_output = pd.concat(new_output, axis=0, sort=False, ignore_index=True) except: print("No results") if not _test: progress.destroy() v.set("No results") root.update_idletasks() time.sleep(2) root.destroy() return #var_file = shelve.open(os.path.join(os.path.expanduser('~'),'var_file')) #try: # plug_dicts = var_file['plug_lists'] # var_file.close() # for key, value in plug_dicts.items(): # if value[0] == 1: # new_new_output = value[1].run(new_new_output) #except KeyError: # var_file.close() #print('fail retrieve_info') cols_index = [] for col in new_new_output: cols_index.append(col) if output_type == 'csv': new_new_output.to_csv(out_d_and_n, index=False) elif output_type == 'xlsx': writer_orig = pd.ExcelWriter(out_d_and_n, engine='xlsxwriter') new_new_output.to_excel(writer_orig, index=False, sheet_name='SearchOutput', float_format=dec_var) workbook = writer_orig.book worksheet = writer_orig.sheets['SearchOutput'] size = 10 f_rule_cnt = len(font_type_size) + len(col_width) + len( dec_rules) crnt_rule = 0 if font_type_size != {}: # Set Global Font Size / Type try: size = int(list(font_type_size.values())[0]) if size != False: workbook.formats[0].set_font_size(size) if list(font_type_size.keys())[0] != False: workbook.formats[0].set_font_name( list(font_type_size.keys())[0]) if not _test: progress['value'] = (( (crnt_rule / f_rule_cnt) * 100) / 2) + 50 crnt_rule += 1 v.set(v.get() + ".") root.update_idletasks() except IndexError: pass if len(col_width) > 0: # Set Column / Widths for rule in col_width.items(): worksheet.set_column(rule[0], int(rule[1])) if not _test: progress['value'] = (( (crnt_rule / f_rule_cnt) * 100) / 2) + 50 crnt_rule += 1 v.set(v.get() + ".") root.update_idletasks() try: writer_orig.save() except Exception as e: print(e) print("File with same criteria already open?") if auto_open_var.get() == 1: try: if platform == "linux" or platform == "linux2": opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, out_d_and_n]) else: os.startfile(out_d_and_n, 'open') except: print( 'Error while trying to open application\nPlease set default xlsx application' ) end = time.time() print('-------' + str(end - start) + '-------') else: end = time.time() print('-------' + str(end - start) + '-------') print('done') if not _test: root.destroy() except PermissionError as e: print(str(e)[:28] + ": Close File Before Searching")
class RedditApp(Frame): def __init__(self, master=None): """ Initialize the main application Frame and load it with other widgets. """ super().__init__(master) self.root = master self.pack() self.setup_main_frame() self.create_menubar() self.create_widgets() def setup_main_frame(self): self.root.resizable(0, 0) self.root.wm_title('(sub)Reddit Downloader') def create_menubar(self): menubar = Menu(self.root) menubar.add_command(label='About', command=AboutWindow.about) menubar.add_command(label='Exit', command=self.root.quit) self.root.config(menu=menubar) def create_widgets(self): """ Create widgets to populate the applications frame. """ # URL, Pages, Destination paths_frame = Frame(self) lbl_url = Label(paths_frame, text='URL:') lbl_pages = Label(paths_frame, text='Pages:') lbl_destination = Label(paths_frame, text='Destination:') lbl_pages_help = Label(paths_frame, text='(Leave zero to crawl all pages)') self.url_var = StringVar() self.pages_var = IntVar() self.destination_var = StringVar() url = Entry(paths_frame, textvariable=self.url_var) pages = Entry(paths_frame, textvariable=self.pages_var) destination = Entry(paths_frame, textvariable=self.destination_var) btn_chooser = Button(paths_frame, text='Destination', command=self.choose_directory) pad_x = 5 pad_y = 7 r = 0 lbl_url.grid(row=r, column=0, sticky=E, padx=pad_x, pady=pad_y) url.grid(row=r, column=1) r += 1 lbl_pages.grid(row=r, column=0, sticky=E) pages.grid(row=r, column=1, padx=pad_x, pady=pad_y) lbl_pages_help.grid(row=r, column=2) r += 1 lbl_destination.grid(row=r, column=0, sticky=E) destination.grid(row=r, column=1, padx=pad_x, pady=pad_y) btn_chooser.grid(row=r, column=2, sticky=E + W) paths_frame.pack(side=TOP, padx=10, pady=10) # Download button download_frame = Frame(self) self.btn_download = Button(download_frame, text='Download', command=self.download_reddit) self.btn_download.pack(padx=10, pady=10) download_frame.pack(side=TOP) # Progress label progress_info = Frame(self) self.lbl_progress_info = Label(progress_info, text='') self.lbl_progress_info.pack(padx=10, pady=10) progress_info.pack(side=TOP) def add_progress_bar(self): """ Add progress bar to root frame. """ self.progress_frame = Frame(self) self.progress_bar = Progressbar(self.progress_frame, orient='horizontal', length=400, mode='indeterminate') self.progress_bar.pack(padx=10, pady=10) self.progress_frame.pack(side=TOP) def remove_progress_bar(self): """ Remove progress bare from root frame. """ self.progress_bar.destroy() self.progress_frame.destroy() def change_progress_label(self, text): """ Change text of progress bar label. """ self.lbl_progress_info.configure(text=text, fg='red', font=(font.BOLD)) def choose_directory(self): """ Update the destination path entry filed with the chosen path. """ destination_path = filedialog.askdirectory(initialdir='~') self.destination_var.set(destination_path) def download_reddit(self): """ Download images from subreddit. """ try: self.reddit = Reddit(self.url_var.get(), self.pages_var.get()) except RedditException: messagebox.showerror('Error', 'Please input valid link') return except TclError: messagebox.showerror('Error', 'Please input only whole numbers') return except Exception as e: print(e) messagebox.showerror('Error', 'Something went wrong with Reddit.') return try: self.downloader = Downloader(self.reddit, self.destination_var.get()) except DownloaderException: messagebox.showerror('Error', 'Invalid download path') return except Exception as e: print(e) messagebox.showerror('Error', 'Something went wrong with Downloader.') return self.btn_download.configure(text='Cancel', command=self.cancel_download) self.change_progress_label('Fetching data...') self.add_progress_bar() self.progress_bar.start() self.queue = Queue() self.reddit_listener = RedditListener() self.reddit.register(self.reddit_listener) self.downloader_listener = DownloaderListener() self.downloader.register(self.downloader_listener) DownloadThread(self.queue, self.reddit, self.downloader).start() self.root.after(100, self.process_queue) def process_queue(self): """ Stop the progress bar if the thread has yielded control. If download was canceled, re-enable download button only after thread has yielded control. Reset progress bar and download button, and unregister all listeners when downloading is finished or canceled. """ try: msg = self.queue.get(0) if self.btn_download['text'] == 'Cancel': # self.reddit.fetch = True # self.downloader.downloading = True self.btn_download.configure(text='Download', command=self.download_reddit) self.remove_progress_bar() self.change_progress_label('Download finished.') if self.btn_download['state'] == DISABLED: self.btn_download.configure(state=NORMAL) self.reddit.unregister() self.downloader.unregister() print(msg) except queue.Empty: if getattr(self.reddit_listener, 'fetched', None): print(self.reddit_listener.maximum) self.progress_bar.configure(mode='determinate') self.progress_bar['value'] = 0 self.progress_bar['maximum'] = self.reddit_listener.maximum self.reddit_listener.fetched = False if (getattr(self.downloader_listener, 'currently_at', None) and self.downloader.downloading): print(self.downloader_listener.currently_at) self.progress_bar[ 'value'] = self.downloader_listener.currently_at self.root.after(100, self.process_queue) def cancel_download(self): """ Cancel fetching or downloading process. """ self.reddit.fetch = False self.downloader.downloading = False self.btn_download.configure(text='Download', command=self.download_reddit) self.remove_progress_bar() self.change_progress_label('Download canceled.') self.btn_download.configure(state=DISABLED)
class App(): def __init__(self): # Create app self.root = tk.Tk() self.root.grid_propagate(0) # global styles config = json.loads(open('src/config.json').read()) themeId = config['activeThemeId'] theme = list(filter(lambda x: config['themes'][x]['themeId'] == themeId, config['themes']))[0] self.globalStyles = config['themes'][theme]['style'] self.backgroundColor = self.globalStyles['backgroundColor'] self.foregroundColor = self.globalStyles['foregroundColor'] self.hoverColor = self.globalStyles['hoverColor'] self.fontColor = self.globalStyles['fontColor'] self.textEntryColor = self.globalStyles['textEntryColor'] self.starColor = self.globalStyles['starColor'] self.padl = 15 # tk styles self.textBorderColor = self.globalStyles['textBorderColor'] self.textHighlightColor = self.globalStyles['textHighlightColor'] # ttk styles classes self.style = ttk.Style() self.style.configure("BW.TCheckbutton", foreground=self.fontColor, background=self.backgroundColor, bordercolor=self.backgroundColor, side='LEFT') self.style.configure('TCombobox', background=self.backgroundColor, bordercolor=self.backgroundColor, relief='flat', lightcolor=self.backgroundColor, darkcolor=self.backgroundColor, borderwidth=4, foreground=self.foregroundColor) # App parameters self.root.title('Hazus Export Tool') self.root_h = 480 self.root_w = 330 self.root.geometry(str(self.root_w) + 'x' + str(self.root_h)) windowWidth = self.root.winfo_reqwidth() windowHeight = self.root.winfo_reqheight() # Gets both half the screen width/height and window width/height positionRight = int(self.root.winfo_screenwidth()/2 - windowWidth) positionDown = int(self.root.winfo_screenheight()/3 - windowHeight) # Positions the window in the center of the page. self.root.geometry("+{}+{}".format(positionRight, positionDown)) self.root.resizable(0, 0) self.root.configure(background=self.backgroundColor, highlightcolor='#fff') #App images self.root.wm_iconbitmap('src/assets/images/HazusHIcon.ico') self.img_data = ImageTk.PhotoImage(Image.open("src/assets/images/data_blue.png").resize((20,20), Image.BICUBIC)) self.img_edit = ImageTk.PhotoImage(Image.open("src/assets/images/edit_blue.png").resize((20,20), Image.BICUBIC)) self.img_folder = ImageTk.PhotoImage(Image.open("src/assets/images/folder_icon.png").resize((20,20), Image.BICUBIC)) # Init dynamic row self.row = 0 def updateProgressBar(self): with open(self.logFile) as f: log = json.loads(f.read()) msg = log['log'][-1]['message'] self.label_progress.config(text=msg) self.root.update_idletasks() self.progress['value'] += 13 def browsefunc(self): self.output_directory = filedialog.askdirectory() self.input_studyRegion = self.dropdownMenu.get() self.text_outputDir.delete("1.0",'end-1c') if len(self.input_studyRegion) > 0: self.text_outputDir.insert("1.0",self.output_directory + '/' + self.input_studyRegion) self.root.update_idletasks() else: self.text_outputDir.insert("1.0",self.output_directory) self.root.update_idletasks() def on_field_change(self, index, value, op): try: self.input_studyRegion = self.dropdownMenu.get() self.output_directory = str(self.text_outputDir.get("1.0",'end-1c')) check = self.input_studyRegion in self.output_directory if (len(self.output_directory) > 0) and (not check): self.output_directory = '/'.join(self.output_directory.split('/')[0:-1]) self.text_outputDir.delete('1.0', tk.END) self.text_outputDir.insert("1.0", self.output_directory + '/' + self.input_studyRegion) self.root.update_idletasks() except: pass def getTextFields(self): dict = { 'title': self.text_title.get("1.0",'end-1c'), 'meta': self.text_meta.get("1.0",'end-1c'), 'output_directory': '/'.join(self.text_outputDir.get("1.0",'end-1c').split('/')[0:-1]) } return dict def focus_next_widget(self, event): event.widget.tk_focusNext().focus() return("break") def on_enter_dir(self, e): self.button_outputDir['background'] = self.hoverColor def on_leave_dir(self, e): self.button_outputDir['background'] = self.backgroundColor def on_enter_run(self, e): self.button_run['background'] = '#006b96' def on_leave_run(self, e): self.button_run['background'] = '#0078a9' def run(self): try: if (len(self.dropdownMenu.get()) > 0) and (len(self.text_outputDir.get("1.0",'end-1c')) > 0): if (self.opt_csv.get() + self.opt_shp.get() + self.opt_report.get() + self.opt_json.get()) > 0: self.root.geometry(str(self.root_w)+ 'x' + str(self.root_h + 50)) # self.root.update() self.root.update() sleep(1) # self.busy() func_row = self.row self.inputObj = self.getTextFields() self.inputObj.update({'study_region': self.dropdownMenu.get()}) self.inputObj.update({'opt_csv': self.opt_csv.get()}) self.inputObj.update({'opt_shp': self.opt_shp.get()}) self.inputObj.update({'opt_report': self.opt_report.get()}) self.inputObj.update({'opt_json': self.opt_json.get()}) self.progress = Progressbar(mode = 'indeterminate') self.progress.grid(row=func_row, column=1, pady=(0,10), padx=50, sticky='nsew') func_row += 1 self.label_progress = tk.Label(self.root, text='Initializing', font='Helvetica 8', background=self.backgroundColor, fg=self.foregroundColor) self.label_progress.grid(row=func_row, column=1, sticky='nsew') self.label_progress.config(text='Establishing connection to SQL Server') self.progress['value'] = 0 self.root.update_idletasks() try: t0 = time() hazus = Exporting(self.inputObj) hazus.setup() hazus.logger.create(self.inputObj['output_directory'] + '/' + self.inputObj['study_region']) self.logFile = hazus.logger.logFile hazus.logger.log('Connected to SQL Server') self.updateProgressBar() hazus.logger.log('Retrieving and parsing data') self.updateProgressBar() hazus.getData() hazus.logger.log('Results are ready for outputting') self.updateProgressBar() if self.inputObj['opt_csv']: hazus.logger.log('Creating CSVs') self.updateProgressBar() hazus.toCSV() hazus.logger.log('CSVs created') self.updateProgressBar() if self.inputObj['opt_shp']: hazus.logger.log('Creating Shapefiles') self.updateProgressBar() hazus.toShapefile() hazus.logger.log('Shapefiles created') self.updateProgressBar() if self.inputObj['opt_report']: hazus.logger.log('Creating report (exchanging patience for maps)') self.updateProgressBar() hazus.toReport() hazus.logger.log('Report created') self.updateProgressBar() hazus.logger.log('Finished exporting') self.updateProgressBar() print('Hazus results available locally at: ' + self.inputObj['output_directory'] + '\\' + self.inputObj['study_region']) self.progress['value'] = 100 # self.notbusy() print('Total elasped time: ' + str(time() - t0)) tk.messagebox.showinfo("Hazus", "Success! Output files can be found at: " + self.inputObj['output_directory'] + '/' + self.inputObj['study_region']) self.root.geometry(str(self.root_w) + 'x' + str(self.root_h)) self.progress.destroy() self.label_progress.destroy() hazus.logger.destroy() except: try: self.progress.destroy() self.label_progress.destroy() hazus.logger.destroy() except: print('unable to destroy progress bar and label') self.root.geometry(str(self.root_w) + 'x' + str(self.root_h)) # self.notbusy() tk.messagebox.showerror('Hazus', str(sys.exc_info()[1])) else: tk.messagebox.showwarning('Hazus', 'Select at least one option to export') else: tk.messagebox.showwarning('Hazus', 'Make sure a study region and output directory have been selected') except: self.root.geometry(str(self.root_w) + 'x' + str(self.root_h)) ctypes.windll.user32.MessageBoxW(None, u"Unable to open correctly: " + str(sys.exc_info()[1]), u'Hazus - Message', 0) def build_gui(self): # App body # Required label self.label_required1 = tk.Label(self.root, text='*', font='Helvetica 14 bold', background=self.backgroundColor, fg=self.starColor) self.label_required1.grid(row=self.row, column=0, padx=(self.padl,0), pady=(20, 5), sticky=W) # Scenario name label self.label_scenarioName = tk.Label(self.root, text='Study Region', font='Helvetica 10 bold', background=self.backgroundColor, fg=self.fontColor) self.label_scenarioName.grid(row=self.row, column=1, padx=0, pady=(20, 5), sticky=W) self.row += 1 # Get options for dropdown options = getStudyRegions() self.variable = StringVar(self.root) self.variable.set(options[0]) # default value # Scenario name dropdown menu self.v = StringVar() self.v.trace(W, self.on_field_change) self.dropdownMenu = ttk.Combobox(self.root, textvar=self.v, values=options, width=40, style='H.TCombobox') self.dropdownMenu.grid(row = self.row, column=1, padx=(0, 0), pady=(0,0), sticky=W) self.dropdownMenu.bind("<Tab>", self.focus_next_widget) # Scenario icon self.img_scenarioName = tk.Label(self.root, image=self.img_data, background=self.backgroundColor) self.img_scenarioName.grid(row=self.row, column=2, padx=0, pady=(0,0), sticky=W) self.row += 1 # Output report title self.label_outputTitle = tk.Label(self.root, text='Report Title', font='Helvetica 10 bold', background=self.backgroundColor, fg=self.fontColor) self.label_outputTitle.grid(row=self.row, column=1, padx=0, pady=(20,5), sticky=W) self.row += 1 # Output report title text form self.text_title = tk.Text(self.root, height=1, width=37, font='Helvetica 10', background=self.textEntryColor, relief='flat', highlightbackground=self.textBorderColor, highlightthickness=1, highlightcolor=self.textHighlightColor) self.text_title.grid(row = self.row, column=1, padx=(0, 0), pady=(0,0), sticky=W) self.text_title.bind("<Tab>", self.focus_next_widget) # Title icon self.img_title = tk.Label(self.root, image=self.img_edit, background=self.backgroundColor) self.img_title.grid(row=self.row, column=2, padx=0, pady=(0,0), sticky=W) self.row += 1 # Output report metadata label self.label_outputMetadata = tk.Label(self.root, text='Metadata/Notes', font='Helvetica 10 bold', background=self.backgroundColor, fg=self.fontColor) self.label_outputMetadata.grid(row=self.row, column=1, padx=0, pady=(20, 5), sticky=W) self.row += 1 # Output report metadata text form self.text_meta = tk.Text(self.root, height=1, width=37, font='Helvetica 10', background=self.textEntryColor, relief='flat', highlightbackground=self.textBorderColor, highlightthickness=1, highlightcolor=self.textHighlightColor) self.text_meta.grid(row = self.row, column=1, padx=(0, 0), pady=(0,15), sticky=W) self.text_meta.bind("<Tab>", self.focus_next_widget) # Metadata icon self.img_metadata = tk.Label(self.root, image=self.img_edit, background=self.backgroundColor) self.img_metadata.grid(row=self.row, column=2, padx=0, pady=(0,15), sticky=W) self.row += 1 # Required label self.label_required2 = tk.Label(self.root, text='*', font='Helvetica 14 bold', background=self.backgroundColor, fg=self.starColor) self.label_required2.grid(row=self.row, column=0, padx=(self.padl,0), pady=(0, 0), sticky=W) # Output checkbox label self.label_outputMetadata = tk.Label(self.root, text='Export', font='Helvetica 10 bold', background=self.backgroundColor, fg=self.fontColor) self.label_outputMetadata.grid(row=self.row, column=1, padx=0, pady=(0, 0), sticky=W) # Output checkbox options xpadl = 200 self.opt_csv = tk.IntVar(value=1) ttk.Checkbutton(self.root, text="CSV", variable=self.opt_csv, style='BW.TCheckbutton').grid(row=self.row, column=1, padx=(xpadl,0), pady=0, sticky=W) self.row += 1 self.opt_shp = tk.IntVar(value=1) ttk.Checkbutton(self.root, text="Shapefile", variable=self.opt_shp, style='BW.TCheckbutton').grid(row=self.row, column=1, padx=(xpadl,0), pady=0, sticky=W) self.row += 1 self.opt_report = tk.IntVar(value=1) ttk.Checkbutton(self.root, text="Report", variable=self.opt_report, style='BW.TCheckbutton').grid(row=self.row, column=1, padx=(xpadl,0), pady=0, sticky=W) self.row += 1 self.opt_json = tk.IntVar(value=1) ttk.Checkbutton(self.root, text="Json", variable=self.opt_json, style='BW.TCheckbutton').grid(row=self.row, column=1, padx=(xpadl,0), pady=0, sticky=W) self.row += 1 # Required label self.label_required3= tk.Label(self.root, text='*', font='Helvetica 14 bold', background=self.backgroundColor, fg=self.starColor) self.label_required3.grid(row=self.row, column=0, padx=(self.padl,0), pady=(10, 0), sticky=W) # Output directory label self.label_outputDir = tk.Label(self.root, text='Output Directory', font='Helvetica 10 bold', background=self.backgroundColor, fg=self.fontColor) self.label_outputDir.grid(row=self.row, column=1, padx=0, pady=(10,0), sticky=W) self.row += 1 # Output directory text form self.text_outputDir = tk.Text(self.root, height=1, width=37, font='Helvetica 10', background=self.textEntryColor, relief='flat', highlightbackground=self.textBorderColor, highlightthickness=1, highlightcolor=self.textHighlightColor) self.text_outputDir.grid(row = self.row, column=1, padx=(0, 0), pady=(0,0), sticky=W) self.text_outputDir.bind("<Tab>", self.focus_next_widget) # Output directory browse button self.button_outputDir = tk.Button(self.root, text="", image=self.img_folder, command=self.browsefunc, relief='flat', background=self.backgroundColor, fg='#dfe8e8', cursor="hand2", font='Helvetica 8 bold') self.button_outputDir.grid(row=self.row, column=2, padx=0, pady=(0,0), sticky=W) self.button_outputDir.bind("<Tab>", self.focus_next_widget) self.button_outputDir.bind("<Enter>", self.on_enter_dir) self.button_outputDir.bind("<Leave>", self.on_leave_dir) self.row += 1 # Run button self.button_run = tk.Button(self.root, text='Run', width=5, command=self.run, background='#0078a9', fg='#fff', cursor="hand2", font='Helvetica 8 bold', relief='flat') self.button_run.grid(row=self.row, column=1, columnspan=1, sticky='nsew', padx=50, pady=(30, 20)) self.button_run.bind("<Enter>", self.on_enter_run) self.button_run.bind("<Leave>", self.on_leave_run) self.row += 1 # Run app def start(self): self.build_gui() self.root.mainloop()
class MainWindow(tk.Tk): def __init__(self): super().__init__() self.title('School Lookup') self.geometry("300x130") self.protocol("WM_DELETE_WINDOW", self.on_exit) self.grid_columnconfigure(0, weight=1) # self.container = tk.Frame(self) choice_label = tk.Label(background='blue', text='Choose the type of school', fg='white', font=('Helvetica', 20)).grid(sticky='ew') # represents the URL path and endpoint to the schools dataset self._API_URL_ROOT_AND_ENDPOINT = "https://api.data.gov/ed/collegescorecard/v1/schools" API_KEY = "edT3yUyoeGnLT0mWh6o34mjlpdqeDoIH54p6Zanq" # Sergio's # API KEY = "U3gvOjZeTT85LONZzqWHLsR56JqmaYgc55MQZlKe" # Maksym's self._s = requests.Session() # this ensures that the api key is appended for the entire session. no need to add the api_key every time xD self._s.auth = (API_KEY, '') self.buttons() self.percent_str = tk.StringVar(self, "In progress... ") self.percent = tk.Label(self, textvariable=self.percent_str, anchor=tk.W).grid(row=2, column=0) self.progress = Progressbar(self, orient=tk.HORIZONTAL, maximum=100, mode='indeterminate') self.progress.grid(row=3, column=0, rowspan=True) self.progress.start() self.update() self._CA_colleges = self._get_CA_schools_thread() self.after(1000, self._close_progress_bar()) self.update() def on_exit(self): ''' This function opens a message box asking if the user wants to quit Then quits out of the program if the user clicks yes ''' if tkmb.askyesno("Exit", "Do you want to quit the application?"): self.quit() def _get_CA_schools_thread(self): ''' This function starts a thread to get the school API info ''' q = queue.Queue() ca_schools_thread = threading.Thread(target=q.put( self._get_CA_college_schools()), name="ca_schools_thread") start = time.time( ) # assigns the time we start thread of fetching schools ca_schools_thread.start() ca_schools_thread.join() print("Elapsed time : {:.10f}s".format(time.time() - start)) return q.get() def _close_progress_bar(self): ''' This function gets rid of the progress bar in the main and puts the state of the buttons back to normal ''' self.progress.stop() # self.progress.pack_forget() self.progress.destroy() self.percent_str.set("Done ...") self.config(cursor="") self.by_public_button["state"] = "normal" self.by_private_button["state"] = "normal" self.by_both_botton["state"] = "normal" def _get_CA_college_schools(self): ''' function call for the GET HTTP API Request to get all schools ''' # start = time.perf_counter() parameters = { "school.state": "CA", "school.carnegie_size_setting__range": "12..17", "school.degrees_awarded.predominant": "3", "_fields": "id,school.name,school.city,school.ownership", "per_page": "75" } page = self._s.get(self._API_URL_ROOT_AND_ENDPOINT, params=parameters) return page.json()['results'] def _get_one_school_info(self, school_id): ''' function call for the GET HTTP API Request to get specific school ''' parameters = { "id": school_id, "_fields": "school.name,latest.cost.tuition.in_state,latest.student.enrollment.all,latest.academics.program_percentage.computer,latest.academics.program_percentage.engineering", } page = self._s.get(self._API_URL_ROOT_AND_ENDPOINT, params=parameters) # print(page.url) return page.json()['results'] def buttons(self): ''' This function creates the buttons for the Main Window Buttons are intially disabled until the progressbar is destroyed ''' buttons_frame = tk.Frame(self) buttons_frame.grid_columnconfigure(0, weight=1) buttons_frame.grid_rowconfigure(1, weight=1) buttons_frame.grid(row=1, column=0, padx=10, pady=10) self.by_public_button = tk.Button(buttons_frame, text='Public', command=self._public_schools_logic, state="disabled") self.by_public_button.grid(row=0, column=1, sticky='ew', padx=15, pady=10) self.by_private_button = tk.Button(buttons_frame, text='Private', command=self._private_schools_logic, state="disabled") self.by_private_button.grid(row=0, column=2, sticky='ew', padx=15, pady=10) self.by_both_botton = tk.Button( buttons_frame, text="Both", command=self._by_both_school_types_logic, state="disabled") self.by_both_botton.grid(row=0, column=3, sticky='ew', padx=15, pady=10) self.but_about = tk.Button(buttons_frame, text="About", command=self._about_info) self.but_about.grid(row=0, column=4, sticky='ew', padx=15, pady=10) # button1 logic def _public_schools_logic(self): ''' function call for public schools button ''' self.by_public_button['state'] = 'disabled' self.config(cursor="wait") self.update() public_schools = [ (str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self._CA_colleges if i['school.ownership'] == 1 ] public_schools = sorted(public_schools) # print(public_schools) # print(len(public_schools)) # 31 dialogWin = DialogWin(self, *public_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_threading(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_public_button['state'] = 'normal' # button2 logic def _private_schools_logic(self): ''' function call for private schools button ''' self.by_private_button['state'] = 'disabled' self.config(cursor="wait") self.update() private_schools = [ (str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self._CA_colleges if i['school.ownership'] == 2 ] private_schools = sorted(private_schools) # print(private_schools) # print(len(private_schools)) # 22 dialogWin = DialogWin(self, *private_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_threading(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_private_button['state'] = 'normal' # button3 logic def _by_both_school_types_logic(self): ''' function call for all schools button ''' self.by_both_botton['state'] = 'disabled' self.config(cursor="wait") self.update() all_schools = [(str(i['school.name']) + ", " + str(i['school.city']), i['id']) for i in self._CA_colleges] all_schools = sorted(all_schools) # print(all_schools) # print(len(all_schools)) # 58 dialogWin = DialogWin(self, *all_schools) self.wait_window(dialogWin) id_of_schools_list = dialogWin.buttonClick() if id_of_schools_list is not None: temp_list = self.school_threading(id_of_schools_list) displayWin = DisplayWin(self, *temp_list) self.config(cursor="") self.by_both_botton['state'] = 'normal' # button4 logic def _about_info(self): ''' button to credit the developers ''' credits = "Credits:\nSergio Chairez\nMaksym Sagadin" tkmb.showinfo("Credits", credits) def school_threading(self, id_list): ''' function that will thread the list of schools and add to a queu, append to a list and return a list of schools after being threaded ''' tmp_q = queue.Queue() school_details = [] if len(id_list) != 0: i = 1 for val in id_list: t = threading.Thread(target=lambda arg: tmp_q.put( self._get_one_school_info(arg)), name="single_school_thread" + str(i), args=(val, )) i += 1 school_details.append(t) for t in school_details: t.start() for t in school_details: t.join() temp_list = [] for val in range(len(id_list)): temp_list.append(tmp_q.get(val)) return temp_list
class ResultsWindow(Window): """This window shows the user the images in the category they have chosen, with the option to export the category, view the common tags, or to reject images in the category""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.image_size = 250 self.windows = {"graph_tags.html": PlotWindow} def post(self, category=None, settings=None): """tells database to start downloading images, starts a progress bar while waiting""" if category: if settings: Window.client.add_instruction("send_query_to_db", category, settings) else: Window.client.add_instruction("get_images_from_category", category) self.button = ResultsButton self.form_type = ResultsForm self.category = category self.pbar = Pbar(self.win, mode='indeterminate') self.pbar.grid(padx=50, pady=50) self.pbar.start() t = threading.Thread(target=self.get_images, args=(category, settings)) t.start() def get_images(self, category=None, settings=None): """gets the images from the database and puts them in a list to be replayed""" if category: self.image_data = [] fetching = True while fetching: Window.client.add_instruction("get_image_from_generator", None) image = Window.client.data_queue.get() if not image: fetching = False continue self.image_data.append([image, False]) initialize = True else: frame = self.get_frame_by_id("display") for child in frame.winfo_children(): child.destroy() initialize = False self.win.after(10, lambda: self.generate_images(initialize)) def generate_images(self, initialize=False): """displays the images from the category that the user has chosen""" if initialize: self._initialize() frame = self.get_frame_by_id("display") self.pbar.stop() self.pbar.destroy() columns = 3 self.display_images = [] self.boxes = {} grid_count = 0 print("creating images") for i, image in enumerate(self.image_data): """image[1] is the is_rejected flag""" if image[1]: """if it's rejected we skip this image""" continue canvas = tk.Canvas(frame) """image[0] is the image, image[0][1] is the blob""" img = TagUtility.get_image(image[0][1], self.image_size, "blob") canvas.create_image(0, 0, anchor=tk.N + tk.W, image=img) canvas.grid(row=grid_count // columns, column=grid_count % columns) canvas.bind("<Button-1>", self.image_selected) self.images.append(img) self.display_images.append(canvas) self.boxes[str(canvas)] = (i, grid_count) grid_count += 1 frame.update() def image_selected(self, event): """callback for when an image is clicked, tells the list to reject it and draw a red X on the image to show the user""" img_index, grid_index = self.boxes[str(event.widget)] self.image_data[img_index][1] = True #set the remove flag to true self.display_images[grid_index].create_line(0, 0, 50, 50, fill="red", width=5) self.display_images[grid_index].create_line(50, 0, 0, 50, fill="red", width=5) self.display_images[grid_index].update()
def analyse(): try: description_ext = os.path.splitext( descriptionFilePath)[1].lower() resume_ext = os.path.splitext(resumeFilePath)[1].lower() # Job Description Text Extraction if description_ext == '.docx' or description_ext == '.doc': job_desc = docx2txt.process(descriptionFilePath) elif description_ext == '.pdf': with pdfplumber.open(descriptionFilePath) as pdf: first_page = pdf.pages[0] job_desc = first_page.extract_text() # Resume Text Extraction if resume_ext == '.docx' or resume_ext == '.doc': resume = docx2txt.process(resumeFilePath) elif resume_ext == '.pdf': with pdfplumber.open(resumeFilePath) as pdf: first_page = pdf.pages[0] resume = first_page.extract_text() text = [job_desc, resume] cv = CountVectorizer() count_matrix = cv.fit_transform(text) match = cosine_similarity(count_matrix)[0][1] match = match * 10 result = round(match, 1) if result == 10.0: result = 10 analyseTextLabel = Label(root, justify=LEFT, compound=RIGHT, padx=10, text="Analysing", image=iconPhoto, font=('arial', 18, 'bold'), bg="white", fg="#483D8B") analyseTextLabel.place(x=165, y=420) analysisLabel = Label(root, font=('arial', 12, 'bold'), bg="white") analysisLabel.place(x=250, y=470) progress = Progressbar(root, orient="horizontal", length=300, mode="determinate") progress.place(x=115, y=500) for i in range(1, 100, 1): progress['value'] = i root.update_idletasks() analysisLabel.config(text=str(i) + "%") time.sleep(0.03) progress['value'] = 100 analyseTextLabel.destroy() analysisLabel.destroy() progress.destroy() analyseButton.destroy() headingLabel = Label(root, text="Your ATS Score", font=('arial', 18, 'bold'), bg="white", fg="teal") headingLabel.place(x=170, y=430) if result > 7.0: resultLabel = Label(root, text=f"{result} / 10", font=('arial', 25, 'bold'), bg="white", fg="green") resultLabel.place(x=205, y=480) textLabel = Label( root, text= "Your resume is perfectly aligned with the job description and", font=('arial', 12, 'bold'), bg="white", fg="green") textLabel.place(x=40, y=540) textLabel1 = Label(root, text="is ready for this job.", font=('arial', 12, 'bold'), bg="white", fg="green") textLabel1.place(x=40, y=570) elif result > 4.0 and result < 6.9: resultLabel = Label(root, text=f"{result} / 10", font=('arial', 25, 'bold'), bg="white", fg="#FF8C00") resultLabel.place(x=205, y=480) textLabel = Label( root, text= "Your resume needs a little bit of improvement before", font=('arial', 12, 'bold'), bg="white", fg="#FF8C00") textLabel.place(x=60, y=540) textLabel1 = Label(root, text="applying for this job.", font=('arial', 12, 'bold'), bg="white", fg="#FF8C00") textLabel1.place(x=60, y=570) tipLabel = Label(root, text=f"Tip : {choice}", font=('arial', 10, 'bold'), bg="white") tipLabel.place(x=60, y=620) else: resultLabel = Label(root, text=f"{result} / 10", font=('arial', 25, 'bold'), bg="white", fg="red") resultLabel.place(x=205, y=480) textLabel = Label( root, text= "Your resume does not align with job description and is not", font=('arial', 12, 'bold'), bg="white", fg="red") textLabel.place(x=40, y=540) textLabel1 = Label(root, text="suitable for this job.", font=('arial', 12, 'bold'), bg="white", fg="red") textLabel1.place(x=40, y=570) tipLabel = Label( root, text="Tips : Optimize your resume with keywords.", font=('arial', 10, 'bold'), bg="white") tipLabel.place(x=40, y=610) tipLabel1 = Label( root, text=": Avoid images, charts, and other graphics.", font=('arial', 10, 'bold'), bg="white") tipLabel1.place(x=70, y=630) except: errorLabel = Label(root, text="Error!!", font=('arial', 20, 'bold'), bg="white", fg="red") errorLabel.place(x=225, y=430) if resume_ext != '.docx' or resume_ext != '.doc' or resume_ext != '.pdf' or description_ext != '.docx' or description_ext != '.doc' or description_ext != '.pdf' or not resume or not job_desc: errorLabel1 = Label( root, text="Please select the correct files.", font=('arial', 16, 'bold'), bg="white", fg="red") errorLabel1.place(x=115, y=480) def reset(): descriptionEntry.delete(0, 'end') resumeEntry.delete(0, 'end') textLabel.destroy() headingLabel.destroy() textLabel1.destroy() resultLabel.destroy() tipLabel.destroy() tipLabel1.destroy() errorLabel.destroy() errorLabel1.destroy() analysisButton = Button(root, text=" Analyse ", font=('arial', 12, 'bold'), width=20, bg="#4169E1", fg='#FFFFFF', command=analyse) analysisButton.place(x=160, y=350) resetButton = Button(root, text=" Reset ", font=('arial', 12, 'bold'), width=20, bg="#9370DB", fg='#FFFFFF', command=reset) resetButton.place(x=160, y=350)
class MainView(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs); self.toForeGround ################### init, main config ###################### container = Frame(self, bg=bgColor); container.pack(side="top", fill="both", expand=True); self.ft1 = font.Font(family='Arial', size=11); self.ft2 = font.Font(family='MS Gothic', size=10); self.ft3 = font.Font(family='Arial', size=9); self.ft4 = font.Font(family='Arial', size=10); self.ft5 = font.Font(family='Arial', size=14); self.ft6 = font.Font(family="Courier", size = 9); self.p1 = Page1(container, bg=container["background"]); self.p2 = Page2(container, bg=container["background"]); self.p3 = Page3(container, bg=container["background"]); self.p4 = Page4(container, bg=container["background"]); self.p5 = Page5(container, bg=container["background"]); self.p6 = Page6(container, bg=container["background"]); self.p7 = Page7(container, bg=container["background"]); self.p8 = Page8(container, bg=container["background"]); self.p9 = Page9(container, bg=container["background"]); topBar = Frame(container, bg=topBarColor, width=container.winfo_width() * framewidth, height=topBarHeight); topBar.place(x=0, y=0); self.p1.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p2.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p3.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p4.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p5.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p6.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p7.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p8.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p9.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); close= Button(topBar, text=u"\u2715", command= lambda: self.close(), bg=topBar["background"], bd=0, font = self.ft2, fg=fgColor, activebackground="#940000"); close.place(x = topBar["width"] - topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); minim = Button(topBar, text="_", command= lambda: self.toicon(), bg=topBar["background"], bd=0, font=self.ft2, fg=fgColor, activebackground="#364969"); minim.place(x = topBar["width"] - 2 * topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); label = Label(topBar, text=title, font=self.ft3, bg=topBar["background"], fg=fgColor); label.place(x = 5, y = 0, height= topBar["height"]); #event handlers so the window can be moved topBar.bind("<ButtonPress-1>", self.StartMove); topBar.bind("<ButtonRelease-1>", self.StopMove); topBar.bind("<B1-Motion>", self.OnMotion); label.bind("<ButtonPress-1>", self.StartMove); label.bind("<ButtonRelease-1>", self.StopMove); label.bind("<B1-Motion>", self.OnMotion); close.bind("<Enter>", self.closeEnterBG); close.bind("<Leave>", self.topBarButtonNormalBG); minim.bind("<Enter>", self.minimEnterBG); minim.bind("<Leave>", self.topBarButtonNormalBG); self.master.bind("<Unmap>", self.toiconify); self.master.bind("<Map>", self.todeiconify); ##################### page 1, intro ############################ T1 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T1.place(x=10, y=10); HelpButton = Label(self.p1, text = "help", background=bgColor, fg = hyperlinkColor, font = self.ft5, cursor="hand2"); HelpButton.place(x=8, y=53); underlineFont = font.Font(HelpButton, HelpButton.cget("font")); underlineFont.configure(underline = True); HelpButton.configure(font=underlineFont); HelpButton.bind("<Button-1>", lambda x: self.clickHelp()) T2 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T2.place(x=53, y=55); T1.insert(END, "Welcome to the ELS Scorion tool. Click next to select what tool to use, or press\n"); T2.insert(END, "to learn more about the tool."); T1.configure(state=DISABLED); T2.configure(state=DISABLED); nextButtonP1 = Button(self.p1, text = "Next", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); nextButtonP1.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); nextButtonP1.bind("<Enter>", self.buttonEnterBG); nextButtonP1.bind("<Leave>", self.buttonNormalBG); ################## page 2, task picker ######################### instrLabel = Label(self.p2, text = "Choose what tool to use", bg=self.p2["background"], fg=fgColor, font=self.ft5); instrLabel.place(x= 30, y = 10); buildGroupsButton = Button(self.p2, text = "Build Scorion groups", command=self.p3.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); buildGroupsButton.place(x = 75, y = 48, width = 250, height = 2*nextprevButtonHeight); buildGroupsButton.bind("<Enter>", self.buttonEnterBG); buildGroupsButton.bind("<Leave>", self.buttonNormalBG); splitGroupsButton = Button(self.p2, text = "Split Scorion file", command=self.p4.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); splitGroupsButton.place(x = 75, y = 120, width = 250, height = 2*nextprevButtonHeight); splitGroupsButton.bind("<Enter>", self.buttonEnterBG); splitGroupsButton.bind("<Leave>", self.buttonNormalBG); onlyFileButton = Button(self.p2, text = "Only create Scorion file", command=self.p5.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); onlyFileButton.place(x = 75, y = 192, width = 250, height = 2*nextprevButtonHeight); onlyFileButton.bind("<Enter>", self.buttonEnterBG); onlyFileButton.bind("<Leave>", self.buttonNormalBG); possibleErrorButton = Button(self.p2, text = "Find errors in file", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); possibleErrorButton.place(x = 75, y = 264, width = 250, height = 2*nextprevButtonHeight); possibleErrorButton.bind("<Enter>", self.buttonEnterBG); possibleErrorButton.bind("<Leave>", self.buttonNormalBG); previousButtonP2 = Button(self.p2, text = "Back", command=self.p1.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP2.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP2.bind("<Enter>", self.buttonEnterBG); previousButtonP2.bind("<Leave>", self.buttonNormalBG); ################## page 3, group builder ######################## previousButtonP3 = Button(self.p3, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP3.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP3.bind("<Enter>", self.buttonEnterBG); previousButtonP3.bind("<Leave>", self.buttonNormalBG); courseIdWrap = Frame(self.p3, bg= self.p3["background"]); courseIdWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar = StringVar(); self.courseVar.trace("w", lambda name, index, mode, courseVar=self.courseVar: self.firecallback()); courseIdLabel = Label(courseIdWrap, text = "Course Id:", bg=self.p3["background"], fg=fgColor, font=self.ft4); courseIdLabel.place(x= 0, y = 0, height = topBarHeight); courseId = Entry(courseIdWrap, width= 45, bg=bg2Color, textvariable=self.courseVar,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId.place(x = 65, y = 0, height=topBarHeight); fileWrap = Frame(self.p3, bg =self.p3["background"]); fileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel = Label(fileWrap, text = "File:", bg=self.p3["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 30, y = 0, height = topBarHeight); self.fileVar = StringVar(); self.fileVar.trace("w", lambda name, index, mode, fileVar=self.fileVar: self.firecallback()); self.fileName = Entry(fileWrap, width= 36, textvariable=self.fileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName.place(x = 65, y = 0, height= topBarHeight); #TODO: drag files into the text field self.browse = Button(fileWrap, text="Browse", command=self.load_file, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse.place(x=326, y=0, height = topBarHeight, width=60); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); seperatorWrap = Frame(self.p3, bg = self.p3["background"]); seperatorWrap.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel = Label(seperatorWrap, text="What seperator is used in the file?", bg=self.p3["background"], fg=fgColor, font=self.ft4); optionLabel.place(x = 0, y = 0, height = topBarHeight); optionList = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar = StringVar(); self.sepVar.set(optionList[0][1]); commaButton = Radiobutton(seperatorWrap, text=optionList[0][0], variable = self.sepVar, value=optionList[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton = Radiobutton(seperatorWrap, text=optionList[1][0], variable = self.sepVar, value=optionList[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton.place(x=260, y = topBarHeight + 2, width = 120); optionLabel = Label(self.p3, text="Do you already have a Scorion File?"); scorionCheckWrap = Frame(self.p3, bg = self.p3["background"]); scorionCheckWrap.place(x=10, y = 194, height=topBarHeight, width = framewidth - 20); self.checkVar = IntVar(); scorionCheck = Checkbutton(scorionCheckWrap, text="Create a Scorion file?", var = self.checkVar, font=self.ft4, fg=fgColor, bg=bg2Color, bd=0, highlightthickness = 0, selectcolor=bg2Color, activeforeground=fgColor, activebackground= bg2Color); scorionCheck.select(); scorionCheck.place(x=210, y=0, height=topBarHeight, width = 170); self.goButton = Button(self.p3, text = "Run", command=self.combineFuncs, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButton.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 4, split groups page ######################## previousButtonP4 = Button(self.p4, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP4.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP4.bind("<Enter>", self.buttonEnterBG); previousButtonP4.bind("<Leave>", self.buttonNormalBG); scorFileWrap = Frame(self.p4, bg =self.p4["background"]); scorFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight); fileLabel = Label(scorFileWrap, text = "Scorion File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 0, y = 0, height = topBarHeight); self.scorFileVar = StringVar(); self.scorFileVar.trace("w", lambda name, index, mode, scorFileVar=self.scorFileVar: self.firecallback1()); self.scorFileName = Entry(scorFileWrap, width= 34, textvariable=self.scorFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.scorFileName.place(x = 79, y = 0, height= topBarHeight); self.browse1 = Button(scorFileWrap, text="Browse", command=self.load_file1, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse1.place(x=326, y=0, height = topBarHeight, width=60); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); errFileWrap = Frame(self.p4, bg =self.p4["background"]); errFileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); errLabel = Label(errFileWrap, text = "Error File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); errLabel.place(x= 0, y = 0, height = topBarHeight); self.errFileVar = StringVar(); self.errFileVar.trace("w", lambda name, index, mode, errFileVar=self.errFileVar: self.firecallback1()); self.errFileName = Entry(errFileWrap, width= 36, textvariable=self.errFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.errFileName.place(x = 65, y = 0, height= topBarHeight); self.browse2 = Button(errFileWrap, text="Browse", command=self.load_file2, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse2.place(x=326, y=0, height = topBarHeight, width=60); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); self.goButtonP4 = Button(self.p4, text = "Run", command=self.combineFuncs2, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP4.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 5, only create groups page ################## previousButtonP5 = Button(self.p5, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP5.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP5.bind("<Enter>", self.buttonEnterBG); previousButtonP5.bind("<Leave>", self.buttonNormalBG); courseIdWrap2 = Frame(self.p5, bg= self.p5["background"]); courseIdWrap2.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar2 = StringVar(); self.courseVar2.trace("w", lambda name, index, mode, courseVar2=self.courseVar2: self.firecallback2()); courseIdLabel2 = Label(courseIdWrap2, text = "Course Id:", bg=self.p5["background"], fg=fgColor, font=self.ft4); courseIdLabel2.place(x= 0, y = 0, height = topBarHeight); courseId2 = Entry(courseIdWrap2, width= 45, bg=bg2Color, textvariable=self.courseVar2,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId2.place(x = 65, y = 0, height=topBarHeight); fileWrap2 = Frame(self.p5, bg =self.p5["background"]); fileWrap2.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel2 = Label(fileWrap2, text = "File:", bg=self.p5["background"], fg=fgColor, font=self.ft4); fileLabel2.place(x= 30, y = 0, height = topBarHeight); self.fileVar2 = StringVar(); self.fileVar2.trace("w", lambda name, index, mode, fileVar2=self.fileVar2: self.firecallback2()); self.fileName2 = Entry(fileWrap2, width= 36, textvariable=self.fileVar2,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName2.place(x = 65, y = 0, height= topBarHeight); self.browse3 = Button(fileWrap2, text="Browse", command=self.load_file3, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse3.place(x=326, y=0, height = topBarHeight, width=60); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); seperatorWrap2 = Frame(self.p5, bg = self.p5["background"]); seperatorWrap2.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel2 = Label(seperatorWrap2, text="What seperator is used in the file?", bg=self.p5["background"], fg=fgColor, font=self.ft4); optionLabel2.place(x = 0, y = 0, height = topBarHeight); optionList2 = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar2 = StringVar(); self.sepVar2.set(optionList2[0][1]); commaButton2 = Radiobutton(seperatorWrap2, text=optionList2[0][0], variable = self.sepVar2, value=optionList2[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton2 = Radiobutton(seperatorWrap2, text=optionList2[1][0], variable = self.sepVar2, value=optionList2[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton2.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton2.place(x=260, y = topBarHeight + 2, width = 120); self.goButtonP5 = Button(self.p5, text = "Run", command=self.combineFuncs3, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP5.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 6, progress page ########################### self.cancelButton = Button(self.p6, text = "cancel", command=lambda:sys.exit(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.cancelButton.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.cancelButton.bind("<Enter>", self.buttonEnterBG); self.cancelButton.bind("<Leave>", self.buttonNormalBG); self.progressLabel = Label(self.p6, text = "Working, this might take a couple of minutes...", bg=self.p6["background"], fg=fgColor, font=self.ft1) self.progressLabel.place(x=10, y=36); #TODO: make the progressbar actually progress to the things that are done style = Style(); style.theme_use('alt') style.configure("els.Horizontal.TProgressbar", background=fgColor); self.progress = Progressbar(self.p6, orient=HORIZONTAL, length = framewidth - 20, mode="indeterminate", style="els.Horizontal.TProgressbar", maximum=40); self.progress.place(x=10, y=10); self.progress.start(17); self.closeP6 = Button(self.p6, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); ################### page 7, error page ########################### #TODO: implement full stacktrace instead of only 2 #TODO: or: make a log file of the stacktrace that can be "downloaded" when clicked #TODO: error page is not working correctly anymore; errors are being cut off self.errorLabel = Label(self.p7, text = "Something went wrong, try again or contact Cas", bg=self.p7["background"], fg=errorColor, font=self.ft1); self.errorLabel.place(x=36, y=10); self.errorInfoLabel = Label(self.p7, text = "Error Info:", bg=self.p7["background"], fg=fgColor, font=self.ft1); self.errorInfoLabel.place(x=36, y=50); self.stackTraceStringVar1 = StringVar(); self.stackTraceStringVar2 = StringVar(); self.stackTraceLabel1 = Label(self.p7, textvariable = self.stackTraceStringVar1, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceLabel2 = Label(self.p7, textvariable = self.stackTraceStringVar2, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.stackTraceLabel1.place(x=36, y=70); self.stackTraceLabel2.place(x=36, y=110); self.backToMenu = Button(self.p7, text = "Back to menu", command=self.backtomenu, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.backToMenu.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.backToMenu.bind("<Enter>", self.buttonEnterBG); self.backToMenu.bind("<Leave>", self.buttonNormalBG); self.closeP7 = Button(self.p7, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.closeP7.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP7.bind("<Enter>", self.buttonEnterBG); self.closeP7.bind("<Leave>", self.buttonNormalBG); ################### page 8, find error page ########################### previousButtonP8 = Button(self.p8, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP8.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP8.bind("<Enter>", self.buttonEnterBG); previousButtonP8.bind("<Leave>", self.buttonNormalBG); checkErrFileWrap = Frame(self.p8, bg =self.p8["background"]); checkErrFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = 3*topBarHeight); checkErrLabel = Label(checkErrFileWrap, text = "File to check for Errors:", bg=self.p4["background"], fg=fgColor, font=self.ft4); checkErrLabel.place(x= 0, y = 0, height = topBarHeight); self.checkErrFileVar = StringVar(); self.checkErrFileVar.trace("w", lambda name, index, mode, checkErrFileVar=self.checkErrFileVar: self.firecallback3()); self.checkErrFileName = Entry(checkErrFileWrap, width= 45, textvariable=self.checkErrFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.checkErrFileName.place(x = 2, y = 25, height= topBarHeight); self.browse4 = Button(checkErrFileWrap, text="Browse", command=self.load_file4, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse4.place(x=326, y=25, height = topBarHeight, width=60); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); self.goButtonP8 = Button(self.p8, text = "Run", command=self.p9.lift, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP8.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 9, find error results ########################### previousButtonP9 = Button(self.p9, text = "Back", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP9.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP9.bind("<Enter>", self.buttonEnterBG); previousButtonP9.bind("<Leave>", self.buttonNormalBG); #testing self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, r"M:\ud\os\ssc\imos\bbsup\@ new folder_Surfdrive\7. Scorion\Vakmappen 171804\46597-171804\group_import_no_TAs.txt"); self.errors = errorChecker(self.checkErrFileVar.get()); self.croppedErrors = self.errors[0:7] if (len(self.errors) > 0): Label(self.p9, text = "Found %d possible errors, on the following lines:" %len(self.errors), fg = fgColor, bg = bgColor, font = self.ft1).place(x=16, y=12); openFile = Button(self.p9, text = "Open file", command=lambda: self.clickOpenFile(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); openFile.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); openFile.bind("<Enter>", self.buttonEnterBG); openFile.bind("<Leave>", self.buttonNormalBG); self.drawErrors(); else: Label(self.p9, text = "Found no errors", fg = fgColor, bg = bgColor, font = self.ft5).place(x=10, y=10); ################### finally, show page 1 to start ################ self.p1.show(); ################### window event handlers ########################## def StartMove(self, event): self.master.x = event.x; self.master.y = event.y; def StopMove(self, event): self.master.x = None; self.master.y = None; def OnMotion(self, event): deltax = event.x - self.master.x; deltay = event.y - self.master.y; x = self.master.winfo_x() + deltax; y = self.master.winfo_y() + deltay; self.master.geometry("+%s+%s" % (x, y)); def toForeGround(self): self.master.lift(); def toicon(self): self.master.update_idletasks(); self.master.overrideredirect(False); self.master.iconify(); def toiconify(self, event): self.master.overrideredirect(False); def todeiconify(self, event): self.master.overrideredirect(True); def closeEnterBG(self, event): event.widget.config(bg="#C40000"); def minimEnterBG(self, event): event.widget.config(bg="#455D85") def topBarButtonNormalBG(self, event): event.widget.config(bg=topBarColor); def buttonEnterBG(self, event): event.widget.config(bg=buttonHoverColor); def buttonNormalBG(self, event): event.widget.config(bg=buttonColor); def buttonEnterDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def buttonNormalDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def close(self): self.progress.stop(); self.progress.destroy(); self.master.quit(); ################### other functions ############################## def clickHelp(self): location = "manual.docx"; os.system("start " + location); def clickOpenFile(self): import subprocess; location = self.checkErrFileName.get(); program = resource_path("Notepad++\\notepad++.exe") subprocess.call([program, location]); def showNextErrors(self): startNumber = self.errors.index(self.croppedErrors[0]); self.croppedErrors = self.errors[startNumber + 7:startNumber + 14]; self.drawErrors(); def showPrevErrors(self): startNumber = self.errors.index(self.croppedErrors[0]) self.croppedErrors = self.errors[startNumber - 7:startNumber]; self.drawErrors(); def drawErrors(self): if (len(self.errors) > 7): startNumber = self.errors.index(self.croppedErrors[0]); self.nextErrors = Button(self.p9, text = ">", command=lambda: self.showNextErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); self.prevErrors = Button(self.p9, text = "<", command=lambda: self.showPrevErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); if not (startNumber >= (len(self.errors) - 7)): self.nextErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX + nextprevButtonWidth/2 + 2, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: print("should hide"); self.hideNextButton(); if (startNumber > 0): self.prevErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: self.prevErrors.lower(); cropRange = 22; ErrorWrap = Frame(self.p9, bg = codeBGColor); ErrorWrap.place(x = 56, y = 40, width = framewidth - 72, height = frameheight - topBarHeight - 124) LineWrap = Frame(self.p9, bg = codeBG2Color); LineWrap.place(x=16, y = 40, width = 40, height = frameheight - topBarHeight - 124); for i in range(len(self.croppedErrors)): formattedLine = str((int(self.croppedErrors[i].getLineOccurence()) + 1)) for k in range(3 - len(formattedLine)): formattedLine = "0" + formattedLine; Label(LineWrap, text = formattedLine, bg = codeBG2Color, font = self.ft6, fg = fgColor).place(x = 6, y = 4+40*i) for i in range(len(self.croppedErrors)): sourceLine = self.croppedErrors[i].getSourceLine(); if (len(sourceLine) - self.croppedErrors[i].getColOccurence()) > cropRange: cropped = sourceLine[max(self.croppedErrors[i].getColOccurence() - cropRange, 0):max(self.croppedErrors[i].getColOccurence() + cropRange, 2 * cropRange)] Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = min(round(7.05 * cropRange), round(7.1*self.croppedErrors[i].getColOccurence())), y = 20 + 40*i) Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) else: EOLOccurence = len(sourceLine) - self.croppedErrors[i].getColOccurence() - 1; cropped = sourceLine[self.croppedErrors[i].getColOccurence() - (2 * cropRange - EOLOccurence):] Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = round(7.05*((2*cropRange) - EOLOccurence)), y = 20 + 40*i) def hideNextButton(self): self.nextErrors.place_forget(); def firecallback(self): if len(self.courseVar.get()) == 0 or len(self.fileVar.get()) == 0: self.goButton.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButton.bind("<Enter>", self.buttonEnterDisabledBG); self.goButton.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButton.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButton.bind("<Enter>", self.buttonEnterBG); self.goButton.bind("<Leave>", self.buttonNormalBG); def firecallback1(self): if len(self.scorFileVar.get()) == 0 or len(self.errFileVar.get()) == 0: self.goButtonP4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP4.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP4.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP4.bind("<Enter>", self.buttonEnterBG); self.goButtonP4.bind("<Leave>", self.buttonNormalBG); def firecallback2(self): if len(self.courseVar2.get()) == 0 or len(self.fileVar2.get()) == 0: self.goButtonP5.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP5.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP5.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP5.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP5.bind("<Enter>", self.buttonEnterBG); self.goButtonP5.bind("<Leave>", self.buttonNormalBG); def firecallback3(self): if len(self.checkErrFileVar.get()) == 0: self.goButtonP8.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP8.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP8.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP8.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP8.bind("<Enter>", self.buttonEnterBG); self.goButtonP8.bind("<Leave>", self.buttonNormalBG); def combineFuncs(self): self.p6.lift(); try: self.createGroups(); except Exception as e: self.fireErrorPage(e); return def combineFuncs2(self): self.p6.lift(); try: self.split(); except Exception as e: self.fireErrorPage(e); return def combineFuncs3(self): self.p6.lift(); try: self.createFile(); except Exception as e: self.fireErrorPage(e); return def fireErrorPage(self, e): import traceback; global tb; tb = traceback.format_exc(); traceback.print_exc(); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.p7.lift(); def getStackTrace(self): if len(tb.split("\n")) == 1: return [tb, ""]; elif len(tb.split("\n")) < 4: return [tb.split("\n")[-2].lstrip(), ""]; return [tb.split("\n")[-2].lstrip(), tb.split("\n")[-4].lstrip()]; def load_file(self): self.browse.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse.bind("<Enter>", self.buttonEnterDisabledBG); self.browse.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName.delete(0, END); self.fileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); return def load_file1(self): self.browse1.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse1.bind("<Enter>", self.buttonEnterDisabledBG); self.browse1.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.scorFileName.delete(0, END); self.scorFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse1.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); return def load_file2(self): self.browse2.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse2.bind("<Enter>", self.buttonEnterDisabledBG); self.browse2.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.errFileName.delete(0, END); self.errFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse2.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); return def load_file3(self): self.browse3.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse3.bind("<Enter>", self.buttonEnterDisabledBG); self.browse3.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName2.delete(0, END); self.fileName2.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse3.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); return def load_file4(self): self.browse4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse4.bind("<Enter>", self.buttonEnterDisabledBG); self.browse4.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); return def createGroups(self): course_id = self.courseVar.get(); fileName = self.fileVar.get(); seperator = self.sepVar.get(); write = self.checkVar.get() == 1; groups = getGroups(course_id, fileName, seperator, write); driver = createScorionGroups(groups, course_id); #throws windowserror driver.quit(); self.finish(); def createFile(self): course_id = self.courseVar2.get(); fileName = self.fileVar2.get(); seperator = self.sepVar2.get(); getGroups(course_id, fileName, seperator, True); self.finish(); def split(self): scorFile = self.scorFileName.get(); errFile = self.errFileName.get(); splitGroups(scorFile, errFile); self.finish(); def finish(self): self.progress["mode"] = 'determinate'; self.progress.update_idletasks(); self.progress.stop(); self.progressLabel["text"] = "Finished!"; self.cancelButton["text"] = "Back to menu"; self.closeP6.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP6.bind("<Enter>", self.buttonEnterBG); self.closeP6.bind("<Leave>", self.buttonNormalBG) self.cancelButton.config(command=self.backtomenu); def backtomenu(self): self.scorFileVar.set(""); self.errFileVar.set(""); self.courseVar.set(""); self.courseVar2.set(""); self.fileVar.set(""); self.fileVar2.set(""); self.sepVar.set(","); self.sepVar2.set(","); self.p2.lift(); self.cancelButton.config(text = "cancel", command=exit); self.closeP6.place_forget(); self.progressLabel["text"] = "Working, this might take a couple of minutes..."; self.progress["mode"] = 'indeterminate';
def search(self, url): # queue to share between gui and threads q = queue.Queue() self.helper.hidefilters() if SearchFrame.content is None: searchprogress = Progressbar(self, orient="horizontal", style='mongo.Horizontal.TProgressbar', length=700, mode="indeterminate") searchprogress.place(relx=.5, rely=.8, anchor=CENTER) searchprogress.start() proglabel = Label(self, text="Fetching Results...", font="Times 14", bg="#282828", fg="#FFFFFF") proglabel.place(relx=.5, rely=.765, anchor=CENTER) # get additional info from filters if they exist url = self.helper.addurlfilters(url) # start thread to get data from url thread = GetDataThread(url, q) thread.start() # wait until thread is done, then get data from queue self.updateuntildata(q, searchprogress) self.data = q.get(0) # get rid of progress bar searchprogress.destroy() proglabel.destroy() else: self.data = SearchFrame.content # make sure search didn't time out if self.data != "ReadTimeout": self.master.master.updateque.queue.clear() # start thread to analyze data and repeat process self.analysisthread = ResultsAnalysisThread( self.data, self.master.master.analyzer, q, self.resultTopics) self.analysisthread.start() self.resultTopics.config(text="Processing Data...(0%)") self.processingloop('percent') self.processingloop('dots') self.helper.hidesearch() style = Style(self) style.configure("Treeview", rowheight=30, fieldbackground='#bdbdbd') style.configure("Treeview.Heading", background="#707070", rowheight=60, font="Ariel 14 bold") self.tree = Treeview(self, columns=('date', 'title'), selectmode='browse') self.tree['show'] = 'headings' self.tree.column('date', width=100, anchor=CENTER) self.tree.heading('date', text="Date", command=lambda: self.treeview_sort_column( self.tree, 'date', False)) self.tree.column('title', width=900) self.tree.heading('title', text="Article Title", anchor=W, command=lambda: self.treeview_sort_column( self.tree, 'title', False)) self.tree.heading('title', text="Article Title", anchor=W, command=lambda: self.treeview_sort_column( self.tree, 'title', False)) #self.tree.place(relx=.3, relheight=1, width=1200) self.tree.place(x=330, relheight=1, width=760) self.treeyscb = Scrollbar(self, orient="vertical", command=self.tree.yview) self.treeyscb.place(relx=1, rely=.5, relheight=1, anchor=E) self.tree.configure(yscrollcommand=self.treeyscb.set) self.treexscb = Scrollbar(self, orient="horizontal", command=self.tree.xview) self.treexscb.place(relx=.3, rely=.999, width=755, anchor=SW) self.tree.configure(xscrollcommand=self.treexscb.set) self.sf.place(relx=0, rely=.055, relwidth=.30, relheight=.4) self.topicsHead.place(relx=.01, rely=.024, relwidth=.28, relheight=.03) self.topics.place(relx=.01, rely=.065, relwidth=.28) # frame for results analysis self.sf2.place(relx=0, rely=.51, relwidth=.30, relheight=.4) self.resultTopicHead.place(relx=.01, rely=.475, relwidth=.28, relheight=.03) self.resultTopics.place(relx=.01, rely=.52, relwidth=.28) # New Search Edit Search Save Search self.new_search = Button(self, text='New Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.NewSearch) self.edit_search = Button(self, text='Edit Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.EditSearch) self.save_search = Button(self, text='Save Search', background='#383838', foreground='#5DE0DC', font="Veranda 14", command=self.saveMenu) if self.data: for count, item in enumerate(self.data): # remove BOM images first from body >uffff item['body'] = ''.join( c for c in unicodedata.normalize('NFC', item['body']) if c <= '\uFFFF') tagname = 'even' if count % 2 == 0 else 'odd' self.tree.insert('', 'end', values=(parser.parse( item['date']).strftime('%m/%d/%y'), item['title'], item['uri'], item['author'], item['body']), tag=tagname) self.tree.tag_configure('even', font='Verdana 14', background="#9fedea") self.tree.tag_configure('odd', font='Verdana 14', background="#dedede") self.tree.bind('<Double-1>', self.on_click) self.tree.bind('<<TreeviewSelect>>', self.on_single_click) self.treeview_sort_column(self.tree, 'date', True) else: self.topics.config(text='No Articles Matching Search') self.resultTopics.config(text='') self.new_search.place(relx=0, rely=.95, relwidth=.1, relheight=.05, anchor=NW) if SearchFrame.content is None: self.edit_search.place(relx=.1, rely=.95, relwidth=.1, relheight=.05, anchor=NW) if len(self.data) > 0: self.save_search.place(relx=.2, rely=.95, relwidth=.1, relheight=.05, anchor=NW) else: messagebox.showerror( "Too Broad", "Search is too broad. Try refining with filters.") self.helper.ent_keyword.focus_set() SearchFrame.content = None pass
def image_search_npy_batch(img_list, image_list_names, img, model, threshold=.5, batch_size=64): global match_filename, match_value, console_frame, match_image global window, console_frame length = len(img_list) count = 0 prepared_batch = [] image_batch = [] steps = int(length / batch_size) remainder = length % batch_size print(str(steps), "steps remainder of ", str(remainder)) transfer = 0 temp_lbl = Label(console_frame, text="searching for image") temp_lbl.grid(column=0, row=7, padx=5, pady=5) progress = Progressbar(console_frame, orient=HORIZONTAL, length=600, mode='determinate') progress.grid(column=0, row=8, padx=5, pady=5) for k in range(steps): done = int((k / steps) * 100) progress['value'] = done console_frame.update() window.update() print(str(k)) names = image_list_names[k * batch_size:(k * batch_size) + batch_size] first = img_list[k * batch_size:(k * batch_size) + batch_size] second = batch_concat(img, first) third = second / 255 pred = model.predict(third) for j in range(batch_size): if pred[j] > threshold: print("match at", str(names[j])) match_filename += [names[j]] temp = pred[j] value = temp[0] match_value += [value] match_image += [first[j]] test = pred[j] progress['value'] = done console_frame.update() update_images() print("finishing remainder") names = image_list_names[(k * batch_size) + batch_size:len(img_list)] first = img_list[(k * batch_size) + batch_size:len(img_list)] second = batch_concat(img, first) third = second / 255 pred = model.predict(third) for j in range(len(pred)): if pred[j] > threshold: print("match at", str(names[j])) match_filename += [names[j]] match_value += [pred[j]] match_image += [first[j]] progress['value'] = done console_frame.update_idletasks() update_images() temp_lbl.destroy() progress.destroy()
class UIPlayer(): def __init__(self, root, player): self.ability = None self.player = player self.root = root self.playerFrame = tk.Frame(self.root) self.playerFrame.pack() self.playerLbl = tk.Label(self.playerFrame, text=player.name) self.playerLbl.pack(side="top") self.stats = tk.Frame(self.playerFrame) self.stats.pack() self.hp = Progressbar(self.stats, style="green.Horizontal.TProgressbar", maximum=player.maxHp, value=player.hp) self.hp.pack(side="left") self.mana = Progressbar(self.stats, style="blue.Horizontal.TProgressbar", maximum=player.maxMana, value=player.mana) self.mana.pack() self.castFrame = tk.Frame(self.playerFrame) self.castFrame.pack() self.castText = tk.StringVar() self.castText.set("cast") self.castLable = tk.Label(self.castFrame, textvariable=self.castText) self.castLable.pack(side="left") self.castBar = Progressbar(self.castFrame, maximum=100, value=50) self.castBar.pack() self.buffList = tk.Frame(self.playerFrame) self.buffList.pack() def startCast(self, ability): self.ability = ability self.castBar['value'] = 0 self.castText.set(ability.name) def hitCast(self, ability): if (ability.name != "Attack"): self.ability = ability self.castText.set(ability.name) def stopCast(self): self.ability = None self.castBar['value'] = 100 pass def addBuff(self, buff): bufflbl = tk.Label(self.buffList, text=buff.name) bufflbl.pack() buff.addUI(bufflbl) def removeBuff(self, buff): buff.buffLbl.destroy() def update(self): self.hp['value'] = self.player.hp self.mana['value'] = self.player.mana def getId(self): return self.player.id def __del__(self): self.mana.destroy() self.hp.destroy() self.stats.destroy() self.playerLbl.destroy() self.playerFrame.destroy() def updateCastTime(self, time): if (self.ability != None): longleft = self.ability.longLeft(time) if (longleft > 0): self.castBar['value'] = 100 - (longleft * 100) else: self.stopCast()
class UI: def __init__(self): self.top = tk.Tk() self.top.title("Youtube DL UI") self.lbl = tk.Label( self.top, text= "Copier/coller le lien dans le tampon puis clicker sur le boutton") self.lbl.grid(column=0, row=0, columnspan=2) self.link_txt = tk.StringVar() self.txt = tk.Entry(self.top, width=105, state=tk.DISABLED, textvariable=self.link_txt) self.txt.grid(column=0, row=1, columnspan=3) self.btnextract = tk.Button(self.top, text="Récuperer du tampon", command=self.get_from_clipboard) self.btnextract.grid(column=0, row=2) self.btn = tk.Button(self.top, text="Extraire!", command=self.extract, state=tk.DISABLED) self.btn.grid(column=1, row=2) self.chk_state = tk.BooleanVar() self.chk_state.set(False) self.chk = tk.Checkbutton(self.top, text="Audio seulement", var=self.chk_state) self.chk.grid(column=2, row=2) def get_from_clipboard(self): txt = self.top.clipboard_get() if txt != "": self.link_txt.set(txt) self.btn.configure(state=tk.NORMAL) else: self.btn.configure(state=tk.DISABLED) def extract(self): self.extract_ui() self.bg_task = DLThread(self) self.bg_task.start() def extract_ui(self): self.top.configure(cursor='watch') self.txt.configure(cursor='watch') self.lbl.configure(text="Extraire %s" % self.link_txt.get()) self.btn.configure(text="Extraction en cours .", state=tk.DISABLED) self.log = ScrolledText(self.top, cursor='watch') self.log.grid(column=1, row=3) self.progress = Progressbar(self.top, orient="horizontal", length=600, mode="determinate") self.progress["value"] = 0.0 self.progress["maximum"] = 100.0 self.progress.grid(column=1, row=4) def finish(self): self.top.configure(cursor='arrow') self.txt.configure(cursor='arrow') self.lbl.configure( text= "Copier/coller le lien dans le tampon puis clicker sur le boutton") # finish self.link_txt.set("") if self.log is not None: self.log.vbar.destroy() self.log.frame.destroy() self.log.destroy() self.log = None if self.progress is not None: self.progress.destroy() self.progress = None def mainloop(self): self.top.mainloop()