def update_chans(self, archive=0): self.center = Frame(root, bg=config.bgcolor, width=50, height=40, padx=3, pady=3) # layout all of the main containers root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=1) self.center.grid(row=1, sticky="nsew") #run through channel check's channels = database.get_channels(archive) number_of_channels = len(channels) + .1 pgbar = Progressbar(self.center, orient=HORIZONTAL, length=700, mode="determinate") pgbar["maximum"] = number_of_channels tbox = Text(self.center, height=25, width=100) tbox.grid(column=0, row=0) pgbar.grid(column=0, row=1) for item in channels: pgbar.step() tbox.insert(END, "checking " + item.displayname + "\n") self.center.update()
class ProgressApp(Tk): def __init__(self): super().__init__() self.value = IntVar() self.value.set(5) self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", maximum=100, variable=self.value) stop_button = Button(self, text='Stop', command=self.stop_progress_bar) start_button = Button(self, text='Start', command=self.start_progress_bar) increment_button = Button(self, text='Increment', command=self.increment) label = Label(self, text="Progess Bar") label.grid(row=0, column=0) self.progress_bar.grid(row=0, column=1) start_button.grid(row=1, column=0) stop_button.grid(row=1, column=1) increment_button.grid(row=2, column=0) def stop_progress_bar(self): self.progress_bar.stop() def start_progress_bar(self): self.progress_bar.start() self.progress_bar.step(10) def increment(self): self.value.set(self.value.get() + 5)
def export_to_csv(array, root): # fenetre de chargement popup_window = Toplevel() label = Label(popup_window, text="Please wait during the scores calculus...") label.pack() p = Progressbar(popup_window, orient=HORIZONTAL, length=200, mode="determinate", takefocus=True, maximum=len(array)) p.pack() x = root.winfo_screenwidth() / 2 y = root.winfo_screenheight() / 2 popup_window.geometry('+%d+%d' % (x, y)) with open('scores.csv', 'w') as csvfile: writer = csv.writer(csvfile) for r in array: writer.writerow(r) p.step() root.update() csvfile.close() popup_window.destroy()
class SomeClass1(threading.Thread): def __init__(self, q, root, total_rows, loop_time=1.0 / 60): self.q = q self.timeout = loop_time self.total_rows = 50 self.root1 = tk.Tk() self.root_ref = root self.processed = 0 self.progress = Progressbar(root, orient=HORIZONTAL, variable=1, length=120) self.progress.config(maximum=MAX, mode='determinate', value=1) self.progress.step(1) self.progress.grid(row=0, column=1) super(SomeClass1, self).__init__() def onThread(self, function, *args, **kwargs): self.q.put((function, args, kwargs)) def run(self): while True: try: function, args, kwargs = self.q.get(timeout=self.timeout) function(*args, **kwargs) print("run processed") except queue.Empty: self.idle() print("run empty") def idle(self): # put the code you would have put in the `run` loop here print("idle") self.progress = Progressbar(self.root_ref, orient=HORIZONTAL, variable=self.processed, length=120) self.progress.config(maximum=MAX, mode='determinate', value=1) def doSomething(self, processed_row): global processed print("waiting in increment_progress_bar...", processed_row, ":", self.total_rows) #int_processed_row = int(processed_row,10) if (processed_row >= self.total_rows): print("in progress stop") self.progress.stop() self.progress.grid_forget() else: print("in progress step") #self.progress.step(processed_row) self.processed = processed_row print("updated progress bar...") def doSomethingElse(self, b): print("doSomethingElse", b) self.progress.step(1) time.sleep(2)
class Widget(tk.Frame): def __init__(self, parent,cola : qu.Queue): tk.Frame.__init__(self, parent, bg="green") self.parent = parent self.widgets() self.cola =cola self.parent.after(100,self.worker) self.parent.configure(background='black') self.parent.protocol("WM_DELETE_WINDOW", self.closewidget) def widgets(self): self.text = st.ScrolledText(self, width=50, height=10) self.text.insert(tk.INSERT, "Hello World\n") self.text.insert(tk.END, "nueva sentencia\n") self.text.insert(tk.END, "This is the first frame") self.text.grid(row=10, column=1) self.label = tk.Label(self, text = "window downloader") self.label.grid(row=0,column=1) self.progress_bar = Progressbar(self,orient=tk.HORIZONTAL,length=500,maximum=100) self.progress_bar.grid(row=11, column=1) def worker(self): self.text.insert(tk.END,"nueva al final") #Daemon make destroy the threads when main trhead ends tread = th.Thread(target=self.polling,args=(self.cola,),daemon=True) tread.start() def polling(self,cola:qu.Queue): # self.text.insert(tk.END,cola.get()+"entrada polling \n") last_message= False while (not last_message): message: Message = cola.get(True) self.text.insert(tk.END,message.messege) self.progress_bar.step(message.progress) last_message = message.lastmessage cola.task_done() self.closewidget() def closewidget(self): print("en destoy") self.parent.destroy()
def uploadDirectoryWithWindow(directory): onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f))] root = tk.Tk() root.geometry("900x40") app = tk.Frame(master=root) app.winfo_toplevel().title("Mouth Music Data Gatherer Upload Progress") progress = tk.IntVar() bar = Progressbar(app, orient="horizontal", length=900, mode="determinate", maximum=len(onlyfiles), variable=progress) bar.pack() app.pack() for a in range(len(onlyfiles)): uploadFileToAws(directory + onlyfiles[a], directory + onlyfiles[a]) bar.step(1) root.update_idletasks() root.update()
class ProgressApp(Tk): def __init__(self): super().__init__() self.value = IntVar() self.value.set(0) style = ttk.Style() style.theme_use('clam') style.configure("blue.Horizontal.TProgressbar", background='light green') self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", style="blue.Horizontal.TProgressbar", maximum=100, variable=self.value) # stop_button = Button(self, text='Stop', command=self.stop_progress_bar) # start_button = Button(self, text='Start', command=self.start_progress_bar) # increment_button = Button(self, text='Increment', command=self.increment) self.start_progress_bar() label = Label(self, text="Progess Bar") label.grid(row=0, column=0) self.progress_bar.grid(row=0, column=1) label2 = Label(self, font=20) label2.config(text=self.value.get()) label2.grid(row=1, column=1) # start_button.grid(row=1,column=0) # stop_button.grid(row=1,column=1) # increment_button.grid(row=2,column=0) def stop_progress_bar(self): self.progress_bar.stop() def start_progress_bar(self): self.progress_bar.start() self.progress_bar.step(100) def increment(self): self.value.set(self.value.get() + 5)
class BarS(Frame): def __init__(self, parent, fs=16, width=1600, height=50, ratio=0.7): Frame.__init__(self, parent, width=width, height=height) self.pack_propagate(0) self.font = 'Times', int(fs) self.sF = Frame(self, height=height, width=int(width * abs(ratio))) self.sF.pack_propagate(0) self.pF = Frame(self, height=height, width=int(width * (1 - abs(ratio)))) self.pF.pack_propagate(0) if ratio >= 0: self.sF.pack(side='left') self.pF.pack(side='left') else: self.pF.pack(side='left') self.sF.pack(side='left') self.msg = StringVar() self.status = Label(self.sF, textvariable=self.msg, font=self.font, justify='left') self.status.pack(expand=1, fill='both') self.progress = Progressbar(self.pF, orient="horizontal", mode="determinate") self.progress.pack(expand=1, fill='both') self.current_val = 0 def update(self, msg, val): self.msg.set(str(msg)) increase = 100 - self.current_val + val self.progress.step(float(increase)) self.current_val = val return
def open_new_window(self, chanid): newWindow = Tk() newWindow.title('Channel Update') newWindow.geometry('{}x{}'.format(800, 500)) vids = self.get_feed(chanid) ''' yt_videoid=str(entry.yt_videoid), title=str(entry.title), description=str(entry.description), publisher=value, publish_date=get_unix_utc(entry.published,'ut'), watched=False ''' tbox = Text(newWindow, height=25, width=100) tbox.grid(column=0, row=0) pgbar = Progressbar(newWindow, orient=HORIZONTAL, length=500, mode="determinate") pgbar["maximum"] = len(vids) + .1 pgbar.grid(column=0, row=1) for videodata in vids: pgbar.step() newWindow.update() #if video not downloaded inititate download result = database.add_video(videodata.yt_videoid, videodata) if result == 1: if self.download_video(videodata, chanid) == True: tbox.insert(END, "Downloading " + videodata.title + " \n") else: tbox.insert(END, videodata.title + " already downloaded \n") database.close() tbox.insert(END, "Operation complete") sleep(2) newWindow.destroy()
class LipreadingRecording(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.data_root_dir = None self.skip_curr_item = False self.gap_wait_counter = 0 # MAKE SURE IN THIS ORDER!!! self.davis_control = jAERController(udp_port=8997) self.das_control = jAERController(udp_port=8998) # Drawing related self.grid() self.create_widgets() def configure_grid(self, master, num_rows, num_cols, weight=1): """Configure a grid in a Frame.""" for r in range(num_rows): master.rowconfigure(r, weight=weight) for c in range(num_cols): master.columnconfigure(c, weight=weight) def create_master_layout(self): # rows self.master.rowconfigure(0, weight=7) self.master.rowconfigure(1, weight=2) self.master.rowconfigure(2, weight=1) # column self.master.columnconfigure(0, weight=1) self.master.columnconfigure(1, weight=2) def create_widgets(self): # get grid layout # self.configure_grid(self.master, MASTER_ROWS, MASTER_COLS, 1) self.create_master_layout() # text frame self.text_frame = tk.Frame(self.master, bg=TEXT_BG_COLOR) self.text_frame.grid(row=TEXT_X, column=TEXT_Y, rowspan=TEXT_ROWS, columnspan=TEXT_COLS, sticky=tk.W + tk.E + tk.N + tk.S) # text label self.text_label = tk.Label(self.text_frame, text="Welcome", font=TEXT_FONT, bg=TEXT_BG_COLOR) self.text_label.place(relx=0.5, rely=0.5, anchor="center") # parameter frame self.param_frame = tk.Frame(self.master, bg=PARAM_BG_COLOR) self.param_frame.grid(row=PARAM_X, column=PARAM_Y, rowspan=PARAM_ROWS, columnspan=PARAM_COLS, sticky=tk.W + tk.E + tk.N + tk.S) self.configure_grid(self.param_frame, 5, 2, 1) self.parameter_frame_widgets() # button frame self.button_frame = tk.Frame(self.master, bg=BUTTON_BG_COLOR) self.button_frame.grid(row=BUTTON_X, column=BUTTON_Y, rowspan=BUTTON_ROWS, columnspan=BUTTON_COLS, sticky=tk.W + tk.E + tk.N + tk.S) self.configure_grid(self.button_frame, 5, 1, 1) self.button_frame_widgets() # progress frame self.progress_frame = tk.Frame(self.master, bg=PROGRESS_BG_COLOR, bd=1) self.progress_frame.grid(row=PROGRESS_X, column=PROGRESS_Y, columnspan=PROGRESS_COLS, sticky=tk.W + tk.E + tk.N + tk.S) # progress bar self.progress_val = tk.IntVar() self.progress_val.set(0) self.progress_bar = Progressbar(self.progress_frame, length=100, orient="horizontal", maximum=100, variable=self.progress_val, mode="determinate") self.progress_bar.pack(fill=tk.BOTH, ipady=5) def button_frame_widgets(self): # buttons self.training_button = tk.Button(self.button_frame) self.training_button["text"] = "Training Session" self.training_button["font"] = BUTTON_FONT self.training_button["width"] = BUTTON_LABEL_WIDTH self.training_button["command"] = self.training_button_cmd self.training_button.grid(row=0, column=0, columnspan=3) self.start_button = tk.Button(self.button_frame) self.start_button["text"] = "Start" self.start_button["font"] = BUTTON_FONT self.start_button["width"] = BUTTON_LABEL_WIDTH self.start_button["command"] = self.start_button_cmd self.start_button.grid(row=1, column=0, columnspan=3) self.skip_button = tk.Button(self.button_frame) self.skip_button["text"] = "Skip" self.skip_button["font"] = BUTTON_FONT self.skip_button["width"] = BUTTON_LABEL_WIDTH self.skip_button["command"] = self.skip_button_cmd self.skip_button.grid(row=2, column=0, columnspan=3) self.select_root_button = tk.Button(self.button_frame) self.select_root_button["text"] = "Select Data Root" self.select_root_button["font"] = BUTTON_FONT self.select_root_button["width"] = BUTTON_LABEL_WIDTH self.select_root_button["command"] = self.select_data_root self.select_root_button.grid(row=3, column=0, columnspan=3) self.stop_button = tk.Button(self.button_frame) self.stop_button["text"] = "Quit" self.stop_button["font"] = BUTTON_FONT self.stop_button["width"] = BUTTON_LABEL_WIDTH self.stop_button["command"] = self.stop_button_cmd self.stop_button.grid(row=4, column=0, columnspan=3) def parameter_frame_widgets(self): # text boxes self.subject_label = tk.Label(self.param_frame, text="Subject ID:", font=PARAM_FONT, bg=PARAM_BG_COLOR, anchor="e", width=PARAM_LABEL_WIDTH) self.subject_label.grid(row=0, column=0) self.subject_text = tk.Entry(self.param_frame, font=PARAM_FONT) self.subject_text.insert(tk.END, "001") self.subject_text.grid(row=0, column=1, columnspan=2) self.trial_label = tk.Label(self.param_frame, text="Trial ID:", font=PARAM_FONT, bg=PARAM_BG_COLOR, anchor="e", width=PARAM_LABEL_WIDTH) self.trial_label.grid(row=1, column=0) self.trial_text = tk.Entry(self.param_frame, font=PARAM_FONT) self.trial_text.insert(tk.END, "1") self.trial_text.grid(row=1, column=1, columnspan=2) self.num_sentence_label = tk.Label(self.param_frame, text="No. sentence(s)/trial:", font=PARAM_FONT, bg=PARAM_BG_COLOR, anchor="e", width=PARAM_LABEL_WIDTH) self.num_sentence_label.grid(row=2, column=0) self.num_sentence_text = tk.Entry(self.param_frame, font=PARAM_FONT) self.num_sentence_text.insert(tk.END, "20") self.num_sentence_text.grid(row=2, column=1, columnspan=2) self.duration_label = tk.Label(self.param_frame, text="Duration [secs]:", font=PARAM_FONT, bg=PARAM_BG_COLOR, anchor="e", width=PARAM_LABEL_WIDTH) self.duration_label.grid(row=3, column=0) self.duration_text = tk.Entry(self.param_frame, font=PARAM_FONT) self.duration_text.insert(tk.END, "4") self.duration_text.grid(row=3, column=1, columnspan=2) self.gap_label = tk.Label(self.param_frame, text="Gap [secs]:", font=PARAM_FONT, bg=PARAM_BG_COLOR, anchor="e", width=PARAM_LABEL_WIDTH) self.gap_label.grid(row=4, column=0) self.gap_text = tk.Entry(self.param_frame, font=PARAM_FONT) self.gap_text.insert(tk.END, "2") self.gap_text.grid(row=4, column=1, columnspan=2) def validate_data_root(self): if self.data_root_dir is None or \ os.path.isdir(self.data_root_dir) is False: self.data_root_dir = os.path.join(os.environ["HOME"], "lipreading_data") os.makedirs(self.data_root_dir) # make a copy of list of sentences in the data root self.curr_GRID_CORPUS_path = os.path.join(self.data_root_dir, "temp_GRID_corpus.pkl") if not os.path.isfile(self.curr_GRID_CORPUS_path): with open(self.curr_GRID_CORPUS_path, "wb") as f: pickle.dump(GRID_CORPUS, f) def start_button_cmd(self): self.start_button["text"] = "Trial in place" self.start_button["state"] = "disabled" # get all variables in the parameter boxes self.subject_id = self.subject_text.get() self.trial_id = self.trial_text.get() self.num_sentences = int(self.num_sentence_text.get()) self.duration = float(self.duration_text.get()) # in secs self.gap = float(self.gap_text.get()) # in secs # freeze the change of the variables self.disable_param_text() # construct recording folder self.validate_data_root() self.current_trial_folder = os.path.join(self.data_root_dir, self.subject_id, self.trial_id) assert os.path.isdir(self.current_trial_folder) is False os.makedirs(self.current_trial_folder) # setup ground truth folder gt_file_path = os.path.join(self.current_trial_folder, "gt_sentences.txt") gt_file = open(gt_file_path, "a+") # start sign if args.debug is True: start_time = timeit.default_timer() self.display_text("We are about to start!", "green") self.sleep(3) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] Start sign used %.3f secs" % (end_time - start_time)) print(Style.RESET_ALL) # start looping through the sentences sentences = self.prepare_text(self.num_sentences) for sen_id in range(self.num_sentences): # get the text self.progress_bar.step(int(100 / self.num_sentences)) curr_sentence = sentences[sen_id] # get to control flow if args.debug is True: start_time = timeit.default_timer() save_paths = self.record_one_sentence(curr_sentence, sen_id) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] Sentence %s used %.3f secs" % (curr_sentence, end_time - start_time)) print(Style.RESET_ALL) # pause the gap if args.debug is True: start_time = timeit.default_timer() do_skip, extra_sleep = self.check_skip_pressed() if do_skip is False: gt_file.write(curr_sentence + "\n") self.remove_last_recording(save_paths, do_skip) if extra_sleep != 0: self.sleep(extra_sleep) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] Total skip for %s used %.3f secs" % (curr_sentence, end_time - start_time)) print(Style.RESET_ALL) # End sign gt_file.close() if args.debug is True: start_time = timeit.default_timer() self.display_text("This trial ends. Thank you!", "green") self.sleep(3) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] End sign used %.3f secs" % (end_time - start_time)) print(Style.RESET_ALL) self.display_text("Welcome", "black") # complete trial self.enable_param_text() # restore button's text self.start_button["text"] = "Start" self.start_button["state"] = "normal" def disable_param_text(self): self.subject_text["state"] = "disabled" self.trial_text["state"] = "disabled" self.num_sentence_text["state"] = "disabled" self.duration_text["state"] = "disabled" self.gap_text["state"] = "disabled" def enable_param_text(self): self.subject_text["state"] = "normal" self.trial_text["state"] = "normal" self.num_sentence_text["state"] = "normal" self.duration_text["state"] = "normal" self.gap_text["state"] = "normal" def record_one_sentence(self, text, text_id, training=False): # construct the save paths if training is False: filename_base = text.replace(" ", "_") + "_" + str(text_id) davis_save_path = os.path.join(self.current_trial_folder, filename_base + "_davis.aedat") das_save_path = os.path.join(self.current_trial_folder, filename_base + "_das.aedat") mic_save_path = os.path.join(self.current_trial_folder, filename_base + "_mic.wav") # zero time stamps for all windows if args.debug is True: start_time = timeit.default_timer() reset_time() if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] First reset %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) # start logging for all sensors if args.debug is True: start_time = timeit.default_timer() self.davis_control.start_logging(davis_save_path, title=None, reset_time=False) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] DAVIS logging %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) if args.debug is True: start_time = timeit.default_timer() self.das_control.start_logging(das_save_path, title=None, reset_time=False) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] DAS logging %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) if args.debug is True: start_time = timeit.default_timer() audio_contrl = log_sound(mic_save_path) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] AUDIO logging %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) # self.sleep(0.2) # display text and change the text color self.display_text(text, color="red") # play sound for signal play_sound() # wait for duration long if args.debug is True: start_time = timeit.default_timer() self.sleep(self.duration) if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] Text displays for %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) # change the text to None self.display_text("------", color="blue") if training is False: # save all the files # close logging if args.debug is True: start_time = timeit.default_timer() self.davis_control.stop_logging() self.das_control.stop_logging() audio_contrl.terminate() if args.debug is True: end_time = timeit.default_timer() print(Fore.RED + "[DEBUG MSG] Stop logging for %s used %.3f secs" % (text, end_time - start_time)) print(Style.RESET_ALL) # TODO quick file checker return (davis_save_path, das_save_path, mic_save_path) else: return ("", "", "") def display_text(self, text, color): """Change text label's content.""" self.text_label["text"] = text self.text_label["fg"] = color def prepare_text(self, num_sentences=20, training=False): with open(self.curr_GRID_CORPUS_path, "rb") as f: curr_GRID_CORPUS = pickle.load(f) shuffle(curr_GRID_CORPUS) f.close() num_avail_sentences = len(curr_GRID_CORPUS) start_idx = randint(0, num_avail_sentences - num_sentences) end_idx = start_idx + num_sentences prepared_text = deepcopy(curr_GRID_CORPUS[start_idx:end_idx]) if training is False: del curr_GRID_CORPUS[start_idx:end_idx] with open(self.curr_GRID_CORPUS_path, "wb") as f: pickle.dump(curr_GRID_CORPUS, f) f.close() return prepared_text def stop_button_cmd(self): self.master.destroy() def skip_button_cmd(self): self.skip_curr_item = True def sleep(self, duration): """Just sleep for a second.""" try: self.master.update() time.sleep(duration) except Exception: pass def check_skip_pressed(self, num_checks=10): """Skip if true, False otherwise.""" sleep_time = self.gap / num_checks for check_idx in range(num_checks): self.sleep(self.gap / num_checks) if self.skip_curr_item is True: return True, sleep_time * (num_checks - check_idx + 1) return False, 0 def remove_last_recording(self, save_paths, do_remove=False): """For cleaning the last recording if skip.""" if do_remove is True: try: print("-" * 50) os.remove(save_paths[0]) print("[RECORDING MSG] Recording %s removed" % (save_paths[0])) os.remove(save_paths[1]) print("[RECORDING MSG] Recording %s removed" % (save_paths[1])) os.remove(save_paths[2]) print("[RECORDING MSG] Recording %s removed" % (save_paths[2])) print("-" * 50) except OSError: pass # restore self.skip_curr_item = False def training_button_cmd(self): self.training_button["text"] = "Training in place" self.training_button["state"] = "disabled" # get all variables in the parameter boxes self.subject_id = self.subject_text.get() self.trial_id = self.trial_text.get() self.num_sentences = int(self.num_sentence_text.get()) self.duration = float(self.duration_text.get()) # in secs self.gap = float(self.gap_text.get()) # in secs # freeze the change of the variables self.disable_param_text() self.validate_data_root() # start sign self.display_text("We are about to start!", "green") self.sleep(3) # start looping through the sentences sentences = self.prepare_text(self.num_sentences, training=True) for sen_id in range(self.num_sentences): # get the text self.progress_bar.step(int(100 / self.num_sentences)) curr_sentence = sentences[sen_id] # get to control flow self.record_one_sentence(curr_sentence, sen_id, training=True) # pause the gap do_skip, extra_sleep = self.check_skip_pressed() if extra_sleep != 0: self.sleep(extra_sleep) # End sign self.display_text("This trial ends. Thank you!", "green") self.sleep(3) self.display_text("Welcome", "black") # complete trial self.enable_param_text() self.training_button["text"] = "Start Training" self.training_button["state"] = "normal" def select_data_root(self): self.data_root_dir = askdirectory() print("[RECORDING MSG] The data directory is set to %s" % (self.data_root_dir))
class MainFrame(Frame): ''' This class implements main GUI of the application. Attributes: parent (Tk object): parent of this frame (Tk()). params_frame (ParamsFrame): frame with parameters. data_frame (DataFrame): frame with data and solution. progress_bar (Progressbar): progress bar widget. increment (int): progress bar increment, it is modified in other classes that are responsible for solving the problem and update progress. weights_status_lbl (Label): label that displays if weight restrictions are feasible. weights_status_str (StringVar): StringVar object used for tracking if weight restrictions are feasible. current_categories (list of str): list of current categories. Args: parent (Tk object): parent of this frame (Tk()). ''' def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.params_frame = None self.data_frame = None self.progress_bar = None self.increment = 0 self.weights_status_lbl = None self.weights_status_str = StringVar() self.weights_status_str.trace('w', self.on_weights_status_change) self.current_categories = [] self.create_widgets() def create_widgets(self): ''' Creates all widgets that belong to this frame. ''' self.parent.title('pyDEA') self.pack(fill=BOTH, expand=1) self.columnconfigure(0, weight=1, pad=5) self.columnconfigure(1, weight=0, pad=5) self.rowconfigure(0, pad=3, weight=1) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.current_categories = [] data_from_params_file = StringVar() str_var_for_input_output_boxes = ObserverStringVar() self.params_frame = ParamsFrame(self, self.current_categories, data_from_params_file, str_var_for_input_output_boxes, self.weights_status_str) data_frame = DataFrame(self, self.params_frame, self.current_categories, data_from_params_file, str_var_for_input_output_boxes) self.data_frame = data_frame data_frame.grid(row=0, column=0, sticky=N+S+W+E, padx=15, pady=15) self.params_frame.grid(row=0, column=1, sticky=W+E+S+N, padx=15, pady=15, columnspan=2) lbl_progress = Label(self, text='Progress') lbl_progress.grid(row=1, column=0, sticky=W, padx=10, pady=5) self.progress_bar = Progressbar(self, mode='determinate', maximum=100) self.progress_bar.grid(row=2, column=0, sticky=W+E, padx=10, pady=5) run_btn = Button(self, text='Run', command=self.run) run_btn.grid(row=2, column=1, sticky=W, padx=10, pady=10) self.weights_status_lbl = Label(self, text='', foreground='red') self.weights_status_lbl.grid(row=2, column=2, padx=10, pady=5, sticky=W) def on_weights_status_change(self, *args): ''' This method is called when weight restrictions status is changed. ''' self.weights_status_lbl.config(text=self.weights_status_str.get()) def run(self): ''' This method is called when the user presses Run button. Solves the problem and displays solution. ''' clean_up_pickled_files() params = self.params_frame.params run_method = RunMethodGUI(self) run_method.run(params) def construct_categories(self): ''' Returns current categories. Returns: (list of str): list of current categories ''' return [category.strip() for category in self.current_categories if category] def on_dmu_change(self, *args): ''' Updates progress bar. ''' self.progress_bar.step(self.increment) self.progress_bar.update()
class CleanUpGui(Frame): def __init__(self, master=None): Frame.__init__(self, master=master) self.master.title("Clean up") self.grid(row=12, column=3, sticky=NSEW) self.progress = Progressbar(self, orient=HORIZONTAL, length=200, maximum=100, mode='determinate') file = open("never_delete_files.txt", "a") # Setup variables self.folder_details = None self.current_file = None self.new_path = "" # dummy, =1 if in never_delete_files.txt, otherwise =0 self.checkvar1 = IntVar() # bytes deleted counter self.bytes_counter = 0 # Setup GUI elements self.current_file_name = Label(self) self.current_file_size = Label(self) self.type_file_info = Label(self) self.never_delete_this_file = Label(self) self.bytes_counter_label = Label(self) self.rename_button = Label(self) # buttons self.delete_file_button = Button(self, text="Delete", command=self.delete_current_file) self.skip_file_button = Button(self, text="Skip", command=self.load_next_file) self.never_delete_button = Checkbutton(self, text="Never delete this file", variable=self.checkvar1, onvalue=1, offvalue=0, command=self.combined_function1) self.bytes_counter_label.configure(text="Current bytes deleted: " + str(self.bytes_counter)) self.rename_button = Button(self, text="Rename file", command=self.rename_window) self.quick_move_button = Button(self, text="Quick Move", command=self.quick_move) # Place GUI elements on Canvas self.progress.grid(row=0, column=0, columnspan=3) self.current_file_name.grid(row=1, column=0, columnspan=3, rowspan=1, sticky="W") self.current_file_size.grid(row=2, column=0, columnspan=3, rowspan=1, sticky="W") self.bytes_counter_label.grid(row=3, column=0, columnspan=3, rowspan=1, sticky="W") self.never_delete_this_file.grid(row=4, column=0, columnspan=3, rowspan=1, sticky="NESW") self.type_file_info.grid(row=5, column=0, columnspan=3, rowspan=4, sticky="NESW") self.quick_move_button.grid(row=10, column=0, columnspan=3, rowspan=1, sticky="ESW") self.delete_file_button.grid(row=11, column=0, columnspan=1, rowspan=1, sticky="ESW") self.skip_file_button.grid(row=11, column=1, columnspan=1, rowspan=1, sticky="ESW") self.rename_button.grid(row=11, column=2, columnspan=1, rowspan=1, sticky="ESW") self.never_delete_button.grid(row=12, column=0, columnspan=3, rowspan=1, sticky="W") # steps of the progress bar for each file def progress_bar(self): n = self.folder_details.n_files steps = (100 - 0.001) / n self.progress.step(steps) # to execute 2 functions with 1 button press def combined_function1(self): self.prevent_unchecking() self.never_delete() # delete files with button press def delete_current_file(self): try: # check if file is not in the "never_delete_file" i.e. box is unchecked/dummy equal to 0 if self.checkvar1.get() == 1: self.never_delete_this_file.configure(text="The file" + self.current_file.path + " cannot be deleted") else: # if not in the .txt file then delete, load next file and count the bytes deleted if self.current_file: file_size = getsize( join(self.folder_details.path, self.current_file.path)) self.bytes_counter += file_size self.bytes_counter_label.configure( text="current bytes deleted: " + str(self.bytes_counter)) remove( join(self.folder_details.path, self.current_file.path)) # load the next file self.load_next_file() except FileNotFoundError: # if file not found e.g. because deleted manually after program started print("no file to delete") self.load_next_file() # load next file def load_next_file(self): if self.folder_details: next_file = self.folder_details.get_next_file() if next_file: # load next file, check if it can be deleted, disable/enable checkbox, move progress bar self.current_file = FileDetails(self, self.folder_details, next_file) self.check_not_delete_list() self.prevent_unchecking() self.progress_bar() else: self.current_file = FileDetails(self, self.folder_details, "") self.check_not_delete_list() self.prevent_unchecking() self.progress.grid_forget() self.current_file.display_details() # write absolute path to txt file, to never deleted a file with that exact absolute path def never_delete(self): path = join(self.folder_details.path, self.current_file.path) file = open("never_delete_files.txt", "a") file.write(path + "\n") # check if file can be deleted, check the checkbox if not/uncheck if it can def check_not_delete_list(self): ndfile = open("never_delete_files.txt", "r") ndfiles = ndfile.read().splitlines() path = join(self.folder_details.path, self.current_file.path) if path in ndfiles: self.checkvar1.set(1) else: self.checkvar1.set(0) # check if file can be deleted, if not disable checkbox def prevent_unchecking(self): if self.checkvar1.get() == 1: self.never_delete_button.config(state=DISABLED) else: self.never_delete_button.config(state=NORMAL) # rename a file with user input + if file is in never_deleted_file add the new path to the text file def rename_file(self): try: path = join(self.folder_details.path, self.current_file.path) new_name = join(self.folder_details.path, self.entry.get()) os.rename(path, new_name) if self.checkvar1.get() == 1: path = join(self.folder_details.path, self.entry.get()) file = open("never_delete_files.txt", "a") file.write(path + "\n") self.root.destroy() self.load_next_file() except OSError: # if file name not allowed raise error print("file name not allowed") # open new canvas, ask for user input to rename, execute function rename_file if button pressed def rename_window(self): self.root = Tk() self.root.title("Rename File") new_window = Canvas(self.root, width=200, height=100) self.entry = Entry(self.root) self.entry.insert(0, str(self.current_file.path)) new_window.create_window(100, 35, window=self.entry) label = Label( self.root, text= "Type your new file name here:\n\n Include the extension in the new file name!" ) b = Button(self.root, text="rename", width=10, command=self.rename_file) label.pack() new_window.pack() b.place(x=65, y=110) # disable buttons when went through all files, to prevent any errors from occurring def disable_buttons(self): self.delete_file_button["state"] = DISABLED self.rename_button["state"] = DISABLED self.never_delete_button["state"] = DISABLED self.skip_file_button["state"] = DISABLED self.quick_move_button["state"] = DISABLED # Move file to selected directory, raise error if no directory selected to or file doesnt exist anymore def quick_move(self): try: if self.new_path == "": self.new_path = filedialog.askdirectory() shutil.move(join(self.folder_details.path, self.current_file.path), self.new_path) self.load_next_file() except FileNotFoundError: print("no directory selected to move the file to") def delete_path(self): pass # startup # select directory and 'start' the program, raise error if no directory selected def select_folder(self): try: folder_path = filedialog.askdirectory() self.folder_details = FolderDetails(folder_path) self.load_next_file() self.check_not_delete_list() self.prevent_unchecking() except AttributeError: print("no folder selected") raise SystemExit
class InstallWindow: def __init__(self, setpath, installpath, systemwide, type='install'): global root self.setpath = setpath self.installpath = installpath self.systemwide = systemwide self.type = type self.master = Toplevel(root) self.master.withdraw() self.master.protocol('WM_DELETE_WINDOW', self.close) self.master.iconbitmap(imgdir) self.master.title('Adb & Fastboot installer - By @Pato05') self.master.geometry("600x400") self.master.resizable(False, False) frame = Frame(self.master, relief=FLAT) frame.pack(padx=10, pady=5, fill=BOTH) Label(frame, text='Please wait while Adb and Fastboot are getting %s...' % ( 'updated' if type == 'update' else 'installed on your PC')).pack(fill=X) self.mode = 'unksize' self.progressbar = Progressbar( frame, orient=HORIZONTAL, length=100, mode='indeterminate') self.progressbar.pack(fill=X) self.progressbar.start(20) self.downloaded = 0 self.progressv = Text(frame, bd=0, insertborderwidth=0, state='disabled', background='#f0f0ed', font=('Segoe UI', 10)) self.progressv.pack(fill=BOTH, pady=(10, 5)) self.master.deiconify() self.downloading = threading.Thread(target=self.download) self.downloading.start() def download_progress(self, count, block_size, total_size): if total_size != -1 and self.mode != 'ksize': self.mode = 'ksize' self.progressbar.stop() self.progressbar.configure(mode='determinate', maximum=total_size) elif total_size == -1 and self.mode != 'unksize': self.mode = 'unksize' self.progressbar.configure(mode='indeterminate') if self.mode == 'ksize': self.downloaded += block_size self.progressbar.step(block_size) if self.downloaded == total_size: self.progress('Download ended.') def download(self): self.pathres = False self.progress('Downloading Adb and Fastboot...', False) from urllib.request import urlretrieve import urllib.error workingdir = scriptdir download = os.path.join(workingdir, 'pt.zip') try: urlretrieve('https://dl.google.com/android/repository/platform-tools-latest-windows.zip', download, self.download_progress) except (urllib.error.HTTPError, urllib.error.URLError) as e: messagebox.showerror(title='Adb & Fastboot Uninstaller', message='Failed while trying to download Adb and Fastboot. Are you connected to the internet?\nError: %s' % e) self.error_close() return False self.progressbar.configure( mode='indeterminate', maximum=150, length=400, value=0) self.progressbar.start(20) self.progress('Extracting Adb and Fastboot...') from zipfile import ZipFile with ZipFile(download) as z: z.extractall(workingdir) os.remove(download) self.progress('Moving Adb and Fastboot to destination folder...') if(os.path.isdir(self.installpath)): rmtree(self.installpath) sleep(0.1) os.mkdir(self.installpath) for file in ['adb.exe', 'AdbWinApi.dll', 'AdbWinUsbApi.dll', 'fastboot.exe']: self.progress("Moving %s..." % file) copyfile(os.path.join(workingdir, 'platform-tools', file), os.path.join(self.installpath, file)) rmtree(os.path.join(workingdir, 'platform-tools')) if self.setpath == 1: self.progress('Adding Adb & Fastboot into %s\'s path' % ('system' if self.systemwide == 1 else 'user')) self.pathres = addToPath(self.installpath, self.systemwide == 1) self.progress( 'Successfully added Adb & Fastboot into path' if self.pathres else 'Failed to add Adb & Fastboot into path') self.progressbar.stop() self.finish() def finish(self): self.app = FinishWindow( self.setpath, self.pathres, self.installpath, self.type) self.master.destroy() def progress(self, what, lb=True): self.progressv.configure(state='normal') self.progressv.insert(END, ('\r\n' if lb else '')+what) self.progressv.configure(state='disabled') def error_close(self): global root root.destroy() def close(self): pass
class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): # master window self.master.title("Scraper") # labels l1 = Label( self.master, text= 'Lets do some scraping, fill in the fields and hit search. Then enjoy!', fg="red") l1.grid(column=0, row=0, columnspan=4) l2 = Label(self.master, text="url or list of url's to search:") l2.grid(column=0, row=4) l3 = Label(self.master, text="location to save to:") l3.grid(column=0, row=5) l4 = Label(self.master, text="String to search for:", fg="blue") l4.grid(column=0, row=3) # buttons #b1 = Button(self.master, text="secret", command=self.secret, bg="green", activebackground="orange") #b1.grid(column=0, row=0, sticky=W) b2 = Button(self.master, text="quit", command=self.quit, fg="red", activebackground="red") b2.grid(column=0, row=6, sticky=W, padx=5) b3 = Button(self.master, text="Browse", command=self.browse1, bg="lime", activebackground="tan") b3.grid(column=3, row=4, sticky=E) b4 = Button(self.master, text="Browse", command=self.browse2, bg="lime", activebackground="tan") b4.grid(column=3, row=5, sticky=E) b5 = Button(self.master, text="Search", command=self.search, bg="orange", activebackground="pink") b5.grid(column=3, row=6, sticky=W) # Data Entry self.e1 = Entry(self.master) # default relief is SUNKEN self.e1.grid(column=1, row=4, sticky=(W, E), pady=5, ipady=3) self.e2 = Entry(self.master) self.e2.grid(column=1, row=5, sticky=(W, E), pady=5, ipady=3) self.e3 = Entry(self.master) self.e3.grid(column=1, row=3, sticky=(W, E), pady=5, ipady=3) # Sizegrip self.sg = Sizegrip(self.master).grid(column=999, row=999, sticky=(S, E)) self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) # these make sizegrip work # Progressbar self.pb = Progressbar(self.master, orient=HORIZONTAL, length=200, mode='indeterminate') self.pb.grid(column=1, row=6, sticky=W) # pop-up for file open dialog def browse1(self): fname = askopenfilename(initialdir='C:/Users', title="Browse to file", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) if fname: try: self.e1.insert( 0, fname) # insert the file path into the dialog box print(fname) except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname) # pop-up for file save dialog def browse2(self): # this gives a dialog that asks for a file name to save and returns the file. It also creates the file in the location given fname = asksaveasfilename(initialdir='C:/Users', title="Browse to file", defaultextension=".txt", filetypes=(("Text files", "*.txt"), ("All files", "*.*"))) if fname: try: self.e2.insert(0, fname) print(fname) except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname) def quit(self): exit() def urlSearch(self, url, logFile, sText): count = 0 with open(logFile, "a") as f: # append to the above created file with urlopen(url) as html: f.write("\n") f.write("Website:\n") f.write(url) f.write("\n") soup = BeautifulSoup(html) # create beautifulsoup object #print("pretty") #print(soup.prettify()) print("") print("original encoding is: %s" % soup.original_encoding) #f.write("original encoding of webpage: \n") #f.write(soup.original_encoding) #f.write("\n") #f.write("\n") print("") #print("find text") print("string to look for:") print(sText) f.write("String to look for: \n") f.write(sText) f.write("\n") f.write("\n") """ # these do the same thing data = soup.find(text=sText) print("data = %s" %data) if data == sText: # print("in if test") #text = soup.getText(sText) print(data) count += 1 # update the counter print("found text") """ data = [] data = soup.find_all(text=sText) print("data = %s" % data) for i in range(0, len(data)): if data[i] == sText: # print("in if test") print(data[i]) count += 1 # update the counter print("found text") print("Text string found %i times" % count) f.write("Text string found %i times" % count) f.write("\n") f.write( "**************************************************************" ) f.write("\n") self.pb.step() self.pb.update_idletasks() print() print("Done") def search(self): self.pb.start(5) # start the progressbar with 5 millisecond interval # get the text out of the entry widget url = self.e1.get() # url or list of url's logLoc = self.e2.get() # location to save to log file to sText = self.e3.get() # string to search for print(url) #print(type(url)) print(sText) print(type(sText)) print(logLoc) # Lets parse the string from the dialog box # This case is if a url is typed directly into the dialog box if url[0] == "h" and url[1] == "t" and url[2] == "t" and url[3] == "p": # print("in if") self.urlSearch(url, logLoc, sText) else: # This case is to support opening a file and getting the url or url's lineCount = 0 with open(url) as f: for lines in f: URL = f.readline() # print(URL) # If there is a empty line in the file pass if URL in ['\n', '\r\n']: print("emptyline found") #pass # if its the end of the file break out of the loop elif URL == '': break else: self.urlSearch(URL, logLoc, sText) lineCount += 1 print("%i lines read" % lineCount) self.pb.stop() # stop the progressbar self.e1.delete(0, END) # delete the text from the entry widget self.e2.delete(0, END) self.e3.delete(0, END) self.master.destroy() # after the search is finished close the window
class waitWindowProgressBar(Toplevel): def __init__(self, parent=None): """ Initialises the calculate wait window. Waits for other processes to finish, then packs everything. messages, setup_dataset and stop are the functions that change the layout of the frame. """ super().__init__(parent) self.title("Setting up.......") #self.attributes("-topmost", True) self.pb_val = IntVar(self) self.pb_val.set(0) self.pb = Progressbar(self, length=400, variable=self.pb_val) self.pb.pack(pady=20, padx=20) self.pb.configure(maximum=10) self.labeltext = StringVar() self.labeltext.set("Waiting for other process.....") self.waiting_label = Label(self, textvariable=self.labeltext) self.waiting_label.configure(anchor="center") self.waiting_label.pack(pady=20, padx=20, fill='both', expand=True) self.stopbutton = Button(self, text="Stop!", compound="bottom", command=self.stop) self.stopbutton.pack(side="left", fill="x", expand=True) self.stopflag = 0 self.update() def stop(self): """ Sets the stopflag to 1, thus stopping the calculation. """ self.stopflag = 1 def setup_dataset(self, dataset): """ Sets up the calculation wait window for the different stages of calculation. """ self.dataset = dataset self.title("Calculating Dataset %s" % os.path.basename(dataset.path)) self.waiting_label.pack(pady=20, padx=20) self.update() def errormessage(self, dataset): messagebox.showwarning( "Invalid parameters", "Dataset %s was skipped in the computation because of invalid parameters. Please configure Cut-off frequency and / or Filter type." % os.path.basename(dataset.path)) def return_function(self): """ Returns two functions for further use in the model. """ @ri.rternalize def messages(i, r, each): """ Messages function given to the R environment. Gives feedback on the state of the Monte-Carlo simulation. """ self.pb.step() count = np.asarray((i, r)) if (count[0] == -1): self.title("Computation for Dataset %s" % os.path.basename(self.dataset.path)) self.pb.pack(pady=20, padx=20) self.pb_val.set(0) self.stopbutton["state"] = "normal" if self.dataset.metadata[ "Method"] == "HILDE-Homogeneous" or self.dataset.metadata[ "Method"] == "HILDE-Heterogeneous": self.pb.configure(maximum=int( self.dataset.metadata["Repetitions_Hilde"])) else: self.pb.configure( maximum=int(self.dataset.metadata["Repetitions"])) self.labeltext.set( "Currently computing quantile for Dataset:\n%s \n Press Stop! button to stop computation for current dataset." % os.path.basename(self.dataset.path)) if (count[0] == -2): self.pb.pack_forget() self.labeltext.set( "Calculating fit for Dataset:\n%s\nThis computation cannot be interrupted and may take a few minutes." % os.path.basename(self.dataset.path)) self.stopbutton["state"] = "disabled" self.waiting_label.pack(pady=20, padx=20) self.update() return self.stopflag return messages, self.setup_dataset, self.errormessage
class Application(Frame): bground = "#4fa334" fground = "white" infoLabelsFont = "none 12 bold" valueLabelsFont = "none 12" infoLabelsWidth = 20 valueLabelsWidth = 7 def create_widgets(self): self.std_info_label["text"] = "Standard deviation: " self.var_info_label["text"] = "Variance: " self.avg_info_label["text"] = "Average: " self.min_info_label["text"] = "Min: " self.max_info_label["text"] = "Max: " self.std_value_label["text"] = "0" self.var_value_label["text"] = "0" self.avg_value_label["text"] = "0" self.min_value_label["text"] = "0" self.max_value_label["text"] = "0" self.progress["length"] = 300 self.progress["maximum"] = self.iterations self.std_info_label.grid(row=0, column=0, sticky=E) self.var_info_label.grid(row=1, column=0, sticky=E) self.avg_info_label.grid(row=2, column=0, sticky=E) self.min_info_label.grid(row=3, column=0, sticky=E) self.max_info_label.grid(row=4, column=0, sticky=E) self.std_value_label.grid(row=0, column=1) self.var_value_label.grid(row=1, column=1) self.avg_value_label.grid(row=2, column=1) self.min_value_label.grid(row=3, column=1) self.max_value_label.grid(row=4, column=1) canvas = FigureCanvasTkAgg(self.figure, self) canvas.draw() canvas.get_tk_widget().grid(row=5, columnspan=2) self.progress.grid(row=6, columnspan=2) def __init__(self, iterations=100, master=None): Frame.__init__(self, master) self.iterations = iterations # default self.configure(bg=self.bground) self.figure = Figure(figsize=(7, 5), dpi=100) self.graph = self.figure.add_subplot(111) self.std_info_label = Label(self, bg=self.bground, fg=self.fground, font=self.infoLabelsFont, width=self.infoLabelsWidth) self.var_info_label = Label(self, bg=self.bground, fg=self.fground, font=self.infoLabelsFont, width=self.infoLabelsWidth) self.avg_info_label = Label(self, bg=self.bground, fg=self.fground, font=self.infoLabelsFont, width=self.infoLabelsWidth) self.min_info_label = Label(self, bg=self.bground, fg=self.fground, font=self.infoLabelsFont, width=self.infoLabelsWidth) self.max_info_label = Label(self, bg=self.bground, fg=self.fground, font=self.infoLabelsFont, width=self.infoLabelsWidth) self.std_value_label = Label(self, bg=self.bground, fg=self.fground, font=self.valueLabelsFont, width=self.valueLabelsWidth) self.var_value_label = Label(self, bg=self.bground, fg=self.fground, font=self.valueLabelsFont, width=self.valueLabelsWidth) self.avg_value_label = Label(self, bg=self.bground, fg=self.fground, font=self.valueLabelsFont, width=self.valueLabelsWidth) self.min_value_label = Label(self, bg=self.bground, fg=self.fground, font=self.valueLabelsFont, width=self.valueLabelsWidth) self.max_value_label = Label(self, bg=self.bground, fg=self.fground, font=self.valueLabelsFont, width=self.valueLabelsWidth) self.progress = Progressbar(self) self.pack() self.create_widgets() def values_changed(self, std, var, avg, minimum, maximum): self.std_value_label["text"] = repr(round(std, 2)) self.var_value_label["text"] = repr(round(var, 2)) self.avg_value_label["text"] = repr(round(avg, 2)) self.min_value_label["text"] = repr(round(minimum, 2)) self.max_value_label["text"] = repr(round(maximum, 2)) self.progress.step() self.master.update() def set_iterations(self, iterations): self.iterations = iterations
de = DateEntry(user_entry_frame) user_entry_frame.pack(anchor = NW) data_out_frame.pack(anchor = NW, fill = BOTH, expand = 1) msg_frame.pack(anchor = NW, fill = BOTH) plu_entry.pack(side = LEFT) s_y.pack(side=RIGHT, fill=Y) tv.pack(anchor = NW, fill = BOTH, expand = 1) s_x.pack(fill=X) pb.pack(fill=X) msg.pack(fill=X, padx = 15, pady = 2) de.pack(side = LEFT, padx = 5) #passing function with argument to command trigger it right away. using partial to delay it until click #or using lamda: call_retrieve(tv) c = ttk.Button(user_entry_frame, text="Retrieve", command = partial(call_retrieve, tv, plu_entry, de, tk_var, pb)).pack(side = LEFT, padx = 5) c = ttk.Button(user_entry_frame, text="Retrieve new", command = partial(call_retrieve_new, tv, plu_entry, de, tk_var, pb)).pack(side = LEFT, padx = 5) pb.start(500) pb.step() gui.mainloop() def property_(_func): you passing a.getter() define an inner wrapper function inside wrapper call a.getter() and adding more behavior finally_ return_ wrapper
class Game(object): def __init__(self, board): self.board = board #set global graphics self.window = Tk() self.window.wm_title('Jeu de la vie') self.window.title('Jeu de la vie') self.cellFrame = Frame(self.window) self.cellFrame.pack() #create special content self.settings = Settings(self) self.detector = PeriodDetector(self.settings.period_study_count) #create cell button set self.cells = {CellButton(cell, self.cellFrame) for cell in self.board} #add buttons self.buttonFrame = Frame(self.window) self.buttonFrame.pack() self.__loaded = False self.load_buttons() self.playbut = Button(self.buttonFrame, command=self.simulate, text='Play') self.playbut.grid(row=0, column=1) self.bar = Progressbar(self.buttonFrame, orient="horizontal", mode='determinate') self.bar['value'] = 0 self.bar.grid(row=0, column=0, padx=10) #set up menu on the top of the window self.menu = Menu(self.window) self.fichier = Menu(self.menu, tearoff=0) self.menu.add_cascade(menu=self.fichier, label='File') self.fichier.add_command(label='Open', command=self.loadf, underline=0) self.fichier.add_command(label='Save as', command=self.savef, underline=0) self.edit = Menu(self.menu, tearoff=0) self.menu.add_cascade(menu=self.edit, label='Edit') self.edit.add_command(label='Empty', command=self.empty_board, underline=0) self.tools = Menu(self.menu, tearoff=0) self.menu.add_cascade(menu=self.tools, label='Tools') self.tools.add_command(label='Settings', command=self.open_settings, underline=0) self.window.config(menu=self.menu) #launch main program self.window.mainloop() def update_board(self): for c in self.cells: c.update_cell_color() self.window.update() def force_update_board(self): for c in self.cells: c.update_cell_color() c.update() self.window.update() def empty_board(self): self.board.empty() self.update_board() def simulate(self): if not self.board.is_empty: self.playbut['state'] = 'disabled' #get the number of generations to simulate gnc = 1_000_000 if self.settings.infinite_play else int( self.box.get()) self.bar['maximum'] = gnc self.bar['value'] = 0 if self.detector.period_observer != self.settings.period_study_count: self.detector.period_observer = self.settings.period_study_count if not self.detector.last == self.board.dump(): self.detector.empty() self.detector.add_dump(self.board.dump()) for _ in range(gnc): if not self.board.is_empty: self.board.evolve() self.bar.step(1) if not self.settings.play_in_background: self.update_board() self.detector.add_dump(self.board.dump()) p = self.detector.detect_period if p: if p == 1: showinfo("Stable system", "Actual cell system is stable.") break else: showinfo('Period detected', f'Actual system has period {p}') break if self.settings.play_in_background: self.update_board() self.playbut['state'] = 'normal' def loadf(self): path = askopenfilename(initialdir=getcwd(), title='Select file', filetypes=(("lifegame files", "*.lg"), ("all files", "*.*"))) if path: self.board.open(path) self.update_board() def savef(self): path = asksaveasfilename(initialdir=getcwd(), title='Save as...', filetypes=(("lifegame files", "*.lg"), )) if path: self.board.save(path) def open_settings(self): f = Tk() f.title('Settings') toggles = Frame(f) toggles.pack() Label(toggles, text='Studied period : ').grid(row=0, column=0) t = StringVar(toggles) t.set(str(self.settings.period_study_count)) study = Spinbox(toggles, from_=1, to=100, increment=1, justify='center', wrap=True, width=3, textvariable=t) study.grid(row=0, column=1) Label(toggles, text='Play in background : ').grid(row=1, column=0) hide = ToggleButton( toggles, text='Yes' if self.settings.play_in_background else 'No') hide.grid(row=1, column=1) Label(toggles, text='Infinite play : ').grid(row=2, column=0) infinite = ToggleButton( toggles, text='Yes' if self.settings.infinite_play else 'No') infinite.grid(row=2, column=1) confirm = Frame(f) confirm.pack() def confirmer(): self.settings.period_observer = int(study.get()) self.settings.play_in_background = hide.actual_toggle self.settings.infinite_play = infinite.actual_toggle self.load_buttons() f.destroy() Button(confirm, text='Ok', command=confirmer).pack() def load_buttons(self): if self.__loaded: self.box.destroy() if not self.settings.infinite_play: self.box = Spinbox(self.buttonFrame, from_=1, to=1000, increment=1, justify='center', wrap=True, width=5) self.box.grid(row=0, column=2) self.__loaded = True
class BasicDBOut: ''' basic output for database retrieve: a TreeView, a Button, and a Message screen ''' def __init__(self, gui, ue_label, with_button=0): self.parent_gui = gui self.user_entry_frame = Frame(self.parent_gui, padx=2, pady=5) self.data_out_frame = Frame(self.parent_gui, padx=2, pady=5) self.msg_frame = Frame(self.parent_gui, padx=2, pady=5) self.s = ttk.Style() self.s.configure('self.Treeview', rowheight=15) self.user_entry_label = Label(self.user_entry_frame, text=ue_label) self.s_y = Scrollbar(self.data_out_frame) self.s_x = Scrollbar(self.data_out_frame, orient=HORIZONTAL) self.tv = ttk.Treeview(self.data_out_frame, style='self.Treeview', yscrollcommand=self.s_y.set, xscrollcommand=self.s_x.set) self.s_y.config(command=self.tv.yview) self.s_x.config(command=self.tv.xview) self.msg = StringVar() #showing completion or error message self.msg_bar = Label(self.msg_frame, textvariable=self.msg, bg='white', fg='blue') self.prg_bar = Progressbar(self.msg_frame, mode='indeterminate') self.user_entry = Entry(self.user_entry_frame) self.user_date_pick = DateEntry(self.user_entry_frame) if with_button: self.retrieve_button = ttk.Button(self.user_entry_frame, text="Retrieve", command=None) def basic_setting(self, *args): self.user_entry_frame.pack(anchor=NW) self.data_out_frame.pack(anchor=NW, fill=BOTH, expand=1) self.msg_frame.pack(anchor=NW, fill=BOTH) self.user_entry_label.pack(side=LEFT) self.user_entry.pack(side=LEFT) self.user_entry.insert(0, "959714") self.s_y.pack(side=RIGHT, fill=Y) self.tv.pack(anchor=NW, fill=BOTH, expand=1) self.s_x.pack(fill=X) self.prg_bar.pack(fill=X) self.prg_bar.start(500) self.prg_bar.step() self.msg_bar.pack(fill=X, padx=15, pady=2) self.user_date_pick.pack(side=LEFT, padx=5) if hasattr(self, 'retrieve_button'): self.retrieve_button.pack(side=LEFT, padx=5) # self.retrieve_button.configure(command = partial(button_func, *button_func_args)) self.retrieve_button.configure( command=partial(self.button_callback, *args)) def __call__( self): #holder to implement this module to callable object later print(repr(self), 'is now callable and got called') def __repr__(self): return str(BasicDBOut) + '(Obj, NOT class):' def button_callback(self, sql_result): try: col_names, recs = sql_result except Exception as e: db_err = e.args[1] if e.args[1:2] else e.args[ 0] #check args[1] exist. Return [] if args[1] NOT exist while check directly on args[1] will throw exception if it NOT exist i = db_err.find(':') #exception is tuple of args strings if i > 0: db_err = db_err[:i] print(db_err) self.msg.set(db_err) return self.tv.delete(*self.tv.get_children( )) #return list of children of root and splatted(unpack list) self.tv['columns'] = [col_name for col_name in col_names] self.tv['show'] = 'headings' for col_name in col_names: self.tv.heading(col_name, text=col_name) self.tv.column(col_name, anchor='center', stretch=0) if recs: for rec in recs: self.tv.insert( "", 0, text=str(rec[0]), value=list(rec) ) #value accepts list, but rec is tuple, so need convert to list self.msg.set('Plu: {}, Date: {}\n Recs: {}'.format( self.user_entry, self.user_date_pick, len(recs))) else: self.msg.set('Plu: {}, Date: {}\n No Recs Found'.format( self.user_entry, self.user_date_pick)) self.prg_bar.stop() #=============================================================================== # if __name__ == '__main__': # gui = Tk() # gui.title("Find Active MP") # gui.geometry("900x500") # # basic_dbout = BasicDBOut(gui, 1) # # plu_label = Label(basic_dbout.user_entry_frame ,text="Short Plu").pack(side = LEFT) # # basic_dbout.basic_setting() # # gui.mainloop() #===============================================================================
class BasicDBOut: ''' basic output for database retrieve: a TreeView, a Button, and a Message screen ''' @staticmethod def thread_db_retrieve(inst, *wg_args): #inst is inst of self, got passed in command='...' inst.msg.set('Retrieving data. Please wait...') t = Thread(target=inst.button_callback, args=wg_args) t.start() def __init__(self, gui, ue_label, with_button=0): self.parent_gui = gui self.db_access = None self.user_entry_frame = Frame(self.parent_gui, padx = 2, pady = 5) self.data_out_frame = Frame(self.parent_gui, padx = 2, pady = 5) self.msg_frame = Frame(self.parent_gui, padx = 2, pady = 5) self.s = ttk.Style() self.s.configure('self.Treeview', rowheight=15) self.user_entry_label = Label(self.user_entry_frame, text=ue_label) self.s_y = Scrollbar(self.data_out_frame) self.s_x = Scrollbar(self.data_out_frame, orient=HORIZONTAL) self.tv = ttk.Treeview(self.data_out_frame, style='self.Treeview', yscrollcommand=self.s_y.set, xscrollcommand = self.s_x.set) self.s_y.config(command=self.tv.yview) self.s_x.config(command=self.tv.xview) self.msg = StringVar() #showing completion or error message self.msg_bar = Label(self.msg_frame ,textvariable=self.msg, bg = 'white', fg = 'blue') self.prg_bar = Progressbar(self.msg_frame, mode='indeterminate') self.user_entry = Entry(self.user_entry_frame) self.user_date_pick = DateEntry(self.user_entry_frame) if with_button: #need use lambda to pass self as arg. thread_db_retrieve(...) is staticmethod, so self.thread_db_retrieve doesn't bind into bound method obj self.retrieve_button = ttk.Button(self.user_entry_frame, text="Retrieve", command = lambda: self.thread_db_retrieve(self)) def basic_setting(self, *args): self.user_entry_frame.pack(anchor = NW) self.data_out_frame.pack(anchor = NW, fill = BOTH, expand = 1) self.msg_frame.pack(anchor = NW, fill = BOTH) self.user_entry_label.pack(side = LEFT) self.user_entry.pack(side = LEFT) self.user_entry.insert(0, "959714") self.s_y.pack(side=RIGHT, fill=Y) self.tv.pack(anchor = NW, fill = BOTH, expand = 1) self.s_x.pack(fill=X) self.prg_bar.pack(fill=X) self.prg_bar.start(500) self.prg_bar.step() self.msg_bar.pack(fill=X, padx = 15, pady = 2) self.user_date_pick.pack(side = LEFT, padx = 5) if hasattr(self, 'retrieve_button'): self.retrieve_button.pack(side = LEFT, padx = 5) # self.retrieve_button.configure(command = partial(button_func, *button_func_args)) def __call__(self): #holder to implement this module to callable object later print(repr(self), 'is now callable and got called') def __repr__(self): return str(BasicDBOut) + '(Obj, NOT class):' def retrv_db(self): try: db_return = self.db_access.connect_retrieve_db() except Exception as e: # db_err = e.args[1] if e.args[1:2] else e.args[0] #check args[1] exist. Return [] if args[1] NOT exist while check directly on args[1] will throw exception if it NOT exist db_err = e.args[1:2] or e.args[0] #ATTENTION!!: A = ((X and Y) or Z). if Y evaluates to 'False', CAN'T use it replace if...else... #semantic: evaluate left to right, on False return the latest item i = db_err.find(':') #exception is tuple of args strings if i > 0: db_err = db_err[:i] print(db_err) self.msg.set(db_err) raise #re-raise previous exception return db_return def button_callback(self): try: col_names, recs = self.retrv_db() except Exception as ee: print(ee) return #already handle in retrv_db self.tv.delete(*self.tv.get_children()) #return list of children of root and splatted(unpack list) self.tv['columns'] = [col_name for col_name in col_names] self.tv['show'] = 'headings' for col_name in col_names: self.tv.heading(col_name, text=col_name) self.tv.column(col_name, anchor='center', stretch = 0) if recs: for rec in recs: self.tv.insert("", 0, text = str(rec[0]), value=list(rec)) #value accepts list, but rec is tuple, so need convert to list self.msg.set('Plu: {}, Date: {}\n Recs: {}'.format(self.user_entry, self.user_date_pick, len(recs))) else: self.msg.set('Plu: {}, Date: {}\n No Recs Found'.format(self.user_entry, self.user_date_pick)) self.prg_bar.stop() #=============================================================================== # if __name__ == '__main__': # gui = Tk() # gui.title("Find Active MP") # gui.geometry("900x500") # # basic_dbout = BasicDBOut(gui, 1) # # plu_label = Label(basic_dbout.user_entry_frame ,text="Short Plu").pack(side = LEFT) # # basic_dbout.basic_setting() # # gui.mainloop() #===============================================================================
def evaluate(scoresMatrice): print("evaluation en cours...\n") global refFile global hypFile global refSent global hypSent # fenetre de chargement popup_window = Toplevel() popup_window.title("Evaluation") label = Label(popup_window, text="Please wait during the scores calculus...") label.pack() p = Progressbar(popup_window, orient=HORIZONTAL, length=200, mode="determinate", takefocus=True, maximum=len(refSent)) p.pack() x = root.winfo_screenwidth() / 2 y = root.winfo_screenheight() / 2 popup_window.geometry('+%d+%d' % (x, y)) # score bleu pour tout le fichier #bleuScoreFile=file_bleu(refFile,hypFile)/100 #print("bleu total= ",bleuScoreFile) refSent = file_to_listeSentence(refFile) hypSent = file_to_listeSentence(hypFile) i = 1 str_score = '' scoresMatrice.append( ('Numéro de phrase', 'Phrase de référence', 'Phrase à évaluer', 'Bleu', 'Score Nist', 'Score Meteor', 'Score Wer', 'Score Ter', 'Score characTER', 'Score Rouge1', 'Score RougeL', 'Score de Fuzzy Matching')) fuzzyScores = list() for r, h in zip(refSent, hypSent): # decomposition au mot pour le calcul des scores nist, wer, ter rw = r.split(" ") hw = h.split(" ") #bleu sentScoreBleu = bleu(r, h) #nist nistScore = nist(rw, hw) #meteor meteorScore = meteor(r, h) # wer werScore = wer(rw, hw) #ter terScore = ter(rw, hw) #characTER characTerScore = characTer(r, h) #rouge rougeScores = rouge(r, h) rouge1 = rougeScores[0] rougeL = rougeScores[1] ###### FUZZY MATCHING #print("---- Fuzzy Matching: Phrase ",str(i)) #fuzzyScores.append(fuzzymatch(r,h)) fuzzyScr = fuzzymatch(r, h) # affichage et stockage des données dans la matrice des scores str_score += '* Sent.' + str(i) + ': - Bleu = ' + str( sentScoreBleu ) + ' - Nist = ' + str(nistScore) + ' - Meteor = ' + str( meteorScore) + ' - Wer = ' + '{:.0f}%'.format( werScore) + '% - Ter = ' + str( terScore) + '% - CharacTer = ' + str( characTerScore) + '% - Rouge1 = ' + str( rouge1) + ' - RougeL = ' + str( rougeL) + ' - FM = ' + str(fuzzyScr) + '\n' scoresMatrice.append( (str(i), r, h, str(sentScoreBleu), str(nistScore), str(meteorScore), '{:.0f}%'.format(werScore), str(characTerScore), str(terScore), str(rouge1), str(rougeL), str(fuzzyScr))) i += 1 p.step() root.update() #### fin de la boucle for #print("**** FUZZY SCORES: ******") #print(fuzzyScores) popup_window.destroy() t4.delete('1.0', END) t4.insert(END, str_score)
class MainFrame(Frame): ''' This class implements main GUI of the application. Attributes: parent (Tk object): parent of this frame (Tk()). params_frame (ParamsFrame): frame with parameters. data_frame (DataFrame): frame with data and solution. progress_bar (Progressbar): progress bar widget. increment (int): progress bar increment, it is modified in other classes that are responsible for solving the problem and update progress. weights_status_lbl (Label): label that displays if weight restrictions are feasible. weights_status_str (StringVar): StringVar object used for tracking if weight restrictions are feasible. current_categories (list of str): list of current categories. Args: parent (Tk object): parent of this frame (Tk()). ''' def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.parent = parent self.params_frame = None self.data_frame = None self.progress_bar = None self.increment = 0 self.weights_status_lbl = None self.weights_status_str = StringVar() self.weights_status_str.trace('w', self.on_weights_status_change) self.current_categories = [] self.create_widgets() def create_widgets(self): ''' Creates all widgets that belong to this frame. ''' self.parent.title('pyDEA') self.pack(fill=BOTH, expand=1) self.columnconfigure(0, weight=1, pad=5) self.columnconfigure(1, weight=0, pad=5) self.rowconfigure(0, pad=3, weight=1) self.rowconfigure(1, pad=3) self.rowconfigure(2, pad=3) self.rowconfigure(3, pad=3) self.current_categories = [] data_from_params_file = StringVar() str_var_for_input_output_boxes = ObserverStringVar() self.params_frame = ParamsFrame(self, self.current_categories, data_from_params_file, str_var_for_input_output_boxes, self.weights_status_str) data_frame = DataFrame(self, self.params_frame, self.current_categories, data_from_params_file, str_var_for_input_output_boxes) self.data_frame = data_frame data_frame.grid(row=0, column=0, sticky=N + S + W + E, padx=15, pady=15) self.params_frame.grid(row=0, column=1, sticky=W + E + S + N, padx=15, pady=15, columnspan=2) lbl_progress = Label(self, text='Progress') lbl_progress.grid(row=1, column=0, sticky=W, padx=10, pady=5) self.progress_bar = Progressbar(self, mode='determinate', maximum=100) self.progress_bar.grid(row=2, column=0, sticky=W + E, padx=10, pady=5) run_btn = Button(self, text='Run', command=self.run) run_btn.grid(row=2, column=1, sticky=W, padx=10, pady=10) self.weights_status_lbl = Label(self, text='', foreground='red') self.weights_status_lbl.grid(row=2, column=2, padx=10, pady=5, sticky=W) def on_weights_status_change(self, *args): ''' This method is called when weight restrictions status is changed. ''' self.weights_status_lbl.config(text=self.weights_status_str.get()) def run(self): ''' This method is called when the user presses Run button. Solves the problem and displays solution. ''' clean_up_pickled_files() params = self.params_frame.params run_method = RunMethodGUI(self) run_method.run(params) def construct_categories(self): ''' Returns current categories. Returns: (list of str): list of current categories ''' return [ category.strip() for category in self.current_categories if category ] def on_dmu_change(self, *args): ''' Updates progress bar. ''' self.progress_bar.step(self.increment) self.progress_bar.update()
def write_all_scores_into_csv(menu): scoresSent = [] scorename = [ 'bleu', 'nist', 'meteor', 'wer', 'ter', 'characTER', 'rouge1', 'rougeL', 'fuzzymatching' ] nbScores = len(scorename) csv = askopenfilename(initialdir="./", title="Select a csv to analyse", filetypes=(("csv files", "*.csv"), )) #stp contains (source,target,predictions) stp = openLearningCsv(csv) nTest = 10 epoch = 0 #creation of the dictionnary # first we put the source sentences and the target sentences into a dataframe d = {stp[0][0]: stp[0][1:], stp[1][0]: stp[1][1:]} df = pd.DataFrame(d) # headers insertion into the dataframe num = 1 nbRow = len(stp[2]) #nbRow=nTest #test nbCol = len(stp[2][0]) # fenetre de chargement popup_window = Toplevel() popup_window.title = "Generation of the csv file" label = Label(popup_window, text="Please wait during the scores calculus...") label.pack() p = Progressbar(popup_window, orient=HORIZONTAL, length=200, mode="determinate", takefocus=True, maximum=nbCol) p.pack() x = menu.winfo_screenwidth() / 2 y = menu.winfo_screenheight() / 2 popup_window.geometry('+%d+%d' % (x, y)) start = time.time() for col in range(nbCol): p.step() menu.update() num += 1 pred_col_name = stp[2][0][col] # insertion of the prediction strings of a same column predSingleCol = [] for i in range(1, nbRow): predSingleCol.append(stp[2][i][col]) df.insert(num, pred_col_name, pd.Series(predSingleCol)) if (num - 2) % 6 == 0: epoch += 1 #print("EPOCH ",epoch) #wordnet.ensure_loaded() # scores calculus for a single column scoresColumn = scoresProcessingColumn_SentThreads( stp[1][1:], predSingleCol) # insertion of the scores for i in range(nbScores): num += 1 score_col_name = scorename[i] + " (" + pred_col_name + ") " currentScoreArray = [] for j in range(len(scoresColumn)): currentScoreArray.append(scoresColumn[j][i]) #print(scoresColumn[j][i]) df.insert(num, score_col_name, pd.Series(currentScoreArray), True) #print(df) popup_window.destroy() end = time.time() print("ELAPSED TIME:::: ", end - start) # write dataframe to csv df.to_csv('AllScore.csv', index=False, header=True) print("--- export completed ---")
class Gui: def __init__(self, master=None): self.master = Tk() if not master else master self.master.title("Book Finder") self.master.resizable(0, 0) #We change the window icon directly with Tk self.master.tk.call('wm', 'iconphoto', self.master, '::tk::icons::question') self.stext = ScrolledText(master=self.master, bg='white', height=25, width=100) #We disable the edition self.stext.config(state="disabled") menu = Menu() menu_tools = Menu(tearoff=0) menu_tools.add_command(label="Search book", command=lambda: self.search_book()) menu_tools.add_command(label="Exit", command=self.master.destroy) menu.add_cascade(label="Menu", menu=menu_tools) menu_option = Menu(tearoff=0) menu_option.add_checkbutton( label="Don't download img", command=lambda: self.cmd2() if self.cmd2 else print("cmd2 not configured")) menu.add_cascade(label="Option", menu=menu_option) #We create a message box with Tk menu.add_command( label="About", command=lambda: self.master.tk.eval( "tk_messageBox -message {Book Finder} -detail {Make by pythonbrad} -icon info -title About" )) self.master.config(menu=menu) self.stext.pack() #This widget will print status self.label_status = Label(self.master, text="STATUS", font=('Arial', 14)) self.label_status.pack() self.progress_bar = Progressbar() self.progress_bar.pack() self.is_searching = False #It will contains widget in memory self.temp = [] #It will contains an external function #Who will be used by the function search_book self.cmd1 = None self.cmd2 = None def insert_img(self, data): #We convert image date in tk image data self.stext.image_create(END, image=self.get_img_tk(data)) def insert_text(self, text, tag=None): #We insert the text self.stext.config(state="normal") self.stext.insert(END, text, tag) self.stext.config(state="disabled") def create_tag(self, tag_name, **args): self.stext.tag_config(tag_name, **args) def get_img_tk(self, data): img = ImageTk.PhotoImage(data=data) self.temp.append(img) return img def progress_bar_reset(self, max_value): self.progress_bar.config(max=max_value, value=0) def progress_bar_step(self): self.progress_bar.step(1) def search_book(self): try: self.win_search_book.destroy() except: pass if not self.is_searching: self.win_search_book = Toplevel() self.win_search_book.tk.call('wm', 'iconphoto', self.win_search_book, '::tk::icons::question') Label(self.win_search_book, image='::tk::icons::question').pack() Label(self.win_search_book, text="Enter a keyword").pack() search_entry = Entry(self.win_search_book) search_entry.pack() def _(self, search_entry): #the data will return in the arg data to this command self.cmd1(search_entry.get()) self.win_search_book.destroy() Button( self.win_search_book, text="Search", #We given the self and the search text #The self will give the access to this object command=lambda: _(self, search_entry) if self.cmd1 else print("cmd1 not configured")).pack() self.win_search_book.mainloop() else: self.master.tk.eval( "tk_messageBox -message {A research aleady running} -icon warning" ) def update(self): self.master.update() def mainloop(self): self.master.mainloop()
def update_progress(progress_bar: ttk.Progressbar, increment: int, gui_root: Tk): progress_bar.step(increment) gui_root.update()
class AppTracker(Frame): def __init__(self, parent): Frame.__init__(self, parent) # widgets self._status_label = Label(parent, anchor="w", font=("Gisha", 8), text="", background="#d9d9d9", foreground="#3f3f3f") self._status_label.grid(sticky="NEWS", row=1, rowspan=1, column=0, columnspan=3, ipady=1) self._progress_bar = Progressbar(parent, maximum=40, mode='determinate', orient="horizontal") self._loading_bar = Progressbar(parent, maximum=40, mode='indeterminate', orient="horizontal") # self._preset_button = Button(parent, border=0, font=("Gisha", 8), text="Change preset file..") # self._preset_button.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) @property def loading_bar(self): return self._loading_bar @property def progress_bar(self): return self._progress_bar @property def status_label(self): return self._status_label # @property # def preset_button(self): # return self._preset_button def show_loading_bar(self): self._loading_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._loading_bar.update_idletasks() def hide_loading_bar(self): self._loading_bar.stop() self._loading_bar.grid_forget() self._loading_bar.update_idletasks() def show_progress_bar(self): self._progress_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._progress_bar.update_idletasks() def hide_progress_bar(self): self._progress_bar.grid_forget() self._progress_bar.update_idletasks() def update_status_label(self, text): self._status_label.configure(text=text) self._status_label.update_idletasks() def update_progress_bar(self, value): self._progress_bar['value'] = value self._progress_bar.update_idletasks() def update_loading_bar(self, value): self._loading_bar.step(value) self._loading_bar.update_idletasks()
class VentanaPrincipal: def _init_(self, master): self.master = master master.title("SO1_Proyecto1") self.label = Label( master, text="Ingresa los parametros y opciones para enviar el trafico.") self.label.pack() # >>>>>>>>>>>>>>>>>>>>>>> URL <<<<<<<<<<<<<<<<<<<<<<<<< self.frame1 = Frame(master) self.frame1.pack(fill=X) self.lblUrl = Label(self.frame1, text="URL", width=10) self.lblUrl.pack(side=LEFT, padx=5, pady=5) self.txtUrl = Entry(self.frame1) self.txtUrl.pack(fill=X, padx=5, expand=True) self.txtUrl.insert(END, valorurl) # >>>>>>>>>>>>>>>>>>>>>>> Concurrencia <<<<<<<<<<<<<<<<<<<<<<<<< self.frame2 = Frame(master) self.frame2.pack(fill=X) self.lblConcurrencia = Label(self.frame2, text="Concurrencia", width=10) self.lblConcurrencia.pack(side=LEFT, padx=5, pady=5) self.spinConcurrencia = Spinbox(self.frame2, from_=1, to=100000) self.spinConcurrencia.pack(fill=X, padx=5, expand=True) # >>>>>>>>>>>>>>>>>>>>>>> Solicitudes <<<<<<<<<<<<<<<<<<<<<<<<< self.frame3 = Frame(master) self.frame3.pack(fill=X) self.lblSolicitudes = Label(self.frame3, text="Solicitudes", width=10) self.lblSolicitudes.pack(side=LEFT, padx=5, pady=5) var = StringVar(root) var.set("5") self.spinSolicitudes = Spinbox(self.frame3, from_=0, to=100000, textvariable=var) self.spinSolicitudes.pack(fill=X, padx=5, expand=True) # >>>>>>>>>>>>>>>>>>>>>>> Timeout <<<<<<<<<<<<<<<<<<<<<<<<< self.frame4 = Frame(master) self.frame4.pack(fill=X) self.lblTimeout = Label(self.frame4, text="Timeout", width=10) self.lblTimeout.pack(side=LEFT, padx=5, pady=5) varTimeout = StringVar(root) varTimeout.set("100") self.spinTimeout = Spinbox(self.frame4, from_=1, to=100000, textvariable=varTimeout) self.spinTimeout.pack(fill=X, padx=5, expand=True) # >>>>>>>>>>>>>>>>>>>>>>> Parametros <<<<<<<<<<<<<<<<<<<<<<<<< self.frame5 = Frame(master) self.frame5.pack(fill=X) self.lblParametros = Label(self.frame5, text="Parametros", width=10) self.lblParametros.pack(side=LEFT, padx=5, pady=5) self.btnBuscar = Button(self.frame5, text="Buscar", command=self.onOpen) self.btnBuscar.pack(fill=X, padx=5, expand=True) self.frame6 = Frame(master) self.frame6.pack(fill=X) self.txt = Text(self.frame6, height=10, width=122) self.txt.pack(fill=X, padx=5, expand=True) # >>>>>>>>>>>>> Variables globales <<<<<<<<<<<<<<< global referenciaProgressBar global referenciaEnviados global referenciaProgreso global referenciaTxtStatus global referenciaTiempo global globalself self.frameProgress = Frame(master) self.frameProgress.pack(fill=X) self.progressbar = Progressbar(self.frameProgress) self.progressbar.place(width=200) self.progressbar.pack(side=RIGHT, padx=25) referenciaProgressBar = self.progressbar # ---------------------------------------- referenciaEnviados = StringVar(root) referenciaEnviados.set("Enviados 0/" + str(self.spinSolicitudes.get())) self.lblEnviados = Label(self.frameProgress, textvariable=referenciaEnviados, width=30) self.lblEnviados.pack(side=LEFT, padx=5) # ---------------------------------------- referenciaProgreso = StringVar(root) referenciaProgreso.set("Progreso 0%") self.lblProgreso = Label(self.frameProgress, textvariable=referenciaProgreso, width=20) self.lblProgreso.pack(side=LEFT, padx=15) # ----------------------------------------- referenciaTiempo = StringVar(root) referenciaTiempo.set("Tiempo Transucrrido[Seg] 0") self.lblTiempo = Label(self.frameProgress, textvariable=referenciaTiempo, width=35) self.lblTiempo.pack(side=LEFT, padx=55) globalself.append(self.lblEnviados) globalself.append(self.lblProgreso) globalself.append(self.frameProgress) # >>>>>>>>>>>>>>>>>>>>>>> Status <<<<<<<<<<<<<<<<<<<<<<<<< self.frame7 = Frame(master) self.frame7.pack(fill=X) self.lblParametros = Label(self.frame7, text="Status", width=10) self.lblParametros.pack(side=LEFT, padx=5, pady=5) self.btnEjecutar = Button(self.frame7, text="Ejecutar", command=self.enviarDatos) self.btnEjecutar.pack(fill=X, padx=5, expand=True) self.frame8 = Frame(master) self.frame8.pack(fill=X) self.txtStatus = Text(self.frame8, height=17, width=122) self.txtStatus.pack(fill=X, padx=5, expand=True) referenciaTxtStatus = self.txtStatus globalself.append(self.frame7) # >>>>>>>>>>>>>>>>>>>>>>> ____ <<<<<<<<<<<<<<<<<<<<<<<<< def onOpen(self): self.txt.delete(0.0, END) self.txt.insert(0.0, "") fl = filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=(("all files", "."), ("jpeg files", "*.jpg"))) if fl != '': text = self.readFile(fl) self.txt.insert(END, text) def readFile(self, filename): f = open(filename, "r") text = f.read() return text def enviarDatos(self): self.txtStatus.delete(0.0, END) self.txtStatus.insert(0.0, "") global arregloLineas global valorTimeout global contadorSolicitudes global valorurl global totalSolicitudes global avanceGlobal global tiempoTranscurrido self.progressbar.step(100 - avanceGlobal) avanceGlobal = 0 tiempoTranscurrido = 0 arregloLineas = [] valorTimeout = int(self.spinTimeout.get()) valorurl = self.txtUrl.get() valorurl = valorurl.replace("\n", "") for x in range(0, int(float(self.txt.index('end')))): arregloLineas.append(self.txt.get(x + 0.0, (x + 1) + 0.0)) totalSolicitudes = int(self.spinSolicitudes.get()) contadorSolicitudes = 0 # -------------------------------------------------------- c = Clock(valorTimeout) c.start() for x in range(0, int(self.spinConcurrencia.get())): mythread = MyThread(name="[Hilo-{}]".format(str(x))) mythread.start() avanzarProgressBar() actualizarTodo()
class widgets: def __init__(self, main): super().__init__() self.window = main # Set window title self.window.title('Create ReactJs Project') # Set window size self.window.geometry("720x530") #disable resizing self.window.resizable(False, False) # Set window background self.window.configure(bg='#262625') # choose application icon p1 = PhotoImage(file=f'{content.absolutePath}images/logo.png') # Setting icon of master window self.window.iconphoto(False, p1) #checking OS for future use status, result = subprocess.getstatusoutput(f"cd /d images") if status == 0: self.getOS = 'windows' else: self.getOS = 'linux' #create frames self.taskDone = False self.headerFrame = Frame(self.window, background="#262625") self.headerFrame.grid(row=0, column=0, sticky="NSEW", pady=10) self.footerFrame = Frame(self.window) self.createHeader() self.createFirstWindow() def createHeader(self): #creates global header for application self.titleIamge = Canvas(self.headerFrame, width=600, height=120, background="#262625", bd=0, highlightthickness=0) self.titleIamge.grid(row=0, column=0, padx=60) self.img = ImageTk.PhotoImage( Image.open(f"{content.absolutePath}images/titleIcon.png")) self.titleIamge.create_image(285, 80, image=self.img) def createFirstWindow(self): # creates first window self.contentFrame1 = Frame(self.window, background="#262625", highlightbackground="#42B3D2", highlightthickness=1, relief=tk.RAISED, borderwidth=0) self.contentFrame1.grid(row=1, column=0, sticky="NS", pady=10, padx=0) self.createForm() def createForm(self): #creates form for fisrt window # ================================= creation and placement of form labels ========================== # Label(self.contentFrame1, text="Select Project Directory", background="#262625", foreground="#c7c9c7", font=("", 10)).grid(row=0, column=0, sticky=tk.W + tk.N, padx=20, pady=23) Label(self.contentFrame1, text="Enter Project Name", background="#262625", foreground="#c7c9c7", font=("", 10)).grid(row=1, column=0, sticky=tk.W, padx=20, pady=10) Label(self.contentFrame1, text="Enter Project Version", background="#262625", foreground="#c7c9c7", font=("", 10)).grid(row=2, column=0, sticky=tk.W, padx=20, pady=10) Label(self.contentFrame1, text="Enter Project Description", background="#262625", foreground="#c7c9c7", font=("", 10)).grid(row=3, column=0, sticky=tk.W + tk.N, padx=20, pady=10) # ================================= creation and placements of form inputs ========================== # self.e1 = tk.Entry(self.contentFrame1, borderwidth=0, disabledbackground="#343634", disabledforeground="#c7c9c7", font=("Times New Roman", 12)) self.e1.grid(row=0, column=1, columnspan=2, padx=8) self.e1.insert(0, " -- nothing selected --") self.e1.configure(state='disabled') self.e2 = tk.Entry(self.contentFrame1, background="#343634", fg="#c7c9c7", borderwidth=0, font=("Times New Roman", 12)) self.e2.grid(row=1, column=1, columnspan=2, padx=8) self.e3 = tk.Entry(self.contentFrame1, background="#343634", fg="#c7c9c7", disabledbackground="#343634", disabledforeground="#c7c9c7", borderwidth=0, font=("Times New Roman", 12)) self.e3.grid(row=2, column=1, columnspan=2, padx=8) self.e3.insert(0, "1.0.0") self.e3.configure(state='disabled') #textarea for input self.textarea = st.ScrolledText(self.contentFrame1, width=18, height=4, borderwidth=0, highlightthickness=0, font=("Times New Roman", 12), background="#343634", fg="#c7c9c7") self.textarea.grid(row=3, column=1, columnspan=2, padx=6, pady=8) # ================================= creation and placements of action buttons ========================== # #for choose button self.folderimg = PhotoImage( file=f"{content.absolutePath}images/folderIcon.png") self.chooseBtn = tk.Button(self.contentFrame1, background="#262625", image=self.folderimg, borderwidth=0, highlightthickness=0, activebackground="#2b2b2a", cursor="hand1", command=self.selectFolder).grid(row=0, column=3, sticky=tk.W, pady=4) #generating information buttons messages = content.messages self.infoimg = PhotoImage( file=f"{content.absolutePath}images/infoIcon.png") for j in range(0, len(messages)): self.infoBtn = tk.Button( self.contentFrame1, image=self.infoimg, borderwidth=0, highlightthickness=0, background="#262625", activebackground="#2b2b2a", cursor="hand1", command=partial(self.messageWidget, messages[j][0], messages[j][1])).grid(row=j + 1, column=3, sticky=tk.W + tk.N, pady=10) #for submit button self.startimg = PhotoImage( file=f"{content.absolutePath}images/startIcon.png") self.submitBtn = tk.Button(self.contentFrame1, text="Start", borderwidth=0, highlightthickness=0, background="#1d84bf", foreground="white", activebackground="#2b2b2a", cursor="hand1", font=("", 12), command=self.processData).grid(row=5, column=1, sticky=tk.W + tk.E, padx=15, pady=20) # ================================= creation and placements of decorative images ========================== # self.graphicImage = Canvas(self.contentFrame1, width=130, height=140, background="#262625", bd=0, highlightthickness=0) self.graphicImage.grid(row=3, column=3, rowspan=3, padx=60) self.img2 = ImageTk.PhotoImage( Image.open(f"{content.absolutePath}images/graphics1.png")) self.graphicImage.create_image(70, 70, image=self.img2) #---------------- action functions --------------------------------------------------------------------------------# def selectFolder(self): #folder selection widget for form input self.folder_selected = filedialog.askdirectory() self.e1.configure(state='normal') self.e1.delete(0, last=len(self.e1.get())) self.e1.insert(0, self.folder_selected) self.e1.configure(state='disabled') def processData(self): #handling of form data once submitted #storing form data if self.e1.get() == ' -- nothing selected --': self.messageWidget( "Please select project directory.\nThis field can't be empty! ", "warning") elif re.search("[A-Za-z]", self.e2.get()) == None: self.messageWidget( "Empty Or Invalid value in Name field! Also this field requires at least one alphabet", "warning") elif re.search("[A-Za-z]", self.textarea.get("1.0", tk.END)) == None: self.messageWidget( "Empty Or Invalid value in Description field! Also this field requires at least one alphabet", "warning") else: self.dirPath = self.e1.get() self.name = self.e2.get() self.version = self.e3.get() self.description = self.textarea.get("1.0", tk.END) self.path = os.path.join(self.dirPath, self.name) os.mkdir(self.path) self.createSecondWindow() #!important creation of second window # ===================================== ++++++++++++++++++++++++++ =================================== # # ============================================ Second window ======================================== # # ===================================== ++++++++++++++++++++++++++ =================================== # def createSecondWindow(self): #second window initialization #distroy current widgets self.contentFrame1.destroy() self.contentFrame2 = Frame(self.window, background="#262625", highlightbackground="#42B3D2", highlightthickness=1, relief=tk.RAISED, borderwidth=0) self.contentFrame2.grid(row=1, column=0, sticky="NS", pady=10, padx=0) self.createProgressbar() self.createConsole() #cancle button to terminate process self.cancelBtn = tk.Button(self.contentFrame2, borderwidth=0, text="Terminate tasks", highlightthickness=0, background="#bf1d1d", activebackground="#2b2b2a", cursor="hand1", foreground="white", font=("", 12), command=self.cancelTask).grid(row=3, column=0, sticky=tk.W, pady=15, padx=250) self.fetchCommands() def cancelTask(self): #cancle processes if messagebox.askyesno( "Are you sure?", "Do you really wants to cancel installation process?"): self.contentFrame2.destroy() self.cleanDir() self.createFirstWindow() else: pass def updateFrame(self, ind): #frame updater function for gif(loader) self.frame = self.loaderFrames[ind] ind += 1 ind = ind % (len(self.loaderFrames) - 1) self.label.configure(image=self.frame) self.contentFrame2.after(200, self.updateFrame, ind) def createProgressbar(self): #main progressbar components #status label for progressbar self.statusLabel = Label(self.contentFrame2, text="initializing commands..", background="#262625", foreground="#c7c9c7", font=("", 10)) self.statusLabel.grid(row=0, column=0, sticky="NW", padx=55, pady=15) #loader gif self.loaderFrames = [ PhotoImage(file=f'{content.absolutePath}images/loader.gif', format='gif -index %i' % (i)) for i in range(24) ] self.label = Label(self.contentFrame2, background="#262625") self.label.grid(row=0, column=0, sticky="W", padx=25) self.contentFrame2.after(0, self.updateFrame, 0) #progressbar self.p = Progressbar(self.contentFrame2, orient=tk.HORIZONTAL, length=570, mode="determinate", takefocus=True, maximum=100) self.p.grid(row=1, column=0, sticky="E", padx=40, pady=5, ipady=0) def createConsole(self): #console creation #textarea for logs self.showLogsArea = st.ScrolledText(self.contentFrame2, width=61, height=8, borderwidth=0, highlightthickness=0, background="#343634", fg="#68D9B5", font=('arial', 12, 'normal')) self.showLogsArea.grid(row=2, column=0, columnspan=3, pady=10, padx=20) def printLogs(self, log, commandDesc=''): #inserts text in textarea self.statusLabel['text'] = commandDesc self.showLogsArea.configure(state='normal') # Inserting Text which is read only self.showLogsArea.update() last_char_visible = self.showLogsArea.bbox("end-1c") self.showLogsArea.insert(tk.INSERT, log) self.showLogsArea.update() if last_char_visible: self.showLogsArea.see("end") self.showLogsArea.configure(state='disabled') def runCommands(self, command, commandDesc): #core function for running commands #Acquiring and Releasing lock(mutex) to prevent deadlock and synchronization self.lock.acquire() self.printLogs( " > " + command + '\n' + '----------------------------------------------\n', commandDesc) #check for the node version if command == "node -v": result = subprocess.getoutput(f"node -v") result = re.search("v(\d+\.)", result).group() result = result[1:len(result) - 1] if int(result) < 10: self.messageWidget( "Node version 10 or above not detected! first install node with version 10 or above", "error") self.contentFrame2.destroy() os.killpg(os.getpgid(result.pid), signal.SIGTERM) self.cleanDir() self.createFirstWindow() cdCommand = {'linux': 'cd ', 'windows': 'cd /d '} status, result = subprocess.getstatusoutput( f"{cdCommand[self.getOS]}{self.path}&&{command}") if status != 0: self.messageWidget(f"Exit status : {status} \n{result}", "error") self.cleanDir() self.contentFrame2.destroy() #self.cleanDir() self.createFirstWindow() self.p.step(99 // len(self.commandList)) self.printLogs(result + '\n') self.counter += 1 if self.counter >= len(self.commandList): self.generateFiles() self.lock.release() def fetchCommands(self): #fetch commands from commands.json #multithreading synchronization lock self.lock = threading.Lock() #reading json cmdFile = open(f"{content.absolutePath}commands.json", "r") commandJsonObject = json.load(cmdFile) self.commandList = commandJsonObject["linux"]['commands'] self.counter = 0 for cmd in self.commandList: t1 = threading.Thread(target=self.runCommands, args=(cmd, self.commandList[cmd])) t1.daemon = True t1.start() #Here intentionally not joining the processes after t1.start() def messageWidget(self, message, mtype): #message widget if mtype == 'info': messagebox.showinfo("Information", message) elif mtype == "error": messagebox.showerror("Opps An Error Occured", message) elif mtype == "warning": messagebox.showwarning("Warning", message) def generateFiles(self): #generating static files dirPath, name, version, description = self.dirPath, self.name, self.version, self.description projectDir = self.path #======================= generating files with content======================================== filedict = { '.gitignore': content.git, '.prettierrc.json': content.pretty, '.eslintrc.json': content.eslint, 'src/index.html': content.indexHtml, 'src/App.js': content.appJs, 'src/style.css': content.styleCss } os.mkdir(os.path.join(projectDir, 'src')) #os.system(f"mkdir {projectDir}/src") for fil in filedict: with open(f"{projectDir}/{fil}", '+w') as rw: rw.write(filedict[fil]) #==================== updating package file ========= #=== package.json jsonFile = open(f"{projectDir}/package.json", "r") json_object = json.load(jsonFile) jsonFile.close() jsonFile = open(f"{projectDir}/package.json", "w") json_object['name'] = name json_object['version'] = version json_object['description'] = description json_object['scripts'][ 'format'] = "prettier \"src/**/*.{js,html}\" --write" json_object['scripts']['lint'] = "eslint \"src/**/*.{js,jsx}\" --quiet" json_object['scripts']['dev'] = "parcel src/index.html" json.dump(json_object, jsonFile, indent=2) jsonFile.close() #===== package-lock.json jsonFile = open(f"{projectDir}/package-lock.json", "r") json_object = json.load(jsonFile) jsonFile.close() jsonFile = open(f"{projectDir}/package-lock.json", "w") json_object['name'] = name json_object['version'] = version json.dump(json_object, jsonFile, indent=2) jsonFile.close() self.statusLabel['text'] = "installation finished!" self.printLogs("\nHappy Coding \n") self.taskDone = True self.contentFrame2.after(4000, self.createThirdWindow) # ===================================== ++++++++++++++++++++++++++ =================================== # # ============================================ Third window ======================================== # # ===================================== ++++++++++++++++++++++++++ =================================== # def createThirdWindow(self): #initialization self.contentFrame2.destroy() self.contentFrame3 = Frame(self.window, background="#262625", highlightbackground="#42B3D2", highlightthickness=1, relief=tk.RAISED, borderwidth=0) self.contentFrame3.grid(row=1, column=0, sticky="NS", pady=10, padx=0) self.showInfo() def showInfo(self): # ================================= creation and placements of decorative images ========================== # self.tickImage = Canvas(self.contentFrame3, width=40, height=40, background="#262625", bd=0, highlightthickness=0) self.tickImage.grid(row=0, column=0, sticky=tk.W, padx=14) self.img3 = ImageTk.PhotoImage( Image.open(f"{content.absolutePath}images/tick.png")) self.tickImage.create_image(20, 20, image=self.img3) Label(self.contentFrame3, text="React Project has been created successfully", background="#262625", foreground="#c7c9c7", font=("", 12)).grid(row=0, column=0, sticky=tk.W + tk.N, padx=50, pady=13) Label(self.contentFrame3, text=f"Project Directory : {self.path}", background="#262625", foreground="#c7c9c7", font=("", 10)).grid(row=1, column=0, sticky=tk.W + tk.N, padx=20, pady=7) Label(self.contentFrame3, text="npm run format", background="#1a1919", foreground="#68D9B5", width=72, font=("Times New Roman", 12)).grid(row=2, column=0, sticky=tk.W, padx=20, pady=7) Label( self.contentFrame3, text= "> Run this command to format whole project's source code. You can always change this format settings in '.prettierrc.json' file ", background="#262625", foreground="#c7c9c7", font=("", 10), wraplength=616, justify="left").grid( row=3, column=0, sticky=tk.W + tk.N, padx=20, ) Label(self.contentFrame3, text="npm run lint -- --fix", background="#1a1919", foreground="#68D9B5", width=72, font=("Times New Roman", 12)).grid(row=4, column=0, sticky=tk.W, padx=20, pady=7) Label( self.contentFrame3, text= "> Run this command to fix all auto-fixable errors. You can always change lint settings in '.eslintrc.json' file", background="#262625", foreground="#c7c9c7", font=("", 10), wraplength=616, justify="left").grid( row=5, column=0, sticky=tk.W + tk.N, padx=20, ) Label(self.contentFrame3, text="npm run dev", background="#1a1919", foreground="#68D9B5", width=72, font=("Times New Roman", 12)).grid(row=6, column=0, sticky=tk.W, padx=20, pady=7) Label( self.contentFrame3, text= "> Run this command to start development server with babel. Parcel web bundler is pre-configured.", background="#262625", foreground="#c7c9c7", font=("", 10), wraplength=616, justify="left").grid( row=7, column=0, sticky=tk.W + tk.N, padx=20, ) #cancle button to terminate process self.QuitBtn = tk.Button(self.contentFrame3, borderwidth=0, text="Finish", highlightthickness=0, background="#bf1d1d", activebackground="#2b2b2a", cursor="hand1", font=("", 12), foreground="white", command=lambda: self.window.destroy()).grid( row=10, column=0, sticky=tk.W, pady=10, padx=280) def close(self): #warning if messagebox.askyesno("Are you sure?", "Do you really want to exit this application?"): if not self.taskDone: self.cleanDir() self.window.destroy() def cleanDir( self): #cleaning project directory if installation is unsuccessful try: os.system(f"rm -r {self.dirPath}/{self.name}") except: pass
class Worker(Frame): """ Worker gui elements, does all the actual work to the images with the watermarker class and contains progressbar and startbutton """ def __init__(self, file_selector, options_pane, master=None): super().__init__(master) self.running = False self.image_que = queue.Queue() self.file_selector = file_selector self.option_pane = options_pane self.watermarker = WaterMarker self.progress_var = IntVar() self.file_count = IntVar() self.counter_frame = Frame(self) self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", length=600) self.time_tracker = RemainingTime(self.counter_frame) self.button_frame = Frame(self) self.start_button = Button(self.button_frame, text="Start", command=self.apply_watermarks, width=10) self.stop_button = Button(self.button_frame, text="Stop", command=self.stop_work, width=10) self.create_widgets() def create_widgets(self): """Create GUI""" self.counter_frame.pack() self.time_tracker.pack(side=LEFT, padx=(0, 10)) Label(self.counter_frame, textvariable=self.progress_var).pack(side=LEFT) Label(self.counter_frame, text="/").pack(side=LEFT) Label(self.counter_frame, textvariable=self.file_count).pack(side=LEFT) self.progress_bar.pack() self.stop_button.config(state=DISABLED) self.start_button.pack(side=LEFT, padx=15) self.stop_button.pack(side=LEFT) self.button_frame.pack(pady=10) def fill_que(self): """ Fill the worker que from the files in file selector, and prepare te progress bar """ files = self.file_selector.get_file_paths() self.file_count.set(len(files)) self.progress_bar.configure(maximum=len(files)) self.time_tracker.set_max(len(files)) for file in files: self.image_que.put(file) def is_existing_files(self): """ Check if there's existing files which will be overwritten by the watermarker :return: True/False """ out = self.option_pane.get_output_path() for _file in self.file_selector.get_file_paths(): if os.path.isfile(self.option_pane.create_output_path(_file, out)): return True return False def apply_watermarks(self): """ Fill the que, then prepare the watermarker before spawning workers """ if len(self.file_selector.files) < 1: messagebox.showerror('Nothing to mark', 'Please choose one or more files ' 'to mark.') return if self.is_existing_files(): kwargs = {"title": "Overwrite files?", "message": "Files already exists, want to overwrite?"} overwrite = messagebox.askyesno(**kwargs) else: # Shouldn't matter since there's no files. overwrite = False try: self.watermarker = WaterMarker(self.option_pane.get_watermark_path(), overwrite=overwrite) except Exception as e: self.handle_error(e) return self.stop_button.config(state=NORMAL) self.start_button.config(state=DISABLED) self.fill_que() self.start_work() def start_work(self): """ The baby factory, spawns worker thread to apply the watermark to the images. Also locks the buttons and output selector """ try: kwargs = {"pos": self.option_pane.get_watermark_pos(), "padding": self.option_pane.get_padding(), "scale": self.option_pane.should_scale(), "opacity": self.option_pane.get_opacity()} output = self.option_pane.get_output_path() print(output) except BadOptionError as e: self.handle_error(e) return self.running = True self.option_pane.output_selector.lock() thread = threading.Thread(target=self.work, kwargs=kwargs, args=(output, )) self.time_tracker.start() thread.start() def reset(self): """ Reset the worker, emptying queue, resetting vars and buttons and stuff. """ self.image_que = queue.Queue() self.watermarker = WaterMarker self.progress_var.set(0) self.progress_bar.stop() self.time_tracker.stop() self.file_count.set(0) self.start_button.config(state=NORMAL) self.stop_button.config(state=DISABLED) self.option_pane.output_selector.unlock() def handle_error(self, e): """ Handle an error, showing the callback to the user. Is meant to be primarily used with BadOption error with a custom text. :param e: Error object. """ self.reset() messagebox.showerror("Error", str(e)) def work(self, outpath, **kwargs): """ Work instructions for the child workers keep grabbing a new image path and then apply free_mark with the watermarker, using option pane to create paths. Controls progress bar and timer_tracker as well """ while self.running: try: input_path = self.image_que.get(block=False) except queue.Empty: self.start_button.config(state=NORMAL) self.stop_button.config(state=DISABLED) self.option_pane.output_selector.unlock() self.progress_var.set(0) self.file_count.set(0) self.running = False return try: self.watermarker.apply_watermark(input_path, self.option_pane.create_output_path(input_path, outpath), **kwargs) except BadOptionError as e: self.handle_error(e) print("Bad config, stopping\n", e) return except Exception as e: print("Error!\n", type(e), "\n", e) self.progress_bar.step(amount=1) self.time_tracker.step() self.progress_var.set(self.progress_var.get()+1) self.reset() def stop_work(self): self.running = False