class Loadbar: def __init__(self,size): self.loadbar = Tk() self.loadbar.wm_title('Loading') self.pgb = Progressbar(self.loadbar,orient='horizontal',length='500',maximum=int(size)) self.pgb.pack() self.pgb.start() def start(self): self.loadbar.mainloop() def kill(self): self.loadbar.destroy()
def _reset_controls(self): """ Resets the controls on the form. """ image = ImageTk.PhotoImage(file="bg.png") # Initialize controls self.lbl_bg = Label(self, image=image) self.lbl_dir = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.lbl_anon = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.lbl_id = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.btn_dir_select = Button(self, text="Select data folder", command=self._btn_dir_press) self.btn_id = Button(self, text="Identify data", command=self._btn_id_press) self.btn_anon = Button(self, text="Anonymize data", command=self._btn_anon_press) self.tb_study = Entry(self, bg="#668FA7", fg="white") self.prg_id = Progressbar(self, orient="horizontal", length=200, mode="determinate") self.prg_anon = Progressbar(self, orient="horizontal", length=200, mode="determinate") # Place controls self.lbl_bg.place(x=0, y=0, relwidth=1, relheight=1) self.lbl_anon.place(x=400, y=400) self.lbl_id.place(x=400, y=325) self.btn_dir_select.place(x=250, y=250) self.btn_id.place(x=250, y=325) self.btn_anon.place(x=250, y=400) self.tb_study.place(x=250, y=175) self.prg_id.place(x=410, y=290) self.prg_anon.place(x=410, y=370) # Other formatting self.lbl_bg.image = image self.btn_id['state'] = "disabled" self.btn_anon['state'] = "disabled" self.prg_id['maximum'] = 100 self.prg_anon['maximum'] = 100
class CalculationFrame(LabelFrame): def __init__(self,parent): LabelFrame.__init__(self,parent,text="Calculate",borderwidth=5) self.startCalculationB = Button(self,text="Start calculation",width=20) self.startCalculationB.grid(row=0,column=0,padx=10,pady=5) self.endCalculationB = Button(self,text="Cancel calculation",width=20) self.endCalculationB.grid(row=1,column=0,padx=10,pady=5) self.calculationPB = Progressbar(self, mode="indeterminate",length=128) self.calculationPB.grid(row=2,column=0,padx=10,pady=5)
def __init__(self, *args, **kwargs): self._app = kwargs.pop('wavesyn_root') self.__topwin = kwargs.pop('topwin') super().__init__(*args, **kwargs) parameter_frame = Frame(self) parameter_frame.pack(side='left', expand='yes', fill='y') self.__num = LabeledEntry(parameter_frame) set_attributes(self.__num, label_text = 'num', entry_text = '1', label_width = 5, entry_width = 8, checker_function = self._app.gui.value_checker.check_int ) self.__num.entry.bind('<Return>', lambda event: self._on_solve_click()) self.__num.pack(side='top') self.__pci = LabeledEntry(parameter_frame) set_attributes(self.__pci, label_text = 'PCI', entry_text = '100', label_width = 5, entry_width = 8, checker_function = self._app.gui.value_checker.check_int ) self.__pci.pack(side='top') self.__parallel_checker_variable = IntVar() self.__parallel_checker = Checkbutton(parameter_frame, text="Parallel", variable=self.__parallel_checker_variable, command=self._on_parallel_checker_click) self.__parallel_checker.pack() progfrm = Frame(self) progfrm.pack(side='left', expand='yes', fill='y') self.__genbtn = Button(progfrm, text='Generate', command=self._on_solve_click) self.__genbtn.pack(side='top') Button(progfrm, text='Stop', command=self._on_stop_button_click).pack(side='top') self.__progressbar_variable = IntVar() self.__finishedwav = IntVar() self.__progressbar = Progressbar(progfrm, orient='horizontal', variable=self.__progressbar_variable, maximum=100) self.__progressbar.pack(side='left') self.__progressbar.config(length=55) self.__finishedwavbar = Progressbar(progfrm, orient='horizontal', variable=self.__finishedwav) self.__finishedwavbar.pack(side='left') self.__finishedwavbar.config(length=30) self.name = 'Generate' self.getparams = None self.__stopflag = False
def popupWindow(self): self.popup = Toplevel(self.root) self.popup.title("Progress window") self.popup.geometry("200x50") self.popup.focus() self.counter = IntVar() self.counter.set(0) #label = Label(self.popup, textvariable = self.strVar) #label.pack(expand=True) pb = Progressbar(self.popup, mode="determinate", orient="horizontal", variable=self.counter, maximum=1000000) pb.start() pb.pack(expand=True) self.root.after(100, self.read_queue)
def average_normals( self ): """ Applies Gouraud normalization to the module """ # Set up updater top = Toplevel() pb = Progressbar(top,orient ="horizontal",length = 200, mode ="determinate") pb['maximum'] = len(self.__elements__) pb['value'] = 10 pb.grid(row=0,column=0) tx = Label(top) tx.grid(row=1,column=0) top.update_idletasks() top.lift() t0 = time.time() # run the loop, if we're visible and phong shading if not self.invisible == 'gouroud': try: buf = np.array([0,0,0,1]) for i,polygon in enumerate(self.__elements__): if not ispoly(polygon): continue polygon._onorms = np.array([polygon.normals.astype(float)+buf for i in range(len(polygon.coordinates))]) # Update the user as to what's going on if i % 50 == 0 and i > 0: pb['value'] = i tmp = i/len(self.__elements__) estimation = int(tmp*(time.time()-t0) * (1-tmp)/tmp) tx.configure(text=str(int(100*i/len(self.__elements__)))+"%"+' Estimated time: '+str(estimation)+'s' ) top.update_idletasks() for c,coordinate in enumerate(polygon.coordinates): for j,opolygon in enumerate(self.__elements__): if i == j or not ispoly(opolygon): continue for k,ocoordinate in enumerate(opolygon.coordinates): if all(coordinate == ocoordinate): # same vertex, finally polygon._onorms[c] += (opolygon.normals+buf) polygon._onorms /= polygon._onorms[:,3,None] for polygon in self.__elements__: if ispoly(polygon): polygon.normals = polygon._onorms del polygon._onorms except IndexError as ie: pass top.destroy() if self.invisible == 'gouroud': self.invisible = False return self # for chaining
class ProgressCheckButton(Frame, Observable): def __init__(self, parent, model, index, status_model): Frame.__init__(self, parent) Observable.__init__(self) self.model = model self.index = index self.status_model = status_model self.var = IntVar() self.var.set(model.get_checked()) self.progress_var = IntVar() self.progress_status = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self.model.add_listener(self._model_changed) def _model_changed(self, new_status): model_state = self.model.get_checked() gui_state = self.var.get() if model_state is not gui_state: self.model.set_checked(gui_state) def refresh_check(self): if self.status_model.is_checked_force_reload(): self.check_button.select() else: self.check_button.deselect() def is_checked(self): return self.var.get() def _progress_status_changed(self, new_status): self._refresh_progress() def _refresh_progress(self): status = self.status_model.get_status() if not status == self.progress_status: if status == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _check_changed(self): new_checked = self.var.get() if new_checked is not self.model.get_checked(): self.model.set_checked(new_checked) if new_checked is not self.status_model.is_checked(): self._notify(self.index, new_checked)
class ProgressListBoxItem(Frame, Observable): def __init__(self, parent, model): Frame.__init__(self, parent) Observable.__init__(self) self._model = model # Create variables and initialise to zero self._checked_var = IntVar() self._progress_var = IntVar() self._checked_var.set(0) self._progress_var.set(0) self._current_gui_checked_state = CheckStatus.undefined self._current_gui_progress_state = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self._update() self._model.add_listener(self._model_changed) def _model_changed(self): self.update() def _update(self): # Update check status model_check_state = self._model.get_check_status() if model_check_state is not self._current_gui_checked_state: self._current_gui_checked_state = model_check_state # if self.status_model.is_checked_force_reload(): if model_check_state: self.check_button.select() else: self.check_button.deselect() # Update progress status model_progress_state = self._model.get_progress_status if not model_progress_state == self._current_gui_progress_state: self._current_gui_progress_state = model_progress_state if model_progress_state == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _user_check_changed(self): new_checked = self._checked_var.get() if new_checked is not self._model.get_check_status(): self._model.manual_set_checked(new_checked)
def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N)
def create_widgets(self): ''' Creates appropriate widgets on this frame. ''' self.columnconfigure(0, weight=1) self.rowconfigure(3, weight=1) frame_for_save_btn = Frame(self) frame_for_save_btn.columnconfigure(1, weight=1) self.status_lbl = Label(frame_for_save_btn, text='') self.status_lbl.grid(row=0, column=1, sticky=N+W) save_solution_btn = Button(frame_for_save_btn, text='Save solution', command=self.on_save_solution) save_solution_btn.grid(row=1, column=0, sticky=W+N, padx=5, pady=5) self.progress_bar = Progressbar(frame_for_save_btn, mode='determinate', maximum=100) self.progress_bar.grid(row=1, column=1, sticky=W+E, padx=10, pady=5) frame_for_save_btn.grid(sticky=W+N+E+S, padx=5, pady=5) frame_for_btns = Frame(self) self._create_file_format_btn('*.xlsx', 1, frame_for_btns, 0) self._create_file_format_btn('*.xls', 2, frame_for_btns, 1) self._create_file_format_btn('*.csv', 3, frame_for_btns, 2) self.solution_format_var.set(1) frame_for_btns.grid(row=1, column=0, sticky=W+N+E+S, padx=5, pady=5) self.data_from_file_lbl = Label(self, text=TEXT_FOR_FILE_LBL, anchor=W, justify=LEFT, wraplength=MAX_FILE_PARAMS_LBL_LENGTH) self.data_from_file_lbl.grid(row=2, column=0, padx=5, pady=5, sticky=W+N) self.solution_tab = SolutionFrameWithText(self) self.solution_tab.grid(row=3, column=0, sticky=W+E+S+N, padx=5, pady=5)
def __init__(self, master=None): # Avoiding to send it continuously. self.lock = False Frame.__init__(self, master) self.grid() self.master = master # Setting for ComboBox. self.url_lang_combobox_str = StringVar() self.url_lang_combobox_list = lang_list # UI components. self.receiver_email_text = Label(self, text="Receiver:") self.receiver_email_field = Entry(self, width=50) self.subject_text = Label(self, text='Subject:') self.subject_field = Entry(self, width=50) self.receiver_name_text = Label(self, text='Name:') self.receiver_name_field = Entry(self, width=50) self.url_lang_text = Label(self, text='Link lang:') self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly') self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300) self.send_button = Button(self, text='Send', command=self._send_mail) self.quit_button = Button(self, text='Exit', command=self.__exit) self.log_msg_text = ScrolledText(self) # Attachment. self.mail_attachment_list = attachment_list[:] self.url_lang_link_title = None self.url_lang_link = copy.deepcopy(content_link) # Mailer self._mailer = None # Let Mailer can control components. Mailer.window_content = self self.__create_widgets()
def _make_cpu_mem_status(self): balloon = Scripting.root_node.gui.balloon def on_progbar_dbclick(app): with code_printer(): Scripting.root_node.gadgets.launch(app) mem_progbar = Progressbar(self, orient="horizontal", length=60, maximum=100, variable=self.__membar) mem_progbar.pack(side='right', fill='y') mem_progbar.bind('<Double-Button-1>', lambda dumb: on_progbar_dbclick('wsmemmeter.pyw')) membar_tip = balloon.bind_widget(mem_progbar, balloonmsg='Total memory usage:') membar_tip.show_callback = lambda: f' {Scripting.root_node.interfaces.os.get_memory_usage()}%.' cpu_progbar = Progressbar(self, orient="horizontal", length=60, maximum=100, variable=self.__cpubar) cpu_progbar.pack(side='right', fill='y') cpu_progbar.bind('<Double-Button-1>', lambda dumb: on_progbar_dbclick('wscpumeter.pyw')) cpubar_tip = balloon.bind_widget(cpu_progbar, balloonmsg='Total CPU usage: ') cpubar_tip.show_callback = lambda: f' {Scripting.root_node.interfaces.os.get_cpu_usage()}%.'
def convert(self): """ Runs the parallel_text converter in a thread with the current input. """ if not self.valid_input(): return popup = Toplevel(self) # Disable closing of the popup window popup.protocol('WM_DELETE_WINDOW', lambda : None) progress = IntVar() Label(popup, text='Converting Epub. This cannot be interrupted. Please wait...').grid(row=0, column=0) progressbar = Progressbar(popup, orient=HORIZONTAL, length=200, mode='determinate', variable=progress) progressbar.grid(row=1, column=0) # Run converter in thread converter = Converter(self.languages[self.input_language.get()], self.languages[self.output_language.get()]) self._error = False def target(): try: converter.convert_epub(self.input_file.get(), self.output_file.get()) except Exception as e: self._error = True self._message = str(e) thread = Thread(target=target) thread.start() # Keep updating progress bar def update_progressbar(): progress.set(converter.percent_complete) if thread.is_alive(): popup.after(500, update_progressbar) else: progressbar.stop() popup.destroy() if self._error: showinfo(title="Conversion failed", message=self._message) else: showinfo(title="Conversion complete", message="Conversion complete.") popup.after(500, update_progressbar) # Disable the main window popup.transient(self) popup.grab_set() self.wait_window(popup)
def __init__(self, parent, model, index, status_model): Frame.__init__(self, parent) Observable.__init__(self) self.model = model self.index = index self.status_model = status_model self.var = IntVar() self.var.set(model.get_checked()) self.progress_var = IntVar() self.progress_status = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self.model.add_listener(self._model_changed)
def __init__(self, parent, model): Frame.__init__(self, parent) Observable.__init__(self) self._model = model # Create variables and initialise to zero self._checked_var = IntVar() self._progress_var = IntVar() self._checked_var.set(0) self._progress_var.set(0) self._current_gui_checked_state = CheckStatus.undefined self._current_gui_progress_state = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self._update() self._model.add_listener(self._model_changed)
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 __init__(self): Tk.__init__(self) self.title("uT to qBt convertor") #main frame self.main_frame = Frame(self, padding="3 3 12 12") self.main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) self.main_frame.columnconfigure(0, weight=1) self.main_frame.rowconfigure(0, weight=1) #uT part self.ut_data = StringVar() self.ut_label = Label(self.main_frame, text="uT data") self.ut_label.grid(column=0, row=1, sticky=(W)) self.ut_entry = Entry(self.main_frame, width=100, textvariable=self.ut_data) self.ut_entry.grid(column=1, row=1, sticky=(W)) self.ut_button = Button(self.main_frame, text="Browse", command=self.load_file) self.ut_button.grid(column=2, row=1) #qBt part self.qbt_folder = StringVar() self.qbt_label = Label(self.main_frame, text="qBt folder") self.qbt_label.grid(column=0, row=4, sticky=(W)) self.qbt_entry = Entry(self.main_frame, width=100, textvariable=self.qbt_folder) self.qbt_entry.grid(column=1, row=4, sticky=(W)) self.qbt_button = Button(self.main_frame, text="Browse", command=self.open_dir) self.qbt_button.grid(column=2, row=4, sticky=(W, E)) #convertor self.convertor_button = Button(self.main_frame, text="Convert", command=self.convert, width=50) self.convertor_button.grid(column=1, columnspan=2, row=5) self.progress_bar = Progressbar(self.main_frame, orient=HORIZONTAL, length=300, mode="indeterminate") self.progress_bar.grid(column=1, columnspan=3, row=6) #set padding for each element for child in self.main_frame.winfo_children(): child.grid_configure(padx=5, pady=5)
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.frameCanvas = Label(self, width=Settings.outputWidth, height=Settings.outputHeight) self.frameCanvas.grid(row=0, column=0, columnspan=5, pady=10) self.frameCanvas.bind("<Button-1>", self.markPosition) self.labelCanvas = Label(self, width=Settings.labelWidth, height=Settings.labelHeight) self.labelCanvas.grid(row=0, column=5, pady=10) self.labelCanvas.bind("<Button-1>", self.unmarkPosition) self.prevButton = Button(self, text="<<", command=self.showPrev) self.prevButton.grid(row=1, column=0, sticky="nesw") self.saveButton = Button(self, text="Save", command=self.save) self.saveButton.grid(row=1, column=2, sticky="nesw") self.nextButton = Button(self, text=">>", command=self.showNext) self.nextButton.grid(row=1, column=4, sticky="nesw") self.progressBar = Progressbar(self, orient=HORIZONTAL) self.progressBar.grid(row=2, column=0, columnspan=5, sticky="nesw", pady=10) self.stateLabel = Label(self, text="Loading...") self.stateLabel.grid(row=3, column=0, pady=10) self.frames = [] self.labels = [] self.currentFrame = 0 self.loadVideo() self.showCurrentFrame() self.clickedPos = (0,0) self.drawState = WorkingWindow.STATE_NONE
def __init__(self, master, u, p): self.master = master self.u = u self.p = p self.master.title("Auto-joiner") self.master.config(bg='LightSkyBlue4') self.master.geometry("880x619+200+120") self.frame = Frame(self.master) self.frame.pack() self.frame.config(bg='LightSkyBlue4') self.trb = Label(self.frame, text='\n', font=('arial', 20, 'bold'), bg='LightSkyBlue4', fg='gray20') self.trb.grid(row=0, column=0) self.Logfr1 = LabelFrame(self.frame, width=750, height=200, font=('arial', 20, 'bold'), relief='ridge', bg='cyan4', bd=10) self.Logfr1.grid(row=1, column=0) # # self.Title = Label(self.Logfr1, text='Meet Auto-Joiner', font=('arial', 50, 'bold'), bg='cyan4', fg='gray20') self.Title.grid(row=0, column=0, columnspan=2, ipadx=50) self.btn = Button(self.Logfr1, text='Start', font=('arial', 15, 'bold'), width=16, command=self.start) self.btn.grid(row=1, column=0, ipadx=30) self.progress = Progressbar(self.Logfr1, orient=HORIZONTAL, length=260, mode='indeterminate') self.progress.grid(row=2, column=0, ipady=11) #btns and entries global delete_box delete_box = Entry(self.Logfr1, width=20, font=('arial', 15, 'bold'), bg='aquamarine3', justify='center') delete_box.grid(row=5, column=0, columnspan=3) delete_box_label = Label( self.Logfr1, text= "Input your ID in the box below in order to Delete/Edit a meeting\nYou can find the ID in the timetable for the desired day ", font=('arial', 15, 'bold'), bd=22, bg='cyan4', fg='black') delete_box_label.grid(row=4, column=0, columnspan=3) self.submit_btn = Button(self.Logfr1, text="Schedule a meeting", font=('arial', 15, 'bold'), width=16, command=self.submit) self.submit_btn.grid(row=1, column=1, columnspan=2, pady=10, padx=30, ipadx=34) self.query_btn = Button(self.Logfr1, text="Timetable", font=('arial', 15, 'bold'), width=11, command=self.query) self.query_btn.grid(row=3, column=1, columnspan=2, pady=0, ipadx=15) self.clicked_query = StringVar() self.currentDay = datetime.today().strftime("%A") self.clicked_query.set(self.currentDay) self.select_query = OptionMenu(self.Logfr1, self.clicked_query, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") self.select_query.grid(row=2, column=1, columnspan=2, pady=10, ipadx=8, ipady=2) self.select_query.config(font=('arial', 15, 'bold'), width=10) self.select_query['menu'].config(font=('arial', 15, 'bold')) self.delete_btn = Button(self.Logfr1, text="Delete a meeting", font=('arial', 15, 'bold'), width=16, command=self.delete) self.delete_btn.grid(row=6, column=1, columnspan=2, ipadx=43) self.edit_btn = Button(self.Logfr1, text="Edit a meeting", font=('arial', 15, 'bold'), width=16, command=self.edit) self.edit_btn.grid(row=6, column=0, columnspan=1, pady=10, padx=18, ipadx=35) self.exit_btn = Button(self.Logfr1, text="Stop", font=('arial', 15, 'bold'), width=16, command=self.exit) self.exit_btn.grid(row=3, column=0, pady=10, padx=10, ipadx=30) self.t = 0
class CompleteDecodePage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) # parent class is "wireframe class" title = tk.Label(self, text="Decoding Stage", font=TITLE_FONT) title.pack(side=TOP, pady=10, padx=10) ''' Function Percentage Case 1: What is x % of y? Case 2: x is what % of y? Case 3: What is the percentage increase/decrease from x to y ''' def percentage_calculator(x,y,case=1): if (case == 1): r = x/100*y return r elif (case == 2): r = x/y*100 return r elif (case == 3): r = (y-x)/x*100 return r else: raise Exception("Only case 1, 2, or 3 are available!") def progress_bar_process(progress, runButton): def reset(): global pickedAudio, direL, priv_keyL, public_keyL, passwordU, audioFile, audioF, directory, private_key, public_key #Reset form by clearing all labels and global variables pickedAudio.configure(text="") direL.configure(text="") priv_keyL.configure(text="") public_keyL.configure(text="") passwordU.delete(0, 'end') audioF = "" audioFile = "" pk = "" puk = "" private_key = "" public_key = "" directory = "" menuBtn.pack_forget() runButton.config(state="active") controller.show_frame(MainPage) def wrong_password(): global pickedAudio, direL, priv_keyL, public_keyL, passwordU, audioFile, audioF, directory, private_key, public_key #Reset form by clearing all labels and global variables pickedAudio.configure(text="") direL.configure(text="") priv_keyL.configure(text="") public_keyL.configure(text="") passwordU.delete(0, 'end') audioF = "" audioFile = "" pk = "" puk = "" private_key = "" public_key = "" directory = "" runButton.config(state="active") controller.show_frame(MainPage) runButton.config(state="disabled") # create the countdown measurements of 10 seconds alist = range(20) # Run Stego Algorithm Script #run_algorithm() try: # This section involves using my hybrid crypto-system # Private and Public keys are now generated # private_key, public_key = create_keys() # Get config variables from config file and load them into specific var audio_file, directory, private_key, public_key, pwd = getConfigFile() # Hash the password to meet AES-128 bit criteria password = hashlib.sha256(pwd.encode('utf-8')).digest() unlocked_file = decode(audio_file,directory) # We first need to extract the files from the all file sent by the sender print (unlocked_file) #extraction(unlock_file) NO LONGER A VALID FUNCTION --> # Now that all files are extracted, we want to decrypt the file #decrypt(private_key, public_key, password, unlocked_file, directory) status, sig_verification = verification(private_key, public_key, password, unlocked_file, directory) print (sig_verification) if (status == False): messagebox.showinfo('Password Error', "The password you provided was incorrect. Directing you back to main menu now!") wrong_password() p = 0 for i in alist: p += 1 # Case2: x is what percent of y? unit = percentage_calculator(p, len(alist), case=2) time.sleep(1) progress['value'] = unit percent['text'] = "{}%".format(int(unit)) container.update() if (sig_verification == False): messagebox.showinfo('Signature Authentication',"This sender failed authentication and cannot be trusted!") elif (sig_verification == True): messagebox.showinfo('Signature Authentication',"This sender is authenticated via their signature!") messagebox.showinfo('Info', "Retrieval Process Complete! Hidden data is in the same directory as the original audio output directory") # create back to Main Menu Button global menuBtn menuBtn = tk.Button(self, text="Main Menu", height="1", width="12", command=reset) menuBtn.pack(side=BOTTOM, pady = 15) except Exception as e: messagebox.showinfo('Info', "ERROR: {}".format(e)) sys.exit() percent = tk.Label(self,text="", anchor=S) percent.pack() progress = Progressbar(self,length=400, mode='determinate') progress.pack() runButton = tk.Button(self, text='Begin Decoding', command=(lambda: progress_bar_process(progress, runButton))) runButton.pack(pady=15) status = tk.Label(self,text="Please wait until the process is complete to retrieve the hidden data file", relief=SUNKEN, anchor=W, bd=2) status.pack(side=BOTTOM, fill=X)
def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button
class ProgressWindow(): """ This is a GUI window used to actually run the training and creation of demonstrations. """ def __init__(self, master): """ The constructor method that initialises all of the widgets to display the progress. Parameters ---------- master : TK The window that contains this GUI. """ self.master = master master.title("Creating demonstrations") self.desc = Label(master, text='Creating Demos......', highlightthickness=10) self.desc.pack() self.progress = Progressbar(master, orient = HORIZONTAL, length = 200, mode='determinate') self.progress.pack() def run(self, envName, stepsPerDemo, numDemos, saveDir, logDir=""): """ Creates a set of demonstrations in a given directory. Parameters ---------- envName : str The case sensitive id of the environment such as BreakoutNoFrameskip-v4. stepsPerDemo : int The number of training steps between each demonstration that is created. numDemos : int The number of demonstrations to be created. saveDir : str The full path to the directory to save the demonstrations. logDir : str The full path to the directory to save the training logs. Returns ------- """ progress_per_demo = 100 / numDemos total_progress = 0 algorithm = "ppo2" splitname = envName.split("-") fullEnvName = splitname[0] + "NoFrameskip-" + splitname[1] stepSize = stepsPerDemo # first generate the initial step if logDir != "": p = subprocess.Popen( "python -m baselines.run --alg={} --env={} --num_timesteps={} --save_path={}/{} --log_path={}/{}" .format(algorithm, fullEnvName, stepSize, saveDir, stepSize, logDir, stepSize), shell=True) p.wait() else: p = subprocess.Popen( "python -m baselines.run --alg={} --env={} --num_timesteps={} --save_path={}/{}" .format(algorithm, fullEnvName, stepSize, saveDir, stepSize), shell=True) p.wait() lastTrained = stepSize # with tf.Graph().as_default(): agent = makeDemoFromAgent(saveDir + "/" + str(lastTrained), fullEnvName) for checkpoint in range(1, numDemos): total_progress += progress_per_demo self.progress['value'] = total_progress nextTrained = lastTrained + stepSize if logDir != "": p = subprocess.Popen( "python -m baselines.run --alg={} --env={} --num_timesteps={} --save_path={}/{} --load_path={}/{} --log_path={}/{}" .format(algorithm, fullEnvName, stepSize, saveDir, nextTrained, saveDir, lastTrained, logDir, nextTrained), shell=True) p.wait() else: p = subprocess.Popen( "python -m baselines.run --alg={} --env={} --num_timesteps={} --save_path={}/{} --load_path={}/{}" .format(algorithm, fullEnvName, stepSize, saveDir, nextTrained, saveDir, lastTrained), shell=True) p.wait() self.desc.config(text="trained checkpoint {} to {}".format(lastTrained, nextTrained)) # with tf.Graph().as_default(): makeDemoFromAgent(saveDir + "/" + str(nextTrained), fullEnvName, agent=agent) lastTrained = nextTrained self.desc.config(text="finished training") self.master.destroy()
class Reg(Frame,deal_word,write_excel): def __init__(self, master): self.success=0 self.failue=0 self.frame = Frame(master) self.frame.pack() self.lab1 = Label(self.frame, text="路径:") self.lab1.grid(row=0, column=0, sticky=E) self.ent1 = Entry(self.frame) self.ent1.grid(row=0, column=1, sticky=W) self.lab2 = Label(self.frame, text="待用:") self.lab2.grid(row=1, column=0,sticky=E) self.ent2 = Entry(self.frame, show="*") self.failure=[] self.ent2.grid(row=1, column=1, sticky=W) self.button = Button(self.frame, text="开始", command=self.Submit) self.button.grid(row=1, column=2, sticky=W,ipadx=20) self.lab3 = Label(self.frame, text="") self.lab3.grid(row=3, column=1, sticky=W) self.lab3.grid(row=0,column=2,sticky=W) self.mpb = Progressbar(self.frame, orient="horizontal", length=200, value=0, mode="determinate") self.mpb.grid(row=2, column=0, columnspan=2) deal_word.__init__(self) write_excel.__init__(self) self.scrolW = 40 # 设置文本框的长度 self.scrolH = 18 # 设置文本框的高度 self.text = scrolledtext.ScrolledText(self.frame, width=self.scrolW, height=self.scrolH, wrap=WORD) self.text.grid(row=3,columnspan=3) def Submit(self): self.text.insert("end","") s1 = self.ent1.get() # or r"C:\Users\道路\Desktop\模板four\凤岗内业\非危房" s2 = self.ent2.get() if os.path.exists(s1): os.chdir(s1) self._s1=s1 self._excel_cell = xlrd.open_workbook(self._excel_path).sheet_by_name("数据源") # cl = deal_word(s1) # cl._main() start = time.time() self.mpb["maximum"] =self._excel_cell.nrows-1 # try: for i in range(2, self._excel_cell.nrows): try: self._serial=self._excel_cell.cell(i, 0).value self._word_all(i) self.mpb["value"] = i self.text.see(END) # 一直查看文本的最后位置~ # print(all_to_string(sht[i, 0].value)) self.text.insert("end", str(i)+":"+self._all_to_string(self._excel_cell.cell(i, 0).value)+'成功生成Word'+ "\n"+"需要补充:"+str(self._list_problem)+"\n"+"照片数量:"+str(self._pictrue_count)+"\n\n") root.update() self.success+=1 if self._list_problem: self._i = i self.execute_main() self._list_problem=[] self._pictrue_count=0 self._serial="" except Exception as e: self._serial=self._excel_cell.cell(i, 0).value # print(e) self.failure.append([self._all_to_string(self._excel_cell.cell(i, 0).value),"错误原因:"+str(e)]) self.failue+=1 self._list_problem=[] self._pictrue_count=0 self._serial="" pass self.text.insert('end',r"程序运行完成:总数"+str(self._excel_cell.nrows-2)+ "\n\n") self.text.insert("end","成功"+str(self.success)+ "\n\n") self.text.insert("end", "失败" + str(self.failue)+"\r\n"+"失败原因:"+str(self.failure) + "\n\n") self.text.update() end=time.time() self.text.see(END) # 一直查看文本的最后位置~ root.update() self.text.insert('end',"运行时间"+str(end - start)+"s"+ "\r\n") # 结束时间-开始时间 self.workbook.save(os.path.join(self._s1,"excel_test.xls")) else: self.lab3["text"] = "请输入路径!"
class job: def __init__(self, root): self.root = root self.depart() self.Liste_date = [] self.Liste_issues = [] self.Liste_review = [] self.Liste_comments = [] def depart(self): self.frame1 = Frame(self.root, width=600, bg='#FFFFFF') self.frame1.grid(row=0, column=0, ipady=10, ipadx=10) self.frame1.grid_columnconfigure(0, weight=2) self.vfichier1 = StringVar() self.vfichier2 = StringVar() self.vproject = StringVar() self.vfichier1.set('') self.vfichier2.set('') self.vproject.set('') self.chemin = '' self.chemin1 = '' self.button1 = Button(self.frame1, text="Import weekly reporting", command=self.set_fichier1, width=50, height=2, bg='#66B239') self.button1.grid(row=0, column=0, pady=5) self.button2 = Button(self.frame1, text='Import SSR dashboard', command=self.set_fichier2, width=50, height=2, bg='#66B239') self.button2.grid(row=2, column=0, pady=5) self.vname_g = StringVar() self.vfilter_name = StringVar() self.vremarque = StringVar() self.vremarque.set("") self.vfilter_name.set('') self.bpetit_tab = Button(self.frame1, text='Import part list', command=self.set_filter, width=50, height=2, bg='#66B239') self.bpetit_tab.grid(row=4, column=0, pady=5) self.bProject = Button(self.frame1, text='Import Hard points list', command=self.set_project, width=50, height=2, bg='#66B239') self.bProject.grid(row=3, column=0, pady=5) self.bpetit_emp = Button(self.frame1, text="Generate report", command=self.set_emplacement, width=50, height=2, bg='#66B239') self.bpetit_emp.grid(row=5, column=0, pady=5) self.lremarque = Label(self.frame1, textvariable=self.vremarque, relief=GROOVE, bg='#CAE21E', font=('arial', 10), border='2px', wraplength=550) self.progress_bar = Progressbar(self.frame1, orient='horizontal', length=286, mode='determinate') def part1(self, fichier1, fichier2, rapport_name, vproject, vfilter): self.progress_bar["maximum"] = 100 self.bpetit_emp['bg'] = '#006738' self.progress_bar.grid(row=6, column=0, pady=2) self.progress_bar["value"] = 5 root.update() # !/usr/bin/env python # coding: utf-8 path = fichier1 classeur = xlrd.open_workbook(path) self.progress_bar["value"] = 20 root.update() nom_des_feuilles = classeur.sheet_names() #feuille = classeur.sheet_by_name(nom_des_feuilles[2]) feuille = classeur.sheet_by_name("ECU Dashboard") ############################################################################################# ############################################################################################# def data_frame12(colonne1, colonne2, colonne3, colonne4, colonne5, colonne6): data = pd.DataFrame({ "Part": (colonne1), "SSR Decision Trend": (colonne2), "Update_date": (colonne3), "Issues/Concerns": (colonne4), "Review/SSR_Status": (colonne5), "Expected Action": (colonne6) }) return data dff = pd.read_excel(path, sheet_name="ECU Dashboard", skiprows=3) List_part = dff['ECU ID'] liste_SSR_Status = dff["SSR status"] Sentence = dff["Review Plans & Commitments / Action plan/ Remarks"] term = "NEWDATE" term1 = "Issues/Concerns:" term2 = "Review/SSR Status:" term3 = " " i = 0 for sentence in list(Sentence): i += 1 sentence = str(sentence).replace('\n', 'sautligne') sentence = sentence.replace('Review /SSR', 'Review/SSR') sentence = sentence.replace('Review / SSR ', 'Review/SSR') sentence = sentence.replace('Review/ SSR', 'Review/SSR') sentence = sentence.replace('Review/SSR status', 'Review/SSR Status') sentence = sentence.replace('Review/SSRstatus', 'Review/SSR Status') sentence = sentence.replace('Review/SSRStatus', 'Review/SSR Status') sentence = sentence.replace('Review/SSR Status :', 'Review/SSR Status:') sentence = sentence.replace('Issues/ Concerns', 'Issues/Concerns') sentence = sentence.replace('Issues /Concerns', 'Issues/Concerns') sentence = sentence.replace('Issues / Concerns', 'Issues/Concerns') sentence = sentence.replace('Issues/Concerns :', 'Issues/Concerns:') list2 = re.findall("\d\d-\d\d-\d{4}", sentence) for formatdate in list2: sentence = sentence.replace(formatdate + " :", formatdate + ":") try: premieredate = list2[0] list2 = [s for s in list2 if s != premieredate] for formatdate in list2: sentence = sentence.split(formatdate + ":")[0] sentence = sentence.split(formatdate + "sautligne")[0] except: 1 # on recupere le blocke le plus recent block = sentence.split("NEWDATE")[0] try: if term1 in block and term2 in block and re.search( 'Issues/Concerns:(.*)Review/SSR Status:', block).group(1) != '' and re.search( 'Review/SSR Status:(.*)', block).group(1): # on recupere la date (première occurence) self.Liste_date.append( re.findall("\d\d-\d\d-\d{4}", block)[0]) # on recupere les Issues/Concerns (première occurence) issue = block.split('Review/SSR Status:')[0] issue = re.findall('Issues/Concerns:(.*)', issue)[0] issue = issue.replace('sautlignesautligne', 'sautligne') # on rajoute les retours à la ligne try: # print(re.search('sautligne(.*)', review).group(1)) if issue[0:9] == 'sautligne': issue = issue[9::] except: issue = issue issue = issue.replace('sautligne', '\n') self.Liste_issues.append(issue) # on recupere les reviews (première occurence) review = re.search('Review/SSR Status:(.*)', block).group(1) self.List_date = re.findall("\d\d-\d\d-\d{4}", review) for k in self.List_date: review = review.split('sautligne' + k)[0] review = review.replace('sautlignesautligne', 'sautligne') # on rajoute les retours à la ligne try: # print(re.search('sautligne(.*)', review).group(1)) if review[0:9] == 'sautligne': review = review[9::] except: review = review review = review.replace('sautligne', '\n') self.Liste_review.append(review) self.Liste_comments.append(term3) # liste_comments.append(" {}".format(feuille.cell_value(i,64))) else: self.Liste_review.append(review) self.Liste_comments.append(term3) self.Liste_issues.append(issue) self.Liste_date.append(".") except: self.Liste_date.append(".") self.Liste_review.append(".") self.Liste_comments.append(".") self.Liste_issues.append(".") print(len(List_part), ' ,', len(liste_SSR_Status), ' ,', len(self.Liste_date), ' ,', len(self.Liste_issues), ' ,', len(self.Liste_review, ), ' ,', len(self.Liste_comments)) ee = data_frame12(List_part, liste_SSR_Status, self.Liste_date, self.Liste_issues, self.Liste_review, self.Liste_comments) import numpy as np ea = ee.to_numpy() import matplotlib.pyplot as plt import numpy as np import datetime # premier tableau================================================= data = pd.read_excel(fichier2, "°Cover Page", skiprows=9, index_col=1) data = data.drop(['R_KPI_MILESTONE', 'Trend'], axis=1) e1 = data.iloc[0:4, 0:1] # deuxieme tableau=============================================== data1 = pd.read_excel(fichier2, "°Cover Page", skiprows=43, index_col=2) data1 = data1.reset_index(drop=True) data1 = data1.drop(['Unnamed: 0', 'Unnamed: 1'], axis=1) e2 = data1.iloc[0:4, 0:11] self.progress_bar["value"] = 30 root.update() time.sleep(0.5) # GRAPHE ========================================================== import matplotlib.pyplot as plt plt.rcParams.update({ "pgf.texsystem": "pdflatex", "pgf.preamble": [ r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}", r"\usepackage{cmbright}", ] }) CWmax = e2['Unnamed: 3'][0].isocalendar()[1] x = [] for i in range(CWmax, CWmax - 10, -1): x.append('CW' + str(i)) self.progress_bar["value"] = 40 root.update() y1 = e2.loc[1] y2 = e2.loc[2] y3 = e2.loc[3] plt.figure(figsize=(10, 5)) plt.grid(True) plt.plot(x, y1, label='Coverage', lw=3) plt.plot(x, y2, label='Completness', lw=3) plt.plot(x, y3, label='Consistency', lw=3) self.progress_bar["value"] = 50 time.sleep(1) root.update() plt.title('Milestone trend') plt.xlabel('Calendar Week') plt.ylabel('Kpi (%)') plt.legend() ax = plt.gca() ax.invert_xaxis() plt.savefig("fig.png") eb = e1.to_numpy() self.progress_bar["value"] = 60 time.sleep(0.5) from openpyxl.utils.dataframe import dataframe_to_rows from openpyxl.chart import BarChart, Series, Reference path = vproject # data = pd.read_excel(path, skiprows=3, sheet_name=4) data = pd.read_excel(path, "Hard points", skiprows=3) id_list = list(data['ID']) veh_Project_list = list(data['Veh Project']) parts_list = list(data['Parts']) status_list = list(data['Status']) # Create a workbook and add a worksheet. workbook = Workbook() worksheet = workbook.active worksheet.title = 'Report.xlsx' # Add a bold format to use to highlight cells. header_formatfont = Font(bold=True, ) header_formattxt = Alignment(wrap_text=True) ## pour le petit tableau worksheet['A1'].value = 'KPI' worksheet['B1'].value = 'Completness' worksheet['C1'].value = 'Consistency' worksheet['B2'].value = 'Target = 100%' worksheet['C2'].value = 'Target = 80%' liste = ['A1', 'A2', 'B2', 'B1', 'C1', 'C2'] for cell in liste: worksheet[cell].font = header_formatfont worksheet[cell].alignment = header_formattxt # data, workbook, and worksheet are the same as in the BarChart example tab = Table(displayName="Table1", ref="A1:C3") # I list out the 4 show-xyz options here for reference style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False) tab.tableStyleInfo = style worksheet.add_table(tab) worksheet.column_dimensions['A'].width = 20 worksheet.column_dimensions['B'].width = 20 worksheet.column_dimensions['C'].width = 20 worksheet.column_dimensions['D'].width = 70 worksheet.column_dimensions['E'].width = 70 worksheet.column_dimensions['F'].width = 40 worksheet.column_dimensions['G'].width = 40 self.progress_bar["value"] = 70 time.sleep(1) root.update() # pour le grand tableau worksheet['A25'].value = 'PART' worksheet['B25'].value = 'SSR Decision Trend' worksheet['C25'].value = 'Update_date' worksheet['D25'].value = 'Issues/Concerns' worksheet['E25'].value = 'Review/SSR_Status' worksheet['F25'].value = 'Hard points and Risks IDs' worksheet['G25'].value = 'Expected Action' liste = ['A25', 'B25', 'C25', 'D25', 'E25', 'F25', 'G25'] for cell in liste: worksheet[cell].font = header_formatfont worksheet[cell].alignment = header_formattxt # Petit tableau roww = 3 coll = 0 worksheet.cell(roww, 2).value = str(eb[1]) worksheet.cell(roww, 3).value = str(eb[2]) filename3 = vfilter wb3 = load_workbook(filename3) ws3 = wb3.worksheets[0] mr = ws3.max_row mc = ws3.max_column filter = [] for i in range(1, mr + 1): c = ws3.cell(row=i, column=1) filter.append(c.value.upper()) # Grand Tableau expenses = ea row = 26 col = 1 #expenses1 = ec col2 = 6 for aa, bb, cc, dd, ff, gg in (expenses): if str(aa).strip().upper() in filter: worksheet.cell(row, col).value = aa worksheet.cell(row, col).alignment = Alignment(wrapText=True, vertical='top') worksheet.cell(row, col + 1).value = bb worksheet.cell(row, col + 1).alignment = Alignment(wrapText=True, vertical='top') worksheet.cell(row, col + 2).value = cc worksheet.cell(row, col + 2).alignment = Alignment(vertical='top', wrapText=True) worksheet.cell(row, col + 3).value = "'" + str(dd).strip() worksheet.cell(row, col + 3).alignment = Alignment(vertical='top', wrapText=True) worksheet.cell(row, col + 4).value = "'" + str(ff).strip() worksheet.cell(row, col + 4).alignment = Alignment(vertical='top', wrapText=True) worksheet.cell(row, col + 6).value = gg #str(gg).strip() worksheet.cell(row, col + 6).alignment = Alignment(vertical='top', wrapText=True) v_hp = "" v_part = "" v_final = "" v_hp = "" v_part = "" v_final = "" for i in range(len(id_list)): v1 = str(veh_Project_list[i]).strip().upper() + "_" + str( parts_list[i]).strip().upper() if v1 != v_part: if str(aa).strip().upper() == v1.strip().upper(): if str(status_list[i]).strip().upper() == "OPEN": worksheet.cell( row, col2).value = str(id_list[i]) + '\n' worksheet.cell(row, col2).alignment = Alignment( wrapText=True, vertical='top') v_part = v1.strip() v_hp = "" v_final = id_list[i] else: if str(aa).strip().upper() == v1.strip().upper(): if str(status_list[i]).strip().upper() == "OPEN": v_hp += v_final + '\n' + id_list[i] worksheet.cell(row, col2).value = v_hp worksheet.cell(row, col2).alignment = Alignment( wrapText=True, vertical='top') v_final = " " # v_final = aaa[0] + ' , ' row += 1 piece_no_disponible = [] piece_disponible = [] self.progress_bar["value"] = 80 time.sleep(1) root.update() for aa, bb, cc, dd, ff, gg in (expenses): piece_disponible.append(str(aa).upper().strip()) for i in filter: if i not in piece_disponible: piece_no_disponible.append(i) # pour le message des piece non disponible l = '' for k in piece_no_disponible: if k != 'PART': l += ' , ' + str(k) li = 'The following parts ( ' + l + " ) are not available." if l != '': self.vremarque.set(li) self.lremarque['bg'] = '#FC4C4C' else: self.vremarque.set('Report created') self.lremarque['bg'] = '#CAE21E' #indice = len(expenses) + 25 indice = len(filter) - len(piece_no_disponible) + 25 ref = "A25:G" + str(indice) tab3 = Table(displayName="Table2", ref=ref) style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False) tab3.tableStyleInfo = style worksheet.add_table(tab3) # Pour le graphe img = openpyxl.drawing.image.Image('fig.png') img.width = 750 img.height = 370 worksheet.add_image(img, 'A5') my_red = openpyxl.styles.colors.Color(rgb='00FF0000') my_green = openpyxl.styles.colors.Color(rgb='0000FF00') my_orange = openpyxl.styles.colors.Color(rgb='00FFA500') # Couleur colonne B for i in range(26, len(expenses) + 26): if str(worksheet.cell(i, 2).value).strip() == 'Not Passed' or str( worksheet.cell(i, 2).value).strip() == 'Not passed': worksheet.cell(i, 2).value = 'Not passed' worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_red) if str(worksheet.cell(i, 2).value).strip() == 'Conditionally': worksheet.cell(i, 2).value = worksheet.cell(i, 2).value.strip() worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_orange) if str(worksheet.cell(i, 2).value).strip() == 'Passed' or str( worksheet.cell(i, 2).value).strip() == 'passed': worksheet.cell(i, 2).value = 'Passed' worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_green) """v = str(worksheet.cell(i, 2).value) if v.upper().strip() == 'NOT PASSED': worksheet.cell(i, 2).value = 'Not passed' worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_red) if str(worksheet.cell(i, 2).value).upper().strip() == 'CONDITIONALLY': worksheet.cell(i, 2).value = worksheet.cell(i, 2).value.strip() worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_orange) if str(worksheet.cell(i, 2).value).upper().strip() == 'PASSED': worksheet.cell(i, 2).value = 'Passed' worksheet.cell(i, 2).fill = PatternFill(patternType='solid', fgColor=my_green)""" workbook.save(rapport_name) workbook.close() self.progress_bar["value"] = 95 time.sleep(2) root.update() self.progress_bar["value"] = 100 time.sleep(2) root.update() self.progress_bar.grid_forget() root.update() def set_emplacement(self): import time self.FILETYPES = [("text files", "*.xlsx")] self.chemin1 = (askdirectory()) date_now = time.strftime('%d%m%Y') self.chemin = self.chemin1 + '/' + 'F' + date_now + '.xlsx' if self.chemin1 != '': self.create_rapport(self.chemin) def set_fichier1(self): self.vremarque.set('') self.lremarque.grid_remove() self.FILETYPES = [("text files", "*.xlsx")] self.vfichier1.set(askopenfilename(filetypes=self.FILETYPES)) if self.vfichier1.get() != '': self.button1['bg'] = '#006738' def set_fichier2(self): self.lremarque.grid_remove() self.vremarque.set('') self.FILETYPES = [("text files", "*.xlsx")] self.vfichier2.set(askopenfilename(filetypes=self.FILETYPES)) if self.vfichier2.get() != '': self.button2['bg'] = '#006738' def set_project(self): self.vremarque.set('') self.lremarque.grid_remove() self.FILETYPES = [("text files", "*.xlsx")] self.vproject.set(askopenfilename(filetypes=self.FILETYPES)) if self.vfichier1.get() != '': self.bProject['bg'] = '#006738' def set_filter(self): self.FILETYPES = [("text files", "*.xlsx")] self.vfilter_name.set(askopenfilename(filetypes=self.FILETYPES)) if self.vfilter_name.get() != '': self.bpetit_tab['bg'] = '#006738' def create_rapport(self, name_r): if self.vfichier1.get() != '' and self.vfichier1.get( ) != '' and self.chemin1 != '' and self.vfilter_name != '': self.part1(str(self.vfichier1.get()), self.vfichier2.get(), name_r, self.vproject.get(), self.vfilter_name.get()) self.button2['bg'] = '#66B239' self.button1['bg'] = '#66B239' self.bpetit_tab['bg'] = '#66B239' self.bpetit_emp['bg'] = '#66B239' self.bProject['bg'] = '#66B239' self.lremarque.grid(row=7, column=0, sticky='news') else: messagebox.showerror( 'ERROR', "Import all files and select storage location")
class MainGUI: def __init__(self, master, result_row): self.master = master self.result_row = result_row master.resizable(0, 0) self.center(win_w=1020, win_h=760) master.title("ZILLOW SCRAPER") # create a menu menu = Menu(master) master.config(menu=menu) helpmenu = Menu(menu, tearoff=0) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.callback_about) title_comment_frame = Frame(master) title_comment_frame.place(x=200, y=20) title_txt = 'ZILLOW SCRAPER' title_lbl = Label(title_comment_frame, text=title_txt, font=('Comic Sans MS bold', 15), fg='#60A644', width=50) title_lbl.pack(side=TOP, anchor=CENTER, padx=10, pady=10) file_comment_frame = Frame(master) file_comment_frame.place(x=10, y=80) file_comment = 'To use the tool browse for the import file (csv or excel)' comment_lbl = Label(file_comment_frame, text=file_comment, font=('Calibri bold', 12), fg='#60A644') comment_lbl.pack(side=TOP, anchor=W, padx=10, pady=10) image = Image.open('resources/UrbanXHome-Logo.png').convert("RGBA") image = image.resize((130, 80), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image) label = Label(master, image=photo) label.image = photo # keep a reference! # label.place(x=15, y=320) label.place(x=795, y=10) file_path_frame = Frame(master) file_path_frame.place(x=10, y=200) file_path_frame = Frame(master) file_path_frame.place(x=10, y=110) file_path_txt = 'File path:' file_path_lbl = Label(file_path_frame, text=file_path_txt, font=('Calibri', 12), fg='black') file_path_lbl.config(height=2) file_path_lbl.pack(side=LEFT, anchor=CENTER, padx=10, pady=50) self.path = StringVar() self.path.trace( "w", lambda name, index, mode, sv=self.path: self.get_filename(sv)) file_path_entry = Entry(file_path_frame, textvariable=self.path, relief=FLAT, highlightbackground='black', highlightthickness=1) file_path_entry.focus_set() file_path_entry.config(width=110) file_path_entry.pack(side=LEFT, anchor=CENTER, padx=10, pady=50) browse_btn = Button(file_path_frame, text='BROWSE', font=('Calibri bold', 12), bg='#60A644', fg='white', command=self.browse_click) browse_btn.config(width=18, height=1) browse_btn.pack(side=LEFT, anchor=CENTER, padx=20, pady=50) # browse_btn.bind("<Button-1>", self.browse_click) self.status_txt = StringVar() status_lbl = Label(master, textvariable=self.status_txt, font=('Calibri bold', 15), fg='#60A644') status_lbl.config(width=40, height=1) status_lbl.place(x=300, y=235) self.status_txt.set("There are no Zillow lines.") import_bnt = Button(master, text='IMPORT', font=('Calibri bold', 12), bg='#0F75BD', fg='white', command=self.import_click) import_bnt.config(width=18, height=1) import_bnt.place(x=450, y=290) # import_bnt.bind("<Button-1>", self.import_click) assessor_bnt = Button(master, text='GET ZILLOW DATA', font=('Calibri bold', 12), bg='#60A644', fg='white', command=self.assessor_click) assessor_bnt.config(width=18, height=1) assessor_bnt.place(x=450, y=360) # assessor_bnt.bind("<Button-1>", self.assessor_click) progress_frame = Frame(master) progress_frame.place(x=60, y=415) self.prog_ratio_txt = StringVar() prog_ratio_lbl = Label(progress_frame, textvariable=self.prog_ratio_txt, font=('Calibri bold', 12), fg='#60A644') prog_ratio_lbl.pack(side=TOP, anchor=CENTER, padx=0) prog_ratio_lbl.config(width=20) self.progress = Progressbar(progress_frame, orient=HORIZONTAL, length=850, mode='determinate') self.progress.pack(side=LEFT, anchor=CENTER, padx=20) self.prog_percent_txt = StringVar() prog_percent_lbl = Label(progress_frame, textvariable=self.prog_percent_txt, font=('Calibri bold', 12), fg='#60A644') prog_percent_lbl.pack(side=RIGHT, anchor=CENTER, padx=0) table_frame = Frame(master) table_frame.place(x=18, y=500) yscrollbar = Scrollbar(table_frame, orient=VERTICAL) yscrollbar.pack(side=RIGHT, fill=Y) xscrollbar = Scrollbar(table_frame, orient=HORIZONTAL) xscrollbar.pack(side=BOTTOM, fill=X) self.listbox = Listbox(table_frame, width=160, height=14) self.listbox.pack() # attach listbox to scrollbar self.listbox.config(yscrollcommand=yscrollbar.set) self.listbox.config(xscrollcommand=xscrollbar.set) yscrollbar.config(command=self.listbox.yview) xscrollbar.config(command=self.listbox.xview) self.listbox_rows_cnt = 0 self.zillow_lines = [] self.running = 0 def browse_click(self): # def browse_click(self, event): fname = askopenfilename(filetypes=(("Input files", "*.csv;*.xlsx;*.xls"), ("CSV files", "*.csv"), ("Excel files", "*.xls;*.xlsx"), ("All files", "*.*"))) if fname: self.path.set(fname) def import_click(self): fname = self.path.get() if fname: if fname.endswith('xlsx'): input_xls = xlrd.open_workbook(fname) sheet = input_xls.sheet_by_index(0) headers = [ sheet.cell(0, col_index).value for col_index in range(sheet.ncols) ] for row_index in range(0, sheet.nrows): row = [ sheet.cell(row_index, col_index).value if isinstance( sheet.cell(row_index, col_index).value, str) else str(int(sheet.cell(row_index, col_index).value)) for col_index in range(sheet.ncols) ] if all(elm == '' for elm in row): continue self.zillow_lines.append(row) elif fname.endswith('csv'): csv_reader = csv.reader(open(fname, 'r', encoding='utf-8')) for i, row in enumerate(csv_reader): if all(elm == '' for elm in row): continue self.zillow_lines.append(row) global TOTAL_CNT TOTAL_CNT = len(self.zillow_lines) - 1 self.status_txt.set( 'There are {} Zillow lines imported'.format(TOTAL_CNT)) else: messagebox.showwarning("Warning", "Please input file name.") def assessor_click(self): # def assessor_click(self, event): if self.zillow_lines: self.running = 1 else: messagebox.showwarning( "Warning", "There are no Zillow lines. Please input file name.") def get_filename(self, sv): print(sv.get()) def center(self, win_w=1200, win_h=800): rootsize = (win_w, win_h) w = self.master.winfo_screenwidth() h = self.master.winfo_screenheight() x = w / 2 - rootsize[0] / 2 y = h / 2 - rootsize[1] / 2 self.master.geometry("%dx%d+%d+%d" % (rootsize + (x, y))) def update_prog_bar(self): global TOTAL_CNT while self.result_row.qsize(): try: result_row = self.result_row.get(0) total_completed = result_row[0] self.prog_ratio_txt.set("{}/{}".format(total_completed, TOTAL_CNT)) self.prog_percent_txt.set('{}%'.format( math.floor(total_completed / TOTAL_CNT * 100))) self.progress['value'] = math.floor(total_completed / TOTAL_CNT * 100) result = result_row self.listbox.insert(END, str(result)) self.listbox_rows_cnt += 1 if self.listbox_rows_cnt > 10000: self.listbox.delete(0, 0) self.listbox.yview(END) if total_completed == TOTAL_CNT: messagebox.showinfo('Success', "Zillow details have been extracted!") except: pass def callback_about(self): about_txt = "Joseph Nguyen\n" messagebox.showinfo('About', about_txt)
class SolutionTabFrame(Frame): ''' This class is responsible for displaying solution on the screen. It extends Frame class. Attributes: parent (Tk object that can contain Frame): parent that can contain Frame, MUST implement method change_solution_tab_name(str). data_from_file_lbl (Label): label that contains file name with data if specified. solution_tab (SolutionFrameWithText): notebook with tabs describing solution. model_solutions (list of Solution): list with one or more solutions that have been generated after running algorithm. param_strs (list of str): list with strings that should appear before printing every solution from model_solutions. ranks (list of list of int): list of ranks corresponding to every solution from model_solutions, ranks are generated by peel-the-onion algorithm. categorical (str): name of the categorical variable used in categorical analysis. progress_bar (Progressbar): progress bar to show how solution is loaded or saved to file. status_lbl (Label): label for displaying solution status. solution_format_var (IntVar): IntVar object that tracks which file format is chosen for solution. ''' def __init__(self, parent, *args, **kw): super().__init__(parent, *args, **kw) self.parent = parent self.data_from_file_lbl = None self.solution_tab = None self.model_solutions = None self.param_strs = None self.ranks = None self.params = None self.categorical = None self.run_date = None self.total_seconds = 0 self.progress_bar = None self.status_lbl = None self.solution_format_var = IntVar() self.create_widgets() def create_widgets(self): ''' Creates appropriate widgets on this frame. ''' self.columnconfigure(0, weight=1) self.rowconfigure(3, weight=1) frame_for_save_btn = Frame(self) frame_for_save_btn.columnconfigure(1, weight=1) self.status_lbl = Label(frame_for_save_btn, text='') self.status_lbl.grid(row=0, column=1, sticky=N+W) save_solution_btn = Button(frame_for_save_btn, text='Save solution', command=self.on_save_solution) save_solution_btn.grid(row=1, column=0, sticky=W+N, padx=5, pady=5) self.progress_bar = Progressbar(frame_for_save_btn, mode='determinate', maximum=100) self.progress_bar.grid(row=1, column=1, sticky=W+E, padx=10, pady=5) frame_for_save_btn.grid(sticky=W+N+E+S, padx=5, pady=5) frame_for_btns = Frame(self) self._create_file_format_btn('*.xlsx', 1, frame_for_btns, 0) self._create_file_format_btn('*.xls', 2, frame_for_btns, 1) self._create_file_format_btn('*.csv', 3, frame_for_btns, 2) self.solution_format_var.set(1) frame_for_btns.grid(row=1, column=0, sticky=W+N+E+S, padx=5, pady=5) self.data_from_file_lbl = Label(self, text=TEXT_FOR_FILE_LBL, anchor=W, justify=LEFT, wraplength=MAX_FILE_PARAMS_LBL_LENGTH) self.data_from_file_lbl.grid(row=2, column=0, padx=5, pady=5, sticky=W+N) self.solution_tab = SolutionFrameWithText(self) self.solution_tab.grid(row=3, column=0, sticky=W+E+S+N, padx=5, pady=5) def _create_file_format_btn(self, btn_text, var_value, parent, column): ''' Creates and grids Radiobutton used for choosing solution file format. Args: btn_text (str): text displayed next to the Radiobutton. var_value (int): value of the IntVar associated with this Radiobutton. parent (Tk object): parent of this Radiobutton. column (int): column index where this Radiobutton should be gridded. ''' sol_format_btn = Radiobutton(parent, text=btn_text, variable=self.solution_format_var, value=var_value) sol_format_btn.grid(row=2, column=column, sticky=W+N, padx=2) def on_save_solution(self): ''' Saves solution to file. This method is called when save solution button is pressed. If there is a solution, this method will ask user to provide a file name where solution should be stored. If a valid name is provided, solution is saved to that file. Allowed file formats are: .xls and .xlsx. Default file extension is .xlsx. If the user checked 'csv' as solution output format, then the user will be asked to choose a directory where all csv files will be written. ''' if self.model_solutions is not None: assert(self.param_strs is not None) if (self.solution_format_var.get() == 1 or self.solution_format_var.get() == 2): file_name = self.ask_file_name_to_save( self.solution_format_var.get()) dir_name = '' else: dir_name = askdirectory() file_name = '' if file_name or dir_name: print(file_name) self.status_lbl.config(text='Saving solution to file...') if file_name.endswith('.xls'): work_book = xlwt.Workbook() elif file_name.endswith('.xlsx'): work_book = XlsxWorkbook() else: # all not supported formats will be written to csv assert(dir_name) work_book = TxtWriter(dir_name) writer = XLSWriter(self.params, work_book, self.run_date, self.total_seconds, ranks=self.ranks, categorical=self.categorical) nb_models = len(self.model_solutions) # +1 for parameters sheet, it is stored separately nb_sheets = len(writer.worksheets) + 1 progress_recorder = GuiProgress(self.progress_bar, nb_models, nb_sheets) try: for count, sol in enumerate(self.model_solutions): writer.write_data(sol, self.param_strs[count], progress_recorder) work_book.save(file_name) except ValueError: # can happen if maximum number of rows is exceeded self.status_lbl.config( text='File is too large for xls format,' ' it will be saved to csv instead') work_book = TxtWriter(os.path.splitext(file_name)[0]) writer = XLSWriter(self.params, work_book, self.run_date, self.total_seconds, ranks=self.ranks, categorical=self.categorical) progress_recorder.set_position(0) for count, sol in enumerate(self.model_solutions): writer.write_data(sol, self.param_strs[count], progress_recorder) work_book.save(file_name) progress_recorder.set_position(100) self.parent.change_solution_tab_name('Solution') self.status_lbl.config(text='Solution saved') def ask_file_name_to_save(self, ext_code): ''' Calls asksaveasfilename dialogue to ask the user where file should be saved. If file without extension is entered, default extension will be used (.xlsx). This method is used to mock this object for unit tests. Args: ext_code (int): code for file extension 1 - xlsx, 2 - xls. ''' if ext_code == 1: filetype = SOLUTION_XLSX_FILE else: filetype = SOLUTION_XLS_FILE return asksaveasfilename(filetypes=filetype, defaultextension='xlsx') def show_solution(self, solutions, params, param_strs, run_date, total_seconds, ranks=None, categorical=None): ''' Displays solution on the screen. Args: solutions (list of Solution): list of solutions (might contain just one solution) that have been generated after running algorithm. params (Parameters): object with parameters that will be written to file on the Parameters page. param_strs (list of str): list with strings that should appear before printing every solution from model_solutions. ranks (list of list of int): list of ranks corresponding to every solution from model_solutions, ranks are generated by peel-the-onion algorithm. categorical (str): name of the categorical variable used in categorical analysis. ''' self.status_lbl.config(text='') self.model_solutions = solutions self.param_strs = param_strs self.ranks = ranks self.params = params self.categorical = categorical self.run_date = run_date self.total_seconds = total_seconds self.status_lbl.config(text='Loading solution...') self.solution_tab.show_solution(solutions, params, param_strs, run_date, total_seconds, ranks, categorical) self.parent.change_solution_tab_name('Solution*') self.status_lbl.config(text='Solution loaded') def update_data_file_name(self, new_data_file_name): ''' Updates label with data file name. Args: new_data_file_name (str): new value of the data file name ''' self.data_from_file_lbl.config(text=TEXT_FOR_FILE_LBL + new_data_file_name)
def createWidgets(self): ## creazione di un menu e sua aggiunta ## menu = Menu(self.root) # self.root.config(menu=menu) ## creazione di un oggetto file ## file = Menu(menu) ## associazione azione all'oggetto ## file.add_command(label="Exit", command=self.client_exit) ## aggiunta del file al menu ## menu.add_cascade(label="File", menu=file) ## quadro gestione tracker self.quadro_tracker = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_tracker.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro login logout self.quadro_login = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_login.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro centrale della ricerca self.quadro_centrale_ricerca = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_centrale_ricerca.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro centrale della ricerca self.quadro_centrale_file = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_centrale_file.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro con file caricati self.quadro_console = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_console.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ##----------------quadro modifica del tracker------------------------ self.lb_tracker_ip4 = Label(self.quadro_tracker, text='IPv4 Tracker', background="white") self.lb_tracker_ip4.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.tracker_ip4 = StringVar() self.en_tracker_ip4 = Entry(self.quadro_tracker, textvariable=self.tracker_ip4, width=15) self.en_tracker_ip4.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.tracker_ip4.set(Utility.IPv4_TRACKER) self.lb_tracker_ip6 = Label(self.quadro_tracker, text='IPv6 Tracker', background="white") self.lb_tracker_ip6.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.tracker_ip6 = StringVar() self.en_tracker_ip6 = Entry(self.quadro_tracker, textvariable=self.tracker_ip6, width=35) self.en_tracker_ip6.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.tracker_ip6.set(Utility.IPv6_TRACKER) self.btn_tracker_config = Button(self.quadro_tracker, command=self.btn_conferma_config_click) self.btn_tracker_config.config(text="Conferma", width=self.larg_bottoni) self.btn_tracker_config.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y) ## ---------------aggiunta dei pulsanti di login e logout------------ self.btn_login = Button(self.quadro_login, command=self.btn_login_click) self.btn_login.configure(text="LOGIN", width=self.larg_bottoni) self.btn_login.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.btn_logout = Button(self.quadro_login, command=self.btn_logout_click) self.btn_logout.configure(text="LOGOUT", width=self.larg_bottoni) self.btn_logout.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.status = StringVar() self.lb_status = Label(self.quadro_login, textvariable=self.status, background="white") self.lb_status.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y) self.status.set("STATUS") ## ------------------fine parte login logout ----------------------- ##------------ quadri di divisione della ricerca e scaricamento------------- self.quadro_sinistro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE) self.quadro_sinistro_ricerca.pack(side=LEFT, fill=BOTH, expand=1, ipadx = self.imb_int_x, ipady = self.imb_int_y, padx=self.imb_x, pady=self.imb_y) self.quadro_destro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE,) self.quadro_destro_ricerca.pack(side=LEFT, fill=BOTH, expand =1, ipadx=self.imb_int_x, ipady=self.imb_int_y, padx=self.imb_x, pady=self.imb_y) ## inserimento widget di ricerca e scaricamento self.en_ricerca = Entry(self.quadro_sinistro_ricerca) self.en_ricerca.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.btn_ricerca = Button(self.quadro_sinistro_ricerca, command=self.btn_ricerca_click) self.btn_ricerca.configure(text="RICERCA", width=self.larg_bottoni) self.btn_ricerca.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.var_progresso = StringVar() self.lb_progresso = Label(self.quadro_sinistro_ricerca, textvariable=self.var_progresso, background="white") self.lb_progresso.pack(fill=BOTH, side=TOP, padx=self.imb_x, pady=self.imb_y) self.var_progresso.set('Progresso Scaricamento') self.prog_scaricamento = Progressbar(self.quadro_sinistro_ricerca, orient='horizontal', mode='determinate') self.prog_scaricamento.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y) ## inserimento listbox dei risultati della ricerca e bottone scarica dalla selezione self.list_risultati = Listbox(self.quadro_destro_ricerca) self.list_risultati.pack(side=TOP, fill=BOTH, pady=self.imb_y) self.btn_scarica = Button(self.quadro_destro_ricerca, command=self.btn_scarica_click) self.btn_scarica.configure(text="SCARICA", width=self.larg_bottoni) self.btn_scarica.pack(side=TOP) ##--------------- fine parte della ricerca scaricamento ------------------- ##---------------- parte di aggiunta dei file ----------------------------- ## quadri di divisione per l'aggiunta self.quadro_sinistro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE) self.quadro_sinistro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y) self.quadro_destro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE) self.quadro_destro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y) self.lb_file = Label(self.quadro_sinistro_file, text='Gestione dei File', background="white") self.lb_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.btn_aggiungi_file = Button(self.quadro_sinistro_file, command=self.btn_aggiungi_file_click) self.btn_aggiungi_file.configure(text="AGGIUNGI", width=self.larg_bottoni) self.btn_aggiungi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.btn_rimuovi_file = Button(self.quadro_sinistro_file, command=self.btn_rimuovi_file_click) self.btn_rimuovi_file.configure(text="RIMUOVI", width=self.larg_bottoni) self.btn_rimuovi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.list_file = Listbox(self.quadro_destro_file) self.list_file.pack(side=TOP, fill=BOTH, pady=self.imb_y) ##---------------- fine parte gestione dei file --------------------------- ##---------------- parte di console per le scritture eventuali------------- self.text_console = Text(self.quadro_console, state=NORMAL) self.text_console.pack(side=TOP, fill=BOTH)
def startLearning(): progress = Progressbar(win, orient=HORIZONTAL, length=250, mode='determinate') progress.grid(row=0, sticky="N", padx=90, pady=420) # Importing the dataset data = pd.read_csv('data.csv', sep='|') X = data.drop(['Name', 'md5', 'legitimate'], axis=1).values y = data['legitimate'].values #open file to save logFile = open("Results.txt", "w") logFile.write("Researching important feature based on " + str(X.shape[1]) + " total features") progress['value'] = 10 win.update_idletasks() time.sleep(1) print('Researching important feature based on %i total features\n' % X.shape[1]) # Feature selection using Trees Classifier fsel = ske.ExtraTreesClassifier().fit(X, y) model = SelectFromModel(fsel, prefit=True) X_new = model.transform(X) nb_features = X_new.shape[1] temp = 20 # Splitting the dataset into the Training set and Test set X_train, X_test, y_train, y_test = train_test_split(X_new, y, test_size=0.2) features = [] print('%i features identified as important:' % nb_features) logFile.write("\n features identified as important: " + str(nb_features)) progress['value'] = 20 win.update_idletasks() time.sleep(1) win.update() indices = np.argsort(fsel.feature_importances_)[::-1][:nb_features] for f in range(nb_features): print("%d. feature %s (%f)" % (f + 1, data.columns[2 + indices[f]], fsel.feature_importances_[indices[f]])) logFile.write("\n feature " + str(f + 1) + " " + str(data.columns[2 + indices[f]]) + " " + str(fsel.feature_importances_[indices[f]])) progress['value'] = temp = temp + 2 win.update_idletasks() time.sleep(1) win.update() progress['value'] = 50 win.update_idletasks() time.sleep(1) win.update() # Take care of the feature order for f in sorted(np.argsort(fsel.feature_importances_)[::-1][:nb_features]): features.append(data.columns[2 + f]) #Algorithm comparison algorithms = { "DecisionTree": tree.DecisionTreeClassifier(max_depth=10), "RandomForest": ske.RandomForestClassifier(n_estimators=50), } results = {} print("\nNow testing algorithms") logFile.write("\nNow testing algorithms") progress['value'] = 70 win.update_idletasks() time.sleep(1) win.update() # Fitting Classification algorithms to the Training set for algo in algorithms: clf = algorithms[algo] clf.fit(X_train, y_train) score = clf.score(X_test, y_test) print("%s : %f %%" % (algo, score * 100)) logFile.write( str(algo) + " " + str(float("{:.5f}".format(score * 100)))) results[algo] = score winner = max(results, key=results.get) f = float("{:.5f}".format(results[winner] * 100)) res = "\nWinner algorithm is " + str(winner) + " with a " + str( f) + "% accuracy" logFile.write(res) print(res) progress['value'] = 90 win.update_idletasks() time.sleep(1) win.update() # Save the algorithm and the feature list for later predictions print('Saving algorithm and feature list in classifier directory...') logFile.write( "\nSaving algorithm and feature list in classifier directory...") joblib.dump(algorithms[winner], 'classifier/classifier.pkl') open('classifier/features.pkl', 'wb').write(pickle.dumps(features)) print('Saved') logFile.write("\nSaved successfully") # Predicting the Test set results y_pred = clf.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) progress['value'] = 100 msgBox = tk.messagebox.showinfo("Success!!", res + "\n Details saved in log file Results.txt", icon="info") progress.grid(pady=1000)
class App(Tk): def __init__(self, master, u, p): self.master = master self.u = u self.p = p self.master.title("Auto-joiner") self.master.config(bg='LightSkyBlue4') self.master.geometry("880x619+200+120") self.frame = Frame(self.master) self.frame.pack() self.frame.config(bg='LightSkyBlue4') self.trb = Label(self.frame, text='\n', font=('arial', 20, 'bold'), bg='LightSkyBlue4', fg='gray20') self.trb.grid(row=0, column=0) self.Logfr1 = LabelFrame(self.frame, width=750, height=200, font=('arial', 20, 'bold'), relief='ridge', bg='cyan4', bd=10) self.Logfr1.grid(row=1, column=0) # # self.Title = Label(self.Logfr1, text='Meet Auto-Joiner', font=('arial', 50, 'bold'), bg='cyan4', fg='gray20') self.Title.grid(row=0, column=0, columnspan=2, ipadx=50) self.btn = Button(self.Logfr1, text='Start', font=('arial', 15, 'bold'), width=16, command=self.start) self.btn.grid(row=1, column=0, ipadx=30) self.progress = Progressbar(self.Logfr1, orient=HORIZONTAL, length=260, mode='indeterminate') self.progress.grid(row=2, column=0, ipady=11) #btns and entries global delete_box delete_box = Entry(self.Logfr1, width=20, font=('arial', 15, 'bold'), bg='aquamarine3', justify='center') delete_box.grid(row=5, column=0, columnspan=3) delete_box_label = Label( self.Logfr1, text= "Input your ID in the box below in order to Delete/Edit a meeting\nYou can find the ID in the timetable for the desired day ", font=('arial', 15, 'bold'), bd=22, bg='cyan4', fg='black') delete_box_label.grid(row=4, column=0, columnspan=3) self.submit_btn = Button(self.Logfr1, text="Schedule a meeting", font=('arial', 15, 'bold'), width=16, command=self.submit) self.submit_btn.grid(row=1, column=1, columnspan=2, pady=10, padx=30, ipadx=34) self.query_btn = Button(self.Logfr1, text="Timetable", font=('arial', 15, 'bold'), width=11, command=self.query) self.query_btn.grid(row=3, column=1, columnspan=2, pady=0, ipadx=15) self.clicked_query = StringVar() self.currentDay = datetime.today().strftime("%A") self.clicked_query.set(self.currentDay) self.select_query = OptionMenu(self.Logfr1, self.clicked_query, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") self.select_query.grid(row=2, column=1, columnspan=2, pady=10, ipadx=8, ipady=2) self.select_query.config(font=('arial', 15, 'bold'), width=10) self.select_query['menu'].config(font=('arial', 15, 'bold')) self.delete_btn = Button(self.Logfr1, text="Delete a meeting", font=('arial', 15, 'bold'), width=16, command=self.delete) self.delete_btn.grid(row=6, column=1, columnspan=2, ipadx=43) self.edit_btn = Button(self.Logfr1, text="Edit a meeting", font=('arial', 15, 'bold'), width=16, command=self.edit) self.edit_btn.grid(row=6, column=0, columnspan=1, pady=10, padx=18, ipadx=35) self.exit_btn = Button(self.Logfr1, text="Stop", font=('arial', 15, 'bold'), width=16, command=self.exit) self.exit_btn.grid(row=3, column=0, pady=10, padx=10, ipadx=30) self.t = 0 def exit(self): self.t = 1 def delete(self): conn = sqlite3.connect('timetable.db') c = conn.cursor() try: c.execute("DELETE from addresses WHERE oid=" + delete_box.get()) except: return delete_box.delete(0, END) conn.commit() conn.close() def edit(self): self.newWin1 = Toplevel(self.master) self.app = editWin(self.newWin1) def submit(self): self.newWin2 = Toplevel(self.master) self.app = submitWin(self.newWin2) def query(self): # shows all the records self.add_query = tk.Toplevel(self.master) self.add_query.config(bg='cyan4') self.add_query.title("Timetable") conn = sqlite3.connect('timetable.db') c = conn.cursor() c.execute( "SELECT *,oid FROM addresses ORDER BY datetime(starting_hour) ASC") records = c.fetchall() record_id = self.clicked_query.get() self.Lbfr3 = LabelFrame(self.add_query, width=750, height=200, font=('arial', 20, 'bold'), relief='ridge', bg='cyan4', bd=10) self.Lbfr3.grid(row=1, column=2) #------------------------------------- self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=1) self.e.insert(END, "Day") self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=2) self.e.insert(END, "Name") self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=3) self.e.insert(END, "Starting Hour") self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=4) self.e.insert(END, "Ending Hour") self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=5) self.e.insert(END, "Link") self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=0, column=6) self.e.insert(END, "ID") #------------------------------------- i = 1 temp = 0 for record in records: if record_id == record[0]: for j in range(1, 7): self.e = Entry(self.Lbfr3, width=12, bg='cyan4', fg='black', font=('Arial', 20, 'bold'), justify='center') self.e.grid(row=i, column=j) self.e.insert(END, record[j - 1]) i = i + 1 conn.commit() conn.close() def start(self): def isAlive(): try: driver.current_url return True except: return False def real_start(): self.progress.start() #the actual thread starts here conn = sqlite3.connect('timetable.db') c = conn.cursor() c.execute("SELECT *, oid FROM addresses ") records = c.fetchall() conn.commit() conn.close() ok = 0 while True: if self.t == 1: self.t = 0 break curTime = strftime("%H:%M") dayy = datetime.today().strftime("%A") for record in records: if str(record[2]) == curTime and record[0] == dayy: #if we got the starting hour and corect day: ok = 0 sub = str(record[4]) gmail_login(sub, self.u, self.p, record[3]) # elif ok == 0 and str( record[3] ) == curTime: # if during the previous meeting we get the ending hour, we need the ok variable to not loop = 1 # we have some problems here, because we either want to exit the meeting, due to a gap between meetings or a new meeting starts right after # and we need to synch this stuff c = 0 while loop: # the loop will check if there are only 5 participants left and it'll exit and at the same time if another meeting has started # if it exits before the time the next meeting has started, ok becomes 1 , loop 0 and we go back to the main if and will start from there again if isAlive() == False: ok = 1 time.sleep(50) break try: numOfParticipants = int( driver.find_element_by_xpath( '/html/body/div[1]/c-wiz/div[1]/div/div[8]/div[3]/div[6]/div[3]/div/div[2]/div[1]/span/span/div/div/span[2]' ).get_attribute('innerHTML')) except: numOfParticipants = 0 testing = 0 if numOfParticipants <= 5: c = 1 if c == 1: loop = 0 ok = 1 driver.close() break else: d = strftime("%H:%M") for idem in records: if str(idem[2]) == d: loop = 0 ok = 1 driver.close() break time.sleep(5) #increases the performance a bit time.sleep(5) #self.start_temp() ####fasffasgasg global submit_thread submit_thread = threading.Thread(target=real_start) submit_thread.daemon = True submit_thread.start() self.master.after(20, self.check_submit_thread) def check_submit_thread(self): if submit_thread.is_alive(): self.master.after(20, self.check_submit_thread) else: self.progress.stop()
spoiler_percentage_var = tk.StringVar() spoiler_percentage_var.set("100") exclude_healing_var = tk.BooleanVar() exclude_ammo_var = tk.BooleanVar() exclude_progression_var = tk.BooleanVar() exclude_weapons_var = tk.BooleanVar() # Outputs cs_label = tk.Label(root, height=2) spoiler_label = tk.Label(root, text='Spoiler percentage: ') spoiler_description = tk.Label(root, text=SPOILER_DESC) exclude_label = tk.Label(root, text='Exclude from spoiler:') exclude_healing_label = tk.Label(root, text=EXCLUDE_HEALING_DESC) exclude_ammo_label = tk.Label(root, text=EXCLUDE_AMMO_DESC) exclude_progression_label = tk.Label(root, text=EXCLUDE_PROGRESSION_DESC) exclude_weapons_label = tk.Label(root, text=EXCLUDE_WEAPONS_DESC) progressbar = Progressbar(root, orient=tk.HORIZONTAL, length=550, mode='determinate') # Inputs run_button = tk.Button(root, text='Generate maps', state=tk.DISABLED) leon_radio_button = tk.Radiobutton(root, text='Leon A', value=1, variable=playthrough_var) claire_radio_button = tk.Radiobutton(root, text='Claire A', value=2, variable=playthrough_var) cs_button = tk.Button(root, text='Select CheatSheet') credits_button = tk.Button(root, text='Credits') spoiler_percentage = tk.Spinbox(root, from_=0, to=100, width=5, textvariable=spoiler_percentage_var) exclude_cb_healing = tk.Checkbutton(root, text='Healing items', var=exclude_healing_var) exclude_cb_ammo = tk.Checkbutton(root, text='Ammunition', var=exclude_ammo_var) exclude_cb_weapons = tk.Checkbutton(root, text='Weapons', var=exclude_weapons_var) exclude_cb_progression = tk.Checkbutton(root, text='Progression items', var=exclude_progression_var) # LAYOUT ####################################################################################################################
def action(): """ ProgressBar is also attached to see if it works but it doesn't works well as threading is not used so the functions doesn't run in background or they run at main loop """ progress = Progressbar(win, orient="horizontal", length=300, mode='determinate') progress.grid(row=5) progress["maximum"] = 100 start_time = time.time() #Starting progress bar here progress.start() folderAddress = os.getcwd() progress['value'] = time.time() - start_time progress.update() def makeFolder(folderAddress, directoryName): try: os.mkdir(folderAddress + "\\" + directoryName) except FileExistsError: pass Code_128 = "code128" letter_words_1 = gender_var.get() letter_words_2 = gender_var_2.get() progress['value'] = time.time() - start_time progress.update() #function add table of columns*rows,i.e 4*1000 barcodes with 100 barcodes in single page to entire document def fasterSolution(folderAddress, pic, progress): progress['value'] = time.time() - start_time progress.update() document = Document() COLUMNS = 4 ROWS = 1000 table = document.add_table(rows=ROWS, cols=COLUMNS) table_cells = table._cells for i in range(ROWS): row_cells = table_cells[i * COLUMNS:(i + 1) * COLUMNS] for cell in row_cells: paragraph = cell.paragraphs[0] run = paragraph.add_run() run.add_picture(folderAddress + "\\" + pic + ".png", width=350000 * 0.71, height=350000 * 0.49) progress['value'] = time.time() - start_time progress.update() document.save(folderAddress + "\\" + "singleFolder" + "\\" + pic + "_" + str(1) + ".docx") progress['value'] = time.time() - start_time progress.update() #function add table of columns*rows,i.e 4*100 barcodes with 100 barcodes in single page to entire document def putIntoDocumentFiles(folderAddress, pic): document = Document() table = document.add_table(rows=100, cols=4) #ROWS=25 For 100 barcodes for row in table.rows: for cell in row.cells: paragraph = cell.paragraphs[0] run = paragraph.add_run() run.add_picture( folderAddress + "\\" + pic + ".png", width=350000 * 0.71, height=350000 * 0.49 ) #(width,height)=>dimensions(singleTableRow,singleTableColumn) for singlePage document.save(folderAddress + "\\singleFolder" + "\\" + pic + "_" + "1" + ".docx") #for i in range(2): #document.save(folderAddress+"\\singleFolder"+"\\"+pic+"_"+str(i+1)+".docx") #print(f'{input_1} and {input_2}') pageNumber = int(page_var.get()) array, array2 = [], [] #print('here') for i in range(1, 1 + pageNumber): progress['value'] = time.time() - start_time progress.update() barcode_Name = letter_words_1 + letter_words_2 + "00" + str(i) ean = barcode.get(Code_128, barcode_Name, writer=ImageWriter()) print(folderAddress + "\\" + barcode_Name) filename = ean.save( folderAddress + "\\" + barcode_Name ) #saves to [MG001.png,MG002.png...MG00(pageNumber).png] array.append(folderAddress + "\\" + barcode_Name + ".png") array2.append(barcode_Name) makeFolder(folderAddress, "singleFolder") for a, b in zip(array, array2): progress['value'] = time.time() - start_time progress.update() #putIntoDocumentFiles(folderAddress,b) fasterSolution(folderAddress, b, progress) progress['value'] = time.time() - start_time progress.update() #Stopping progress bar here progress.stop()
var = IntVar() var.set(36) spin = Spinbox(window, from_=0, to=100, width=5, textvariable=var, command=spin_changed) #spin = Spinbox(window, values=(3, 8, 11), width=5) spin.grid(column=0, row=10) # progressbar example from tkinter.ttk import Progressbar bar = Progressbar(window, length=500) bar['value'] = 70 # 70 means 70% bar.grid(column=0, row=11) # style Progressbar style = Style() style.theme_use('default') style.configure("black.Horizontal.TProgressbar", background='black') bar2 = Progressbar(window, length=500, style='black.Horizontal.TProgressbar') bar2['value'] = 70 bar2.grid(column=0, row=12) # filedialog from tkinter import filedialog
def createwidthes(): global imbrowsing, immute, ProgressbarMusicLabel, ProgressbarLabel, ProgressbarVolume, ProgressbarVolumeLabel, imunmute, impasue, imresume, imvloumeup, imvloumedown, implay, imstop global AudioStatusLabel, ProgressbarMusicStartTimeLabel, ProgressbarMusic, ProgressbarMusic, ProgressbarMusicEndTimeLabel #######Images Register########## imbrowsing = PhotoImage(file='browsing.png') implay = PhotoImage(file='play-button.png') impasue = PhotoImage(file='pause (3).png') imresume = PhotoImage(file="play-button.png") imvloumeup = PhotoImage(file='volume-up.png') imstop = PhotoImage(file='stop.png') immute = PhotoImage(file='mute.png') imunmute = PhotoImage(file='volume.png') imvloumedown = PhotoImage(file='volume-down.png') ############change size of images########### imbrowsing = imbrowsing.subsample(15, 15) implay = implay.subsample(15, 15) impasue = impasue.subsample(15, 15) imresume = imresume.subsample(15, 15) imvloumeup = imvloumeup.subsample(15, 15) imstop = imstop.subsample(15, 15) immute = immute.subsample(15, 15) imunmute = imunmute.subsample(15, 15) imvloumedown = imvloumedown.subsample(15, 15) #######labels####### TrackLabel = Label(root, text="Select Audio Track:", bg='lightskyblue', font=('arial', 15, 'italic bold')) TrackLabel.grid(row=0, column=0, padx=20, pady=20) AudioStatusLabel = Label(root, text="paused", bg='lightskyblue', font=('arial', 15, 'italic bold'), width=20) AudioStatusLabel.grid(row=2, column=1, padx=20, pady=20) ##### Entry Box##### TrackLabelEntry = Entry(root, font=('arial', 15, 'italic bold'), width=35, textvariable=audiotrack) TrackLabelEntry.grid(row=0, column=1, padx=20, pady=20) ######Button####### BrowseButton = Button(root, text='Search', bg='deeppink', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=imbrowsing, compound=RIGHT, command=musicurl) BrowseButton.grid(row=0, column=2, padx=20, pady=20) BrowsePlay = Button(root, text='Play', bg='green2', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=implay, compound=RIGHT, command=playmusic) BrowsePlay.grid(row=1, column=0, padx=20, pady=20) root.BrowsePause = Button(root, text='Pause', bg='yellow', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=impasue, compound=RIGHT, command=pausemusic) root.BrowsePause.grid(row=1, column=1, padx=20, pady=20) root.BrowseResume = Button(root, text='Resume', bg='yellow', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=imresume, compound=RIGHT, command=resumemusic) root.BrowseResume.grid(row=1, column=1, padx=20, pady=20) root.BrowseResume.grid_remove() root.BrowseMute = Button(root, text='Mute', width=100, bg='yellow', activebackground='purple4', bd=5, image=immute, compound=RIGHT, command=mutemusic) root.BrowseMute.grid(row=3, column=3) root.BrowseMute.grid_remove() root.BrowseUnMute = Button(root, text='UnMute', width=100, bg='yellow', activebackground='purple4', bd=5, image=imunmute, compound=RIGHT, command=unmutemusic) root.BrowseUnMute.grid(row=3, column=3) BrowseVolumeUp = Button(root, text='VolumeUp', bg='blue', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=imvloumeup, compound=RIGHT, command=volumeup) BrowseVolumeUp.grid(row=1, column=2, padx=20, pady=20) BrowseStop = Button(root, text='Stop', bg='red', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=imstop, compound=RIGHT, command=stopmusic) BrowseStop.grid(row=2, column=0, padx=20, pady=20) BrowseVolumeDown = Button(root, text='VolumeDown', bg='blue', font=('arial', 13, 'italic bold'), width=200, bd=5, activebackground='purple4', image=imvloumedown, compound=RIGHT, command=volumedown) BrowseVolumeDown.grid(row=2, column=2, padx=20, pady=20) ##################3progressbar valume######################3333333 ProgressbarLabel = Label(root, text='', bg='red') ProgressbarLabel.grid(row=0, column=3, rowspan=3, padx=20, pady=20) ProgressbarLabel.grid_remove() ProgressbarVolume = Progressbar(ProgressbarLabel, orient=VERTICAL, mode='determinate', value=0, length=190) ProgressbarVolume.grid(row=0, column=0, ipadx=5) ############################ ProgressbarVolumeLabel = Label(ProgressbarLabel, text='0%', bg='lightgray', width=3) ProgressbarVolumeLabel.grid(row=0, column=0) ##########################Progressbarmusic################################ ProgressbarMusicLabel = Label(root, text='', bg='red') ProgressbarMusicLabel.grid(row=3, column=0, columnspan=3, padx=20, pady=20) ProgressbarMusicLabel.grid_remove() ProgressbarMusicStartTimeLabel = Label(ProgressbarMusicLabel, text='0:00:0', bg='red', width=6) ProgressbarMusicStartTimeLabel.grid(row=0, column=0) ProgressbarMusic = Progressbar(ProgressbarMusicLabel, orient=HORIZONTAL, mode='determinate', value=0) ProgressbarMusic.grid(row=0, column=1, ipadx=370, ipady=3) ProgressbarMusicEndTimeLabel = Label(ProgressbarMusicLabel, text='0:00:0', bg='red') ProgressbarMusicEndTimeLabel.grid(row=0, column=2)
class UploadItem(CanvasItem): def __init__(self, qcopyoverpc, name="<UNKNOWN>", description="<UNKNOWN>", **kw): if qcopyoverpc is None: raise ValueError("qcopyoverpc must be specified.") title = "Upload" super().__init__(qcopyoverpc.frames[-1], **kw) title_font = ("Helvetica", 20) info_font = ("Helvetica", 10) # noinspection PyProtectedMember self._id = qcopyoverpc._id self.canvass = qcopyoverpc.canvass self.names = qcopyoverpc.names self.frames = qcopyoverpc.frames self.onError: Callable[[Exception], None] = lambda exc: None self.onComplete: Callable[[], None] = lambda: None self.canvass.append(self) # canv: Canvas = self.canvass[-1] self._id[self.canvass[-1]] = {} self.title = self._id[self.canvass[-1]]["Title"] = self.canvass[-1].create_text( 10, 10, text=title, fill="#bfbfbf", anchor="nw", font=title_font) self.name = self._id[self.canvass[-1]]["Filename"] = self.canvass[-1].create_text( 10, 40, text=name, fill="#bfbfbf", anchor="nw", font=info_font) self.desc = self._id[self.canvass[-1]]["Description"] = self.canvass[-1].create_text( 10, 60, text=description, fill="#bfbfbf", anchor="nw", font=info_font) self.canvass[-1].create_rectangle(-1, 0, 790, 149, outline="#676767") self.canvass[-1].bind("<ButtonRelease-1>", lambda event, c=self.canvass[-1]: self._on_canvas_l_click(c)) # self.canvass[-1].bind("<Double-Button-1>", lambda event, n_=name: self.open_direct(n_)) self.canvass[-1].bind("<Motion>", lambda event, c=self.canvass[-1]: self._on_canvas_motion(c)) self.canvass[-1].bind("<Leave>", lambda event, c=self.canvass[-1]: self._on_canvas_leave(c)) self.progressbar = Progressbar(self.frames[-1], maximum=10, value=0) self.create_window(10, 110, window=self.progressbar, width=770, height=30, anchor="nw") self.names[self.canvass[-1]] = name def set_description(self, text: str): self.itemconfigure(self.desc, text=text) def set_title(self, text: str): self.itemconfigure(self.title, text=text) def update_progress(self, value: int): self.progressbar.config(value=value) def set_file_size(self, size: int): self.progressbar.config(maximum=size) def set_color(self, color: ColorType) -> None: """ @param color: the color """ if color == ColorType.ERROR: background = "#7f0000" text = "#bf0000" elif color == ColorType.WARNING: background = "#7f3f00" text = "#bf5f00" elif color == ColorType.INFO: background = "#00007f" text = "#0000bf" elif color == ColorType.SUCCESS: background = "#007f00" text = "#00bf00" else: background = "7f7f7f" text = "#bfbfbf" self.configure(bg=background) self.itemconfig(self.title, fill=text) self.itemconfig(self.desc, fill=text) self.itemconfig(self.name, fill=text)
cm = makeListofColorMatrix(mUpdater.getIterations()) rowsColor, colsColor = len(cm[int(slider.get() - 1)]), len( cm[int(slider.get() - 1)][0]) rect_width, rect_height = widthMap // rowsColor, heightMap // colsColor for y, row in enumerate(cm[int(slider.get() - 1)]): for x, color in enumerate(row): x0, y0 = x * rect_width, y * rect_height x1, y1 = x0 + rect_width - 1, y0 + rect_height - 1 canvas.create_rectangle(x0, y0, x1, y1, fill=color, width=0) # progress bar progress = Progressbar(root, orient=HORIZONTAL, length=100, mode='indeterminate') # Function responsible for the updation # of the progress bar value def bar(): import time progress['value'] = 20 root.update_idletasks() time.sleep(0.5) progress['value'] = 40 root.update_idletasks() time.sleep(0.5)
def run(self): # sets the initial values of things self.simCancel = False tempvalues = [] # creates a new window for the progress bar and other buttons self.progWin = tk.Toplevel(self.root) self.progWin.title("SimulationRun") self.progWin.protocol('WM_DELETE_WINDOW', self.cancel) # creates a style for the progress bar style = tk.ttk.Style() style.theme_use('default') style.configure("black.Horizontal.TProgressbar", background='black') # makes lable for the progress meter progLabel = tk.Label(self.progWin, text='Simulation Progress:') progLabel.grid(column=0, row=0, sticky='w') # makes a lable for current progress percent curProgLabel = tk.Label(self.progWin, text='0.00%') curProgLabel.grid(column=1, row=0, sticky='w') timeLabel = tk.Label(self.progWin, text='Estimated Time Remaining:') timeLabel.grid(column=0, row=2, sticky='w') timeRemain = tk.Label(self.progWin, text='HRS:MIN:SEC') timeRemain.grid(column=1, row=2, sticky='w') # makes a progress bar set to just under the size of the window bar = Progressbar(self.progWin, length=self.root.winfo_screenwidth() / 5, style='black.Horizontal.TProgressbar') bar.grid(column=0, columnspan=4, row=1, padx=10, pady=5) # Creates buttons for cancal and analyse bCancel = tk.Button(self.progWin, text='Cancel', command=self.cancel) bCancel.grid(column=1, row=3, pady=5) bAnalyse = tk.Button(self.progWin, text='Analyse', command=lambda: self.analyse(tempvalues)) bAnalyse['state'] = 'disable' bAnalyse.grid(column=0, row=3, pady=5) # updates window self.progWin.update() #gets sim number self.simNumber = self.numSim.get() # gets sim length simLen = self.simLength.get() # gets car ratios ratioNC = int(self.sbNorm.get()) ratioBB = int(self.sbBBCar.get()) ratioAC = int(self.sbAuton.get()) # validity checks for different data fields if (not self.boolNormCar.get() or ratioNC < 0): ratioNC = 0 if (not self.boolBBCar.get() or ratioBB < 0): ratioBB = 0 if (not self.boolAutoCar.get() or ratioAC < 0): ratioAC = 0 if (self.boolGraphics.get()): self.simNumber = 1 simLen = 100000 # counter for tests simiters = 0.0 # runs the tests for i in range(self.simNumber): # checks if the sim should still run if (self.simCancel == True): self.progWin.quit() messagebox.showwarning('Sim Canceled', 'Simulation has been interrupted.') return self.sim = s.simulator(self.root, self.lanes.get(), self.boolDebug.get(), self.speedLim.get(), self.boolGraphics.get(), simLen, 8, self.carsPerMin.get(), ratioNC, ratioBB, ratioAC) t0 = time.time() self.sim.start() t1 = time.time() deltaT = t1 - t0 estTime = round((self.simNumber - simiters) * deltaT, 2) sec = round(estTime % 60) min = int((estTime - sec) / 60) % 60 hr = int(estTime / 60 / 60) timeStr = '' if (hr > 0): timeStr += str(hr) + " Hours " if (min > 0): timeStr += str(min) + " Minutes " timeStr += str(sec) + " Seconds" timeRemain['text'] = str(timeStr) self.sim.collect_results() tempvalues.append(self.sim.RESULTS) simiters += 1.0 bar['value'] = round(simiters / float(self.simNumber) * 100.0, 2) if (round(simiters / float(self.simNumber) * 100.0, 2) == 100): timeRemain['text'] = 'Done' curProgLabel['text'] = str(bar['value']) + "%" self.progWin.update() bCancel['state'] = 'disable' bAnalyse['state'] = 'normal'
score = 0 lbl = Label(window, text=score, font=("Arial Bold", 100)) lbl.grid(column=1, row=9) def addToScore(): global score score += 1 lbl['text'] = score btn = Button(window, text="click", command=addToScore) btn.grid(column=1, row=10) bar = Progressbar(window, length=200) bar['value'] = 100 menu = Menu(window) new_item = Menu(menu) new_item.add_command(label='Alexs Menu') new_item.add_separator() new_item.add_command(label='Edit') menu.add_cascade(label='File', menu=new_item) window.config(menu=menu)
class control_FPGA(): def __init__(self): self.version = "V7.6" print(f"> Interfaz Sistema de Autoenfoque OpenFlexure {self.version} ") # Fecha y hora para los archivos self.timestamp = '{:%m%d-%H%M}'.format(datetime.datetime.now()) # Comprueba si se ha seleccionado el path self.flag_carpeta = False # variable auxiliar contador de número de imagenes desde que inicio la interfaz self.aux = 0 self.aux_af = 0 self.count_m1 = 0 self.count_m2 = 0 self.count_m3 = 0 #inicialización de variables self.directorio = "" self.flag_carpeta = False self.dirflag = False self.homeflag = False self.M1_is_on = True self.M2_is_on = True self.M3_is_on = True self.M_is_on = True self.DIR_is_on = True self.sobel_is_on = False self.btnHOME_is_on = True self.cap_is_on = False self.on = "ON" self.off = "OFF" self.img_enf_maximo = False # ----------------- # --- FUNCIONES --- # ----------------- # Función para determinar la carpeta de trabajo donde guardar las imagenes def carpeta_imagenes(self): self.flag_carpeta = True directorio = filedialog.askdirectory() print(f'> Ruta establecida para guardar las imágenes: {directorio}') self.dir_simples = directorio + '/IMG_Simples' os.makedirs(self.dir_simples, exist_ok=True) self.dir_autoenfoque = directorio + '/IMG_Autoenfoque' os.makedirs(self.dir_autoenfoque, exist_ok=True) self.directorio_trabajo.delete(0, tkinter.END) self.directorio_trabajo.insert(0, directorio) self.pos.config(text="Estado: Directorio seleccionado") # Función para reiniciar la interfaz def reset(self): print("> Interfaz reseteada") self.root.destroy() interfaz = control_FPGA() interfaz.createGUI() # Mueve las imágenes al directorio correspondiente def ordena_img(self, nombrebin, nombre, direccion): shutil.copy(nombrebin + '.bin', direccion) shutil.copy(nombre + '.png', direccion) os.remove(nombrebin + '.bin') os.remove(nombre + '.png') # Funcion para enviar las instrucciones a la FPGA por el puerto serie def env_serial(self, arg): global ser bin_num = arg.to_bytes(8, byteorder='big') ser.write(bin_num) if arg == 0 or arg == 255: pass else: print("- Instruccion " + str(arg) + " enviada") print("----") # Generación del archivo PGM: def bin_to_png(self, ancho, alto, nombre_bin, nombre_png): # - Se crea una array de numpy con los bytes del archivo .bin archivo_bin = nombre_bin + ".bin" arr = np.fromfile(archivo_bin, dtype=np.uint8, count=-1, sep='', offset=0) data_png = struct.pack('B' * len(arr), *[pixel for pixel in arr]) size = 320, 240 archivo_png = Image.frombuffer('L', size, data_png) archivo_png.save(nombre_png + '.png') self.imagen_interfaz = archivo_png suma = np.sum(arr) return (suma) # Función que capturar la imagen def captura_img_serie(self): if self.cap_is_on: self.cap.config(text="Activar cam") self.cap_is_on = False print("- Imagen capturada") self.env_serial(2) self.pos.config(text="Estado Inicial: Esperando instrucciones... ") else: self.cap.config(text="Capturar IMG") self.cap_is_on = True print("- Captura deshabilitada") self.env_serial(1) self.pos.config(text="Estado: Imagen capturada ") #Activa/Desactiva el filtro sobel def sobel(self): if self.sobel_is_on: self.sobel_is_on = False print("- Filtro Sobel-H OFF") self.env_serial(192) self.env_serial(0) else: self.sobel_is_on = True print("- Filtro Sobel-H ON") self.env_serial(192) self.env_serial(0) #--- # Función que manda la instrucción para iniciar el sist. de AutoEnfoque def autoenfoque(self): if self.homeflag == True: self.env_serial(5) self.env_serial(0) self.env_serial(133) self.env_serial(0) self.img = PhotoImage(file=r"./img/img_micro22.png") self.panel = Label(self.root, image=self.img) self.panel.grid(row=3, column=3, columnspan=4, rowspan=7, padx=5, pady=5) self.save_img_autofocus( ) # como no detecto cuando la FGPA termina el mov del motor y manda la siguiente foto lo hago por "software" self.img_enf_maximo = True self.pos.config(text="Estado: Ajustando a la mejor posición") self.save_img_serie() self.img_enf_maximo = False self.pos.config(text="Estado: IMANGEN ENFOCADA GUARDADA ") print("-- IMANGEN ENFOCADA GUARDADA -- ") time.sleep(0.5) self.pos.config(text="Estado: Esperando instrucciones... ") else: self.pos.config(text="Estado: Primero seleccione un directorio! ") # Guarda las imagenes en la estructura de directorios creada def save_img_serie(self): if self.flag_carpeta == True: self.root.update() self.env_serial(4) nombrebin = "IMG_BIN_" + str(self.aux) + '_' + self.timestamp if self.img_enf_maximo == False: self.pos.config(text="Estado: Guardando imagen...") nombre = "IMG_" + str(self.aux) + '_' + self.timestamp self.aux = self.aux + 1 else: self.pos.config(text="Estado: Guardando imagen enfocada...") nombre = "IMG_ENFOCADA" + str( self.aux_af) + '_' + self.timestamp self.aux_af = self.aux_af + 1 print("> Guardando imagen...") self.progress_bar.grid(row=6, column=3, columnspan=4, padx=5, pady=5) self.lee_serial(nombrebin, 320, 240) self.progress_bar.grid(row=6, column=3, columnspan=4, padx=5, pady=5) self.progress_bar.grid_forget() self.bin_to_png(320, 240, nombrebin, nombre) img_interfaz = ImageTk.PhotoImage(self.imagen_interfaz) self.panel.configure(image=img_interfaz) self.panel.image = img_interfaz print("> Imagen .PNG recibida") print("----------------------------------") x = threading.Thread(target=self.ordena_img, args=(nombrebin, nombre, self.dir_simples)) x.start() self.pos.config(text="Estado: Imagen recibida ") self.root.update() time.sleep(0.5) self.pos.config(text="Estado inicial: Esperando instrucciones... ") self.root.update() else: self.pos.config(text="Estado: Primero seleccione un directorio! ") print("! Seleccione un directorio para guardar las imágenes") # Lectura del puerto serie, para recibir la imagen def lee_serial(self, nombre_bin, ancho, alto): self.dimensiones = ancho * alto archivo_bin = nombre_bin + ".bin" fout = open(archivo_bin, 'wb') self.total_bits = 0 while self.total_bits < self.dimensiones: bytesToRead = ser.inWaiting() data = ser.read(bytesToRead) fout.write(data) self.total_bits = len(data) + self.total_bits if self.total_bits < (self.dimensiones * 1 / 5): self.barra_progreso(0) self.root.update_idletasks() elif (self.dimensiones * 1 / 5) < self.total_bits < (self.dimensiones * 2 / 5): self.barra_progreso(20) self.root.update_idletasks() elif (self.dimensiones * 2 / 5) < self.total_bits < (self.dimensiones * 3 / 5): self.barra_progreso(40) self.root.update_idletasks() elif (self.dimensiones * 3 / 5) < self.total_bits < (self.dimensiones * 4 / 5): self.barra_progreso(60) self.root.update_idletasks() elif (self.dimensiones * 4 / 5) < self.total_bits < (self.dimensiones): self.barra_progreso(80) self.root.update_idletasks() elif self.total_bits == (self.dimensiones): self.barra_progreso(100) self.root.update_idletasks() time.sleep(0.1) print("- total bits recibidos:" + str(self.total_bits)) # Función para guardar las imaágenes obtenidas en el modo AutoEnfoque def save_img_autofocus(self): if self.flag_carpeta == True: self.env_serial(4) lista_datos_enfoque = [] max_ele = 0 for i in range(0, 3): nombrebin = "IMG_BIN_AF" + str(i) + '_' + self.timestamp nombre = "IMG_AF" + str(i) + '_' + self.timestamp self.pos.config(text="Estado: proceso de autoenfoque... %s/3" % i) #-- self.lee_serial(nombrebin, 320, 240) #-- a = self.bin_to_png(320, 240, nombrebin, nombre) time.sleep(0.5) print("- Archivo procesado, PNG listo") print(str(i) + ")------------------------") print("Suma DEC:" + str(a)) print("Suma HEX:" + str(hex(a))) lista_datos_enfoque.append(a) print("----------------------------------") # mueve imgs x = threading.Thread(target=self.ordena_img( nombrebin, nombre, self.dir_autoenfoque)) x.start() for j in range(1, len(lista_datos_enfoque)): if int(lista_datos_enfoque[i]) > max_ele: max_ele = int(lista_datos_enfoque[i]) print("Lista de datos obtenidos:") print(lista_datos_enfoque) print("- Posición máximo: " + str(lista_datos_enfoque.index(max(lista_datos_enfoque))) + " - Valor: " + str(max(lista_datos_enfoque))) print("----------------------------------") time.sleep(0.2) else: self.pos.config(text="Estado: Primero seleccione un directorio! ") print("! Seleccione un directorio para guardar las imágenes") # -------- Control de los Motores ---------- def btnHOME(self): if self.btnHOME_is_on: self.pos.config( text="Estado: Colocando en posición de referencia...") self.btnHOME_is_on = False print("btn HOME on") if self.flag_carpeta == True: self.env_serial(3) self.info.configure( text= f"Posición muestra: {self.count_m1}-{self.count_m2}-{self.count_m3}" ) else: self.pos.config( text="Estado: Primero seleccione un directorio") self.homeflag = True self.M1.config(text="Ajustar") self.M2.config(text="Ajustar") self.M3.config(text="Ajustar") self.M.config(text="Ajustar") self.dir.config(text="ARRIBA") self.DIR_is_on = True else: self.pos.config(text="Estado Inicial: Esperando instrucciones... ") self.btnHOME_is_on = True print("btn HOME off") self.env_serial(0) self.homeflag = False self.count_m1 = 0 self.count_m2 = 0 self.count_m3 = 0 def switchDIR(self): if self.DIR_is_on: self.dir.config(text="ABAJO") # elimnino dir_on self.DIR_is_on = False print("Movimiento descendente") self.env_serial(128) self.env_serial(0) self.dirflag = False else: self.dir.config(text="ARRIBA") self.DIR_is_on = True print("Movimiento ascendente") self.env_serial(128) self.env_serial(0) self.dirflag = True def switchM1(self): if self.homeflag == False: if self.M1_is_on: self.M1.config(text=self.on) self.M1_is_on = False print("Motor1 on") self.env_serial(129) self.env_serial(0) else: self.M1.config(text=self.off) self.M1_is_on = True print("Motor1 off") self.env_serial(129) self.env_serial(0) else: self.M1.config(text="Ajustar") self.M1_is_on = False print("Motor1 pulsado") self.env_serial(129) self.env_serial(0) if self.dirflag == True: self.count_m1 = self.count_m1 + 1 elif self.dirflag == False: if self.count_m1 == 0: self.count_m1 = self.count_m1 else: self.count_m1 = self.count_m1 - 1 self.pos.config(text="Estado: Ajuste pre-autoenfoque") self.info.configure( text= f"Posición muestra: {self.count_m1}-{self.count_m2}-{self.count_m3}" ) self.root.update() def switchM2(self): if self.homeflag == False: if self.M2_is_on: self.M2.config(text=self.on) self.M2_is_on = False print("Motor2 on") self.env_serial(130) self.env_serial(0) # 255 else: self.M2.config(text=self.off) self.M2_is_on = True print("Motor2 off") self.env_serial(130) self.env_serial(0) else: self.M2.config(text="Ajustar") self.M2_is_on = False print("Motor2 pulsado") self.env_serial(130) self.env_serial(0) if self.dirflag == True: self.count_m2 = self.count_m2 + 1 elif self.dirflag == False: if self.count_m2 == 0: self.count_m2 = self.count_m2 else: self.count_m2 = self.count_m2 - 1 self.pos.config(text="Estado: Ajuste pre-autoenfoque") self.info.configure( text= f"Posición muestra: {self.count_m1}-{self.count_m2}-{self.count_m3}" ) self.root.update() def switchM3(self): if self.homeflag == False: if self.M3_is_on: self.M3.config(text=self.on) self.M3_is_on = False print("Motor3 on") self.env_serial(131) self.env_serial(0) else: self.M3.config(text=self.off) self.M3_is_on = True print("Motor3 off") self.env_serial(131) self.env_serial(0) else: self.M3.config(text="Ajustar") self.M3_is_on = False print("Motor2 pulsado") self.env_serial(131) self.env_serial(0) if self.dirflag == True: self.count_m3 = self.count_m3 + 1 elif self.dirflag == False: if self.count_m3 == 0: self.count_m3 = self.count_m3 else: self.count_m3 = self.count_m3 - 1 self.pos.config(text="Estado: Ajuste pre-autoenfoque") self.info.configure( text= f"Posición muestra: {self.count_m1}-{self.count_m2}-{self.count_m3}" ) self.root.update() def switchM(self): if self.homeflag == False: if self.M_is_on: self.M.config(text=self.on) self.M1.config(text=self.on) self.M2.config(text=self.on) self.M3.config(text=self.on) self.M_is_on = False self.M1_is_on = False self.M2_is_on = False self.M3_is_on = False print("All Motor on") self.env_serial(132) self.env_serial(0) else: self.M.config(text=self.off) self.M1.config(text=self.off) self.M2.config(text=self.off) self.M3.config(text=self.off) self.M_is_on = True self.M1_is_on = True self.M2_is_on = True self.M3_is_on = True print("All Motor off") self.env_serial(132) self.env_serial(0) else: self.M.config(text="Ajustar") self.M1.config(text="Ajustar") self.M2.config(text="Ajustar") self.M3.config(text="Ajustar") self.M_is_on = False self.M1_is_on = False self.M2_is_on = False self.M3_is_on = False print("All Motor on") self.env_serial(132) self.env_serial(0) if self.dirflag == True: self.count_m1 = self.count_m1 + 1 self.count_m2 = self.count_m2 + 1 self.count_m3 = self.count_m3 + 1 elif self.dirflag == False: if self.count_m1 == 0: self.count_m1 = self.count_m1 else: self.count_m1 = self.count_m1 - 1 if self.count_m2 == 0: self.count_m2 = self.count_m2 else: self.count_m2 = self.count_m2 - 1 if self.count_m3 == 0: self.count_m3 = self.count_m3 else: self.count_m3 = self.count_m3 - 1 self.pos.config(text="Estado: Ajuste pre-autoenfoque") self.info.configure( text= f"Posición muestra: {self.count_m1}-{self.count_m2}-{self.count_m3}" ) self.root.update() # ---------------------------INTERFAZ---------------------------------------------- def createGUI(self): self.root = Tk() self.root.resizable(width=False, height=False) self.color_fondo = "#FFFFFF" self.root['background'] = self.color_fondo #canvas.create_image(0,0,image=bg, anchor="nw") #self.root.geometry("523x502") # titulo de ventana - icono self.root.title('- FPGA - Interfaz de control del microscopio') self.root.iconbitmap('./img/logo.ico') # Define el directorio de trabajo: selectdir = Button(self.root, text="Path", font=("Helvetica", 8), command=lambda: self.carpeta_imagenes()) selectdir.grid(row=0, column=1, sticky=E, padx=5, pady=10) self.carpeta_trabajo = Entry(self.root, width=50, text="Seleccionar carpeta", font=("Calibri Light", 10)) self.carpeta_trabajo.grid(row=0, column=2, columnspan=3, sticky=W, padx=5, pady=10) self.carpeta_trabajo.insert( 0, "Seleccione un directorio para guardar las imágenes") self.directorio_trabajo = self.carpeta_trabajo # Etiqueta que define la posición de la muestra self.pos = Label(self.root, text="Estado inicial: Esperando instrucciones... ", font=('Calibri Light', 11), bg=self.color_fondo) self.pos.grid(row=1, column=1, sticky=W + E, padx=10, pady=10, columnspan=15) # Etiqueta que define el estado en el que se encuentra trabajando el microscopio self.info = Label(self.root, text="Posición muestra: %-%-%", font=('Calibri Light', 9), bg=self.color_fondo) self.info.grid(row=3, column=1, sticky=W + E, padx=10, pady=0, columnspan=2) # Botón que inicia el movimiento del microscopio, desplazandose al punto de referencia self.btn_home = Button(self.root, text="HOME", font=("Helvetica", 9), bg=None, command=lambda: self.btnHOME()) self.btn_home.grid(row=2, column=2, sticky=E, pady=10) # Botón que inicia el proceso de AUTOENFOQUE self.btn_focus = Button(self.root, text="AUTOENFOQUE", font=("Helvetica", 9), bg=None, command=lambda: self.autoenfoque()) self.btn_focus.grid(row=2, column=3, pady=10) # Botón que activa el filtro SOBEL self.btn_sobel = Button(self.root, text="SOBEL", font=("Helvetica", 9), bg=None, command=lambda: self.sobel()) self.btn_sobel.grid(row=2, column=4, sticky=W, pady=10) # Botones de control de los motores: self.M1 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M1.grid(row=4, column=2, sticky=W, pady=2) self.btnM1 = Button(self.root, text="Motor M1", font=("Calibri Light", 10), command=lambda: self.switchM1()) self.btnM1.grid(row=4, column=1, sticky=E, pady=2) self.M2 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M2.grid(row=5, column=2, sticky=W, pady=2) self.btnM2 = Button(self.root, text="Motor M2", font=("Calibri Light", 10), command=lambda: self.switchM2()) self.btnM2.grid(row=5, column=1, sticky=E, pady=2) self.M3 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M3.grid(row=6, column=2, sticky=W, pady=2) self.btnM3 = Button(self.root, text="Motor M3", font=("Calibri Light", 10), command=lambda: self.switchM3()) self.btnM3.grid(row=6, column=1, sticky=E, pady=2) self.M = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M.grid(row=7, column=2, sticky=W, pady=4) self.btnM = Button(self.root, text="Todos", font=("Calibri Light", 10), command=lambda: self.switchM()) self.btnM.grid(row=7, column=1, sticky=E, pady=2) # Botón que define la dirección de los motores self.dir = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.dir.grid(row=9, column=2, sticky=W, pady=5) self.btnDIR = Button(self.root, text="Dirección", font=("Calibri Light", 10), command=lambda: self.switchDIR()) self.btnDIR.grid(row=9, column=1, sticky=E, pady=2) # Botón que captura la imagen self.cap = Button(self.root, text="Capturar IMG", bg=None, command=lambda: self.captura_img_serie()) self.cap.grid(row=10, column=3, sticky=E, padx=5, pady=5) # Botón para obtener la imagen de la FPGA self.recibir_img = Button(self.root, text="Guardar IMG", bg=None, command=lambda: self.save_img_serie()) self.recibir_img.grid(row=10, column=4, sticky=W, padx=5, pady=5) #Versión del código ejecutado self.version = Label(self.root, text=self.version) self.version.grid(row=12, column=1, sticky=W, pady=2) # Define la imagen obtenida de la FPGA self.img = PhotoImage(file=r"./img/img_micro22.png") #self.img1 = self.img.subsample(1, 1) self.panel = Label(self.root, image=self.img) self.panel.grid(row=3, column=3, columnspan=4, rowspan=7, padx=5, pady=5) # Barra de progreso # - para cambiar el estilo de la barra #self.style = ttk.Style() #self.style.theme_use('alt') #self.style.configure("green.Horizontal.TProgressbar", foreground='green', background='green') #ttk.Progressbar(self.root, style="green.Horizontal.TProgressbar", mode='determinate', maximum=4, value=2) self.progress_bar = Progressbar(self.root, orient=HORIZONTAL, length=160, mode='determinate') self.progress_bar.grid(row=6, column=3, columnspan=4, padx=5, pady=5) self.progress_bar.grid_forget() # ---MENU --- menubar = Menu(self.root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Instrucciones", command=self.instrucciones) filemenu.add_command(label="Esquema FPGA", command=self.esquema) filemenu.add_command(label="About", command=self.about) filemenu.add_command(label="Reset", command=self.reset) filemenu.add_command(label="Exit", command=self.root.quit) configmenu = Menu(menubar, tearoff=0) configmenu.add_command(label="Filtro Sobel-H", command=self.sobel) configmenu.add_command(label="Exit", command=self.root.quit) # filemenu.add_separator() menubar.add_cascade(label="Menu", menu=filemenu) menubar.add_cascade(label="Configuración", menu=configmenu) # configuracion self.root.config(menu=menubar) # background = '#1A1A1A') self.root.mainloop() # ---------------------------INFORMACIÓN------------------------------------------- def barra_progreso(self, valor): self.progress_bar['value'] = int(valor) self.root.update_idletasks() def about(self): toplevel = tkinter.Toplevel(self.root) label0 = tkinter.Label(toplevel, text="\n Interfaz de control FPGA", font=("Helvetica", 9, "bold")) label0.grid(row=0, column=1, padx=1, sticky="s") label1 = ttk.Label( toplevel, text="\n Esta trabajo forma parte del TFM : " "\n " "\n SISTEMA DE AUTOENFOQUE MEDIANTE FPGA PARA MICROSCOPIO DE BAJO " "\n COSTE Y HARDWARE LIBRE CON POSICIONAMIENTO DE BISAGRAS FLEXIBLES " "\n " "\n La interfaz permite el control del sistema de posicionamiento, la obtención " "\n de imágenes y un proceso de enfoque automático desarrollado en FPGA. " "\n " "\n Toda la información del proyecto se encuentra disponible en: " "\n https://github.com/URJCMakerGroup/Autofocus_Delta_Stage " "\n ") label1.grid(row=1, column=1, padx=1, sticky="s") close_btn = ttk.Button(toplevel, text=" ok ", command=toplevel.destroy) close_btn.grid(row=2, column=1) label2 = ttk.Label(toplevel, text=" ") label2.grid(row=3, column=1, padx=1, sticky="s") def esquema(self): x = threading.Thread(target=self.info_esquema, args=()) x.start() def info_esquema(self): img = cv2.imread(r"./img/esquema.png", cv2.IMREAD_COLOR) cv2.imshow("Esquema control FPGA", img) cv2.waitKey(0) cv2.destroyAllWindows() def instrucciones(self): toplevel = tkinter.Toplevel(self.root) label0 = tkinter.Label(toplevel, text="\n Instrucciones de uso:", font=("Helvetica", 9, "bold")) label0.grid(row=0, column=1, padx=1, sticky="s") label1 = ttk.Label( toplevel, text= "\n La interfaz permite el control de los motores para el ajuste de la muestra. " "\n " "\n En primer lugar es preciso definir un directorio de trabajo pulsando el" "\n botón path. A partir de ahí se puede controlar los diferentes motores y" "\n su dirección, capturar imágenes o guardarlas en PNG el path seleccionado." "\n " "\n - El botón HOME, fija el sistema de posicionamiento en el lugar de referencia" "\n Una vez en la posición de referencia se puede realizar el autoenfoque." "\n " "\n - El botón SOBEL, aplica ese filtro a la imagen (de forma horizontal) " "\n " "\n - El botón AUTOENFOQUE, inicia el proceso para obtener la imagen mejor enfocada " "\n ") label1.grid(row=1, column=1, padx=1, sticky="s") close_btn = ttk.Button(toplevel, text=" ok ", command=toplevel.destroy) close_btn.grid(row=2, column=1) label2 = ttk.Label(toplevel, text=" ") label2.grid(row=3, column=1, padx=1, sticky="s")
def depart(self): self.frame1 = Frame(self.root, width=600, bg='#FFFFFF') self.frame1.grid(row=0, column=0, ipady=10, ipadx=10) self.frame1.grid_columnconfigure(0, weight=2) self.vfichier1 = StringVar() self.vfichier2 = StringVar() self.vproject = StringVar() self.vfichier1.set('') self.vfichier2.set('') self.vproject.set('') self.chemin = '' self.chemin1 = '' self.button1 = Button(self.frame1, text="Import weekly reporting", command=self.set_fichier1, width=50, height=2, bg='#66B239') self.button1.grid(row=0, column=0, pady=5) self.button2 = Button(self.frame1, text='Import SSR dashboard', command=self.set_fichier2, width=50, height=2, bg='#66B239') self.button2.grid(row=2, column=0, pady=5) self.vname_g = StringVar() self.vfilter_name = StringVar() self.vremarque = StringVar() self.vremarque.set("") self.vfilter_name.set('') self.bpetit_tab = Button(self.frame1, text='Import part list', command=self.set_filter, width=50, height=2, bg='#66B239') self.bpetit_tab.grid(row=4, column=0, pady=5) self.bProject = Button(self.frame1, text='Import Hard points list', command=self.set_project, width=50, height=2, bg='#66B239') self.bProject.grid(row=3, column=0, pady=5) self.bpetit_emp = Button(self.frame1, text="Generate report", command=self.set_emplacement, width=50, height=2, bg='#66B239') self.bpetit_emp.grid(row=5, column=0, pady=5) self.lremarque = Label(self.frame1, textvariable=self.vremarque, relief=GROOVE, bg='#CAE21E', font=('arial', 10), border='2px', wraplength=550) self.progress_bar = Progressbar(self.frame1, orient='horizontal', length=286, mode='determinate')
def createGUI(self): self.root = Tk() self.root.resizable(width=False, height=False) self.color_fondo = "#FFFFFF" self.root['background'] = self.color_fondo #canvas.create_image(0,0,image=bg, anchor="nw") #self.root.geometry("523x502") # titulo de ventana - icono self.root.title('- FPGA - Interfaz de control del microscopio') self.root.iconbitmap('./img/logo.ico') # Define el directorio de trabajo: selectdir = Button(self.root, text="Path", font=("Helvetica", 8), command=lambda: self.carpeta_imagenes()) selectdir.grid(row=0, column=1, sticky=E, padx=5, pady=10) self.carpeta_trabajo = Entry(self.root, width=50, text="Seleccionar carpeta", font=("Calibri Light", 10)) self.carpeta_trabajo.grid(row=0, column=2, columnspan=3, sticky=W, padx=5, pady=10) self.carpeta_trabajo.insert( 0, "Seleccione un directorio para guardar las imágenes") self.directorio_trabajo = self.carpeta_trabajo # Etiqueta que define la posición de la muestra self.pos = Label(self.root, text="Estado inicial: Esperando instrucciones... ", font=('Calibri Light', 11), bg=self.color_fondo) self.pos.grid(row=1, column=1, sticky=W + E, padx=10, pady=10, columnspan=15) # Etiqueta que define el estado en el que se encuentra trabajando el microscopio self.info = Label(self.root, text="Posición muestra: %-%-%", font=('Calibri Light', 9), bg=self.color_fondo) self.info.grid(row=3, column=1, sticky=W + E, padx=10, pady=0, columnspan=2) # Botón que inicia el movimiento del microscopio, desplazandose al punto de referencia self.btn_home = Button(self.root, text="HOME", font=("Helvetica", 9), bg=None, command=lambda: self.btnHOME()) self.btn_home.grid(row=2, column=2, sticky=E, pady=10) # Botón que inicia el proceso de AUTOENFOQUE self.btn_focus = Button(self.root, text="AUTOENFOQUE", font=("Helvetica", 9), bg=None, command=lambda: self.autoenfoque()) self.btn_focus.grid(row=2, column=3, pady=10) # Botón que activa el filtro SOBEL self.btn_sobel = Button(self.root, text="SOBEL", font=("Helvetica", 9), bg=None, command=lambda: self.sobel()) self.btn_sobel.grid(row=2, column=4, sticky=W, pady=10) # Botones de control de los motores: self.M1 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M1.grid(row=4, column=2, sticky=W, pady=2) self.btnM1 = Button(self.root, text="Motor M1", font=("Calibri Light", 10), command=lambda: self.switchM1()) self.btnM1.grid(row=4, column=1, sticky=E, pady=2) self.M2 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M2.grid(row=5, column=2, sticky=W, pady=2) self.btnM2 = Button(self.root, text="Motor M2", font=("Calibri Light", 10), command=lambda: self.switchM2()) self.btnM2.grid(row=5, column=1, sticky=E, pady=2) self.M3 = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M3.grid(row=6, column=2, sticky=W, pady=2) self.btnM3 = Button(self.root, text="Motor M3", font=("Calibri Light", 10), command=lambda: self.switchM3()) self.btnM3.grid(row=6, column=1, sticky=E, pady=2) self.M = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.M.grid(row=7, column=2, sticky=W, pady=4) self.btnM = Button(self.root, text="Todos", font=("Calibri Light", 10), command=lambda: self.switchM()) self.btnM.grid(row=7, column=1, sticky=E, pady=2) # Botón que define la dirección de los motores self.dir = Label(self.root, text="Estado", font=("Calibri Light", 10), bg=self.color_fondo) self.dir.grid(row=9, column=2, sticky=W, pady=5) self.btnDIR = Button(self.root, text="Dirección", font=("Calibri Light", 10), command=lambda: self.switchDIR()) self.btnDIR.grid(row=9, column=1, sticky=E, pady=2) # Botón que captura la imagen self.cap = Button(self.root, text="Capturar IMG", bg=None, command=lambda: self.captura_img_serie()) self.cap.grid(row=10, column=3, sticky=E, padx=5, pady=5) # Botón para obtener la imagen de la FPGA self.recibir_img = Button(self.root, text="Guardar IMG", bg=None, command=lambda: self.save_img_serie()) self.recibir_img.grid(row=10, column=4, sticky=W, padx=5, pady=5) #Versión del código ejecutado self.version = Label(self.root, text=self.version) self.version.grid(row=12, column=1, sticky=W, pady=2) # Define la imagen obtenida de la FPGA self.img = PhotoImage(file=r"./img/img_micro22.png") #self.img1 = self.img.subsample(1, 1) self.panel = Label(self.root, image=self.img) self.panel.grid(row=3, column=3, columnspan=4, rowspan=7, padx=5, pady=5) # Barra de progreso # - para cambiar el estilo de la barra #self.style = ttk.Style() #self.style.theme_use('alt') #self.style.configure("green.Horizontal.TProgressbar", foreground='green', background='green') #ttk.Progressbar(self.root, style="green.Horizontal.TProgressbar", mode='determinate', maximum=4, value=2) self.progress_bar = Progressbar(self.root, orient=HORIZONTAL, length=160, mode='determinate') self.progress_bar.grid(row=6, column=3, columnspan=4, padx=5, pady=5) self.progress_bar.grid_forget() # ---MENU --- menubar = Menu(self.root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Instrucciones", command=self.instrucciones) filemenu.add_command(label="Esquema FPGA", command=self.esquema) filemenu.add_command(label="About", command=self.about) filemenu.add_command(label="Reset", command=self.reset) filemenu.add_command(label="Exit", command=self.root.quit) configmenu = Menu(menubar, tearoff=0) configmenu.add_command(label="Filtro Sobel-H", command=self.sobel) configmenu.add_command(label="Exit", command=self.root.quit) # filemenu.add_separator() menubar.add_cascade(label="Menu", menu=filemenu) menubar.add_cascade(label="Configuración", menu=configmenu) # configuracion self.root.config(menu=menubar) # background = '#1A1A1A') self.root.mainloop()
def __init__(self, master, result_row): self.master = master self.result_row = result_row master.resizable(0, 0) self.center(win_w=1020, win_h=760) master.title("ZILLOW SCRAPER") # create a menu menu = Menu(master) master.config(menu=menu) helpmenu = Menu(menu, tearoff=0) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.callback_about) title_comment_frame = Frame(master) title_comment_frame.place(x=200, y=20) title_txt = 'ZILLOW SCRAPER' title_lbl = Label(title_comment_frame, text=title_txt, font=('Comic Sans MS bold', 15), fg='#60A644', width=50) title_lbl.pack(side=TOP, anchor=CENTER, padx=10, pady=10) file_comment_frame = Frame(master) file_comment_frame.place(x=10, y=80) file_comment = 'To use the tool browse for the import file (csv or excel)' comment_lbl = Label(file_comment_frame, text=file_comment, font=('Calibri bold', 12), fg='#60A644') comment_lbl.pack(side=TOP, anchor=W, padx=10, pady=10) image = Image.open('resources/UrbanXHome-Logo.png').convert("RGBA") image = image.resize((130, 80), Image.ANTIALIAS) photo = ImageTk.PhotoImage(image) label = Label(master, image=photo) label.image = photo # keep a reference! # label.place(x=15, y=320) label.place(x=795, y=10) file_path_frame = Frame(master) file_path_frame.place(x=10, y=200) file_path_frame = Frame(master) file_path_frame.place(x=10, y=110) file_path_txt = 'File path:' file_path_lbl = Label(file_path_frame, text=file_path_txt, font=('Calibri', 12), fg='black') file_path_lbl.config(height=2) file_path_lbl.pack(side=LEFT, anchor=CENTER, padx=10, pady=50) self.path = StringVar() self.path.trace( "w", lambda name, index, mode, sv=self.path: self.get_filename(sv)) file_path_entry = Entry(file_path_frame, textvariable=self.path, relief=FLAT, highlightbackground='black', highlightthickness=1) file_path_entry.focus_set() file_path_entry.config(width=110) file_path_entry.pack(side=LEFT, anchor=CENTER, padx=10, pady=50) browse_btn = Button(file_path_frame, text='BROWSE', font=('Calibri bold', 12), bg='#60A644', fg='white', command=self.browse_click) browse_btn.config(width=18, height=1) browse_btn.pack(side=LEFT, anchor=CENTER, padx=20, pady=50) # browse_btn.bind("<Button-1>", self.browse_click) self.status_txt = StringVar() status_lbl = Label(master, textvariable=self.status_txt, font=('Calibri bold', 15), fg='#60A644') status_lbl.config(width=40, height=1) status_lbl.place(x=300, y=235) self.status_txt.set("There are no Zillow lines.") import_bnt = Button(master, text='IMPORT', font=('Calibri bold', 12), bg='#0F75BD', fg='white', command=self.import_click) import_bnt.config(width=18, height=1) import_bnt.place(x=450, y=290) # import_bnt.bind("<Button-1>", self.import_click) assessor_bnt = Button(master, text='GET ZILLOW DATA', font=('Calibri bold', 12), bg='#60A644', fg='white', command=self.assessor_click) assessor_bnt.config(width=18, height=1) assessor_bnt.place(x=450, y=360) # assessor_bnt.bind("<Button-1>", self.assessor_click) progress_frame = Frame(master) progress_frame.place(x=60, y=415) self.prog_ratio_txt = StringVar() prog_ratio_lbl = Label(progress_frame, textvariable=self.prog_ratio_txt, font=('Calibri bold', 12), fg='#60A644') prog_ratio_lbl.pack(side=TOP, anchor=CENTER, padx=0) prog_ratio_lbl.config(width=20) self.progress = Progressbar(progress_frame, orient=HORIZONTAL, length=850, mode='determinate') self.progress.pack(side=LEFT, anchor=CENTER, padx=20) self.prog_percent_txt = StringVar() prog_percent_lbl = Label(progress_frame, textvariable=self.prog_percent_txt, font=('Calibri bold', 12), fg='#60A644') prog_percent_lbl.pack(side=RIGHT, anchor=CENTER, padx=0) table_frame = Frame(master) table_frame.place(x=18, y=500) yscrollbar = Scrollbar(table_frame, orient=VERTICAL) yscrollbar.pack(side=RIGHT, fill=Y) xscrollbar = Scrollbar(table_frame, orient=HORIZONTAL) xscrollbar.pack(side=BOTTOM, fill=X) self.listbox = Listbox(table_frame, width=160, height=14) self.listbox.pack() # attach listbox to scrollbar self.listbox.config(yscrollcommand=yscrollbar.set) self.listbox.config(xscrollcommand=xscrollbar.set) yscrollbar.config(command=self.listbox.yview) xscrollbar.config(command=self.listbox.xview) self.listbox_rows_cnt = 0 self.zillow_lines = [] self.running = 0
class GUIDuple(object): PHOTO_SAVE_COLOR = '#70d067' PHOTO_DELETE_COLOR = '#e3464e' COLOR_FRAMES1 = '#ececec' COLOR_FRAMES2 = '#999' COLOR_FRAMES3 = '#ccc' def __init__(self): self.results = {} self.num_photos_to_delete = 0 self.root = Tk() self.root.title('Duplicates finder') self.root.attributes('-fullscreen', True) # create all of the main containers self.frame_header1 = Frame(self.root, padx=15, pady=5, bg=self.COLOR_FRAMES1) self.frame_header2 = Frame(self.root, padx=15, pady=5, bg=self.COLOR_FRAMES1) self.frame_center = Frame(self.root) self.frame_bottom = Frame(self.root, padx=15, pady=15, bg=self.COLOR_FRAMES1) # layout all of the main containers self.root.grid_rowconfigure(2, weight=1) self.root.grid_columnconfigure(0, weight=1) self.frame_header1.grid(row=0, sticky="ew") self.frame_header2.grid(row=1, sticky="ew") self.frame_center.grid(row=2, sticky="nsew") self.frame_bottom.grid(row=3, sticky="ew") # widgets frame_header1 self.frame_header1.grid_columnconfigure(1, weight=1) self.label_title = Label(self.frame_header1, text='DUPLICATES FINDER', font="-weight bold", bg=self.COLOR_FRAMES1) self.label_title.grid(row=0, column=0) self.folder_path = StringVar() self.label_folder = Entry(self.frame_header1, state='disabled', width=40, textvariable=self.folder_path, highlightbackground=self.COLOR_FRAMES1) self.label_folder.grid(row=0, column=2) self.btn_browse_folder = Button(self.frame_header1, text="Choose folder", command=self.action_browse, highlightbackground=self.COLOR_FRAMES1) self.btn_browse_folder.grid(row=0, column=3, padx=(5, 50)) self.btn_scan = Button(self.frame_header1, text="Scan", command=self.action_scan, state='disabled', highlightbackground=self.COLOR_FRAMES1) self.btn_scan.grid(row=0, column=4) # widgets frame_header1 self.prgs_bar = Progressbar(self.frame_header2) self.prgs_bar.grid(row=0, column=0) self.prgs_bar.pack(expand=True, fill='both') # widgets frame_bottom self.frame_bottom.grid_columnconfigure(2, weight=1) self.label_delete_num = Label(self.frame_bottom, text='0', bg=self.COLOR_FRAMES1) self.label_delete_num.grid(row=0, column=0) self.label_delete_str = Label(self.frame_bottom, text='photos to delete', bg=self.COLOR_FRAMES1) self.label_delete_str.grid(row=0, column=1) self.btn_delete_photos = Button(self.frame_bottom, text="Delete photos", state=DISABLED, command=self.action_delete, highlightbackground=self.COLOR_FRAMES1) self.btn_delete_photos.grid(row=0, column=3) # frames frame_center self.frame_center.grid_columnconfigure(1, weight=1) self.frame_center.grid_rowconfigure(0, weight=1) self.frame_center1 = Frame(self.frame_center, bg=self.COLOR_FRAMES2, padx=15, pady=5) self.frame_center1.grid(row=0, column=0) self.frame_center1.grid(row=0, sticky="nsew") self.frame_center2 = Frame(self.frame_center, pady=15, bg=self.COLOR_FRAMES3) self.frame_center2.grid(row=0, column=1) self.frame_center2.grid(row=0, sticky="nsew") # widgets frame_center1 self.frame_center1.grid_rowconfigure(1, weight=1) self.label_list = Label(self.frame_center1, text="Duplicates", bg=self.COLOR_FRAMES2) self.label_list.grid(row=0, column=0) self.lb_ids = [] self.lb = Listbox(self.frame_center1, font=("Courier", 12), height=600) self.lb.grid(row=1, column=0) self.lb.bind('<<ListboxSelect>>', self.onselect) self.lb.bind('1', self.toggle_photo_key) self.lb.bind('2', self.toggle_photo_key) self.lb.bind('3', self.toggle_photo_key) self.lb.bind('4', self.toggle_photo_key) self.lb.bind('5', self.toggle_photo_key) self.lb.bind('6', self.toggle_photo_key) self.lb.bind('7', self.toggle_photo_key) self.lb.bind('8', self.toggle_photo_key) self.lb.bind('9', self.toggle_photo_key) self.labels_memory = [] self.labels_img_memory = [] def toggle_photo_key(self, evt): position = int(evt.keysym) - 1 self.toggle_photo(position) def toggle_photo(self, position): # Update object photo photo_obj = self.results[self.lb_ids[self.lb.curselection()[0]]][position] photo_obj.delete = not photo_obj.delete # Update label photo if photo_obj.delete: bg_color = self.PHOTO_DELETE_COLOR self.update_num_photos_to_delete(self.num_photos_to_delete + 1) else: bg_color = self.PHOTO_SAVE_COLOR self.update_num_photos_to_delete(self.num_photos_to_delete - 1) self.labels_memory[position][0].config(bg=bg_color) def update_num_photos_to_delete(self, num): self.num_photos_to_delete = num if self.num_photos_to_delete < 1: self.btn_delete_photos.config(state='disabled') else: self.btn_delete_photos.config(state='normal') self.label_delete_num.config(text=str(self.num_photos_to_delete)) def update(self, outqueue): try: msg = outqueue.get_nowait() if isinstance(msg, list): print('SCAN FINISHED') self.update_num_photos_to_delete(msg[0]) self.results = msg[1] for i, r in self.results.items(): self.lb_ids.append(i) self.lb.insert(END, str(i)[:8] + ' (%d)' % len(r)) self.btn_browse_folder.config(state='normal') self.btn_scan.config(state='normal') self.btn_delete_photos.config(state='normal') self.prgs_bar['value'] = 0 if self.results: self.lb.select_set(0) self.lb.event_generate('<<ListboxSelect>>') self.lb.focus_set() else: messagebox.showinfo("Duplicate finder", "No duplicates found!") else: self.prgs_bar['value'] = msg * 100 self.root.after(100, self.update, outqueue) except queue.Empty: self.root.after(100, self.update, outqueue) def action_browse(self): # Allow user to select a directory and store it in global var # called folder_path filename = filedialog.askdirectory() self.folder_path.set(filename) if filename: self.btn_scan.config(state='normal') print(filename) def clear_photos(self): for labels_obj in self.labels_memory: for label in labels_obj: label.destroy() def action_scan(self): self.btn_browse_folder.config(state='disabled') self.btn_scan.config(state='disabled') self.lb.delete(0,'end') self.clear_photos() self.outqueue = queue.Queue() thr = threading.Thread(target=SimilarImagesFinder().find_similar_images, args=(self.folder_path.get(), self.outqueue)) thr.start() self.root.after(250, self.update, self.outqueue) def img_click(self, evt): position = int(evt.widget.grid_info()["column"]) self.toggle_photo(position) def onselect(self, evt): w = evt.widget index = int(w.curselection()[0]) value = w.get(index) # delete old labels self.clear_photos() self.labels_memory = [] self.labels_img_memory = [] # calculate widths frame_width = self.frame_center2.winfo_width() grid_width = frame_width/len(self.results[self.lb_ids[index]]) photo_with = grid_width - 40 count = 0 for photo in self.results[self.lb_ids[index]]: self.frame_center2.grid_columnconfigure(count, minsize=grid_width) img = Image.open(photo.path) img.thumbnail((photo_with, photo_with)) render = ImageTk.PhotoImage(img) self.labels_img_memory.append(render) photo_border_color = self.PHOTO_DELETE_COLOR if photo.delete else self.PHOTO_SAVE_COLOR label_img = Label(self.frame_center2, image=self.labels_img_memory[count], borderwidth=10, bg=photo_border_color) label_img.grid(row=4, column=count) label_img.bind("<Button-1>", self.img_click) label_text = Label(self.frame_center2, anchor=N, font="TkDefaultFont 20 bold", text=photo.size_text) label_text.grid(row=5, column=count) label_text2 = Label(self.frame_center2, anchor=N, text=photo.name) label_text2.grid(row=6, column=count) self.labels_memory += [[label_img, label_text, label_text2]] count += 1 def action_delete(self): result = messagebox.askquestion("Delete", "Are You Sure you want to delete %d photos?" % self.num_photos_to_delete, icon='warning') if result == 'yes': for _, photos in self.results.items(): for photo_obj in photos: if photo_obj.delete: os.remove(photo_obj.path) self.results = {} self.update_num_photos_to_delete(0) self.lb.delete(0,'end') self.clear_photos() def run(self): mainloop()
def func_main(datafolder): print("Starte Aufgabendownload") main = Tk() main.geometry("300x100") main.title("Herunterladen...") #Add window elements progress = Progressbar(main, orient="horizontal", length=300, mode="determinate") progress["value"]=0 progress.grid(row=0, column=0) status = Label(main, font='Helvetica 11 bold', padding=4, text="Statusanzeige") status.grid(row=1, column=0) download = Label(main, font='Helvetica 11', padding=4, text="") download.grid(row=2, column=0) main.update() #Manually update the window since mainloop() cannot be used #Read user data from user.data datafolder = os.path.join(datafolder, "") usrdata = open(os.path.join(datafolder, "user.data")).read() server = usrdata.split("server:")[1].split(";")[0] username = usrdata.split("username:"******";")[0] password = usrdata.split("password:"******";")[0] taskfilter = usrdata.split("taskfilter:")[1].split(";")[0] if password == "[none]": password = popup.func_main(5) url1 = "<td class=\"iserv-admin-list-field iserv-admin-list-field-textarea\"><a href=\"" url2 = "\">" name = "</a></td>" oldtasks = "" tasks = [] newtasks = [] title = "" start = "" end = "" url = "" files = 0 filenames = [] filelinks = [] json = [] taskname1 = "<h1>Details zu " taskname2 = "</h1>" taskstart = "<th>Starttermin:</th>" taskend = "<th>Abgabetermin:</th>" textstart = "<div class=\"text-break-word p-3\">" textend = "</div>" fileurl = "/iserv/fs/file/exercise-dl/" file1 = "<a href=\"" date1 = "<td>" date2 = "</td>" att1 = "<form name=\"iserv_exercise_attachment\"" att2 = "</form>" fileend1 = "<span class=\"text-muted\">" fileend2 = "</a>" headers = {'User-Agent': 'Mozilla/5.0'} #User-Agent (Browser) festlegen credits = {'_username': username, '_password': password} #Login-Daten festlegen #Connect to IServ status["text"] = "Verbinde zu IServ..." main.update() print("Verbinde zu IServ...") session = requests.Session() session.post('https://' + server + '/iserv/login_check', headers=headers, data=credits) #Download list of tasks status["text"] = "Aufgabenliste wird geladen..." main.update() print("Aufgabenliste wird geladen...") html = session.get("https://" + server + "/iserv/exercise?filter[status]=" + taskfilter).text #Extract Links from the downloaded html file i = int(len(html.split(url1))-1) searchtml = html #Index links in an array for ii in range(i): tasks.append(searchtml.split(url1)[1].split(url2)[0]) #Attach link to the list of all tasks newtasks.append(searchtml.split(url1)[1].split(url2)[0]) #Add link to the list of new tasks (if the task is not new, the link will be removed later). searchtml = html.split(name)[ii+1] #Limit HTML to be searched so that the same link is not indexed again #Check, which tasks are new and which have already been downloaded try: oldtasks = open(datafolder + "tasks.json", "r").read() #Read list of tasks that already have been downloaded for i in range(len(tasks)): if oldtasks.find(tasks[i]) != -1: #If an entry in the downloaded tasks matches an extry in the list of old tasks, that entry will be removed newtasks.remove(tasks[i]) except: #If the program is started for the first time, an error occures. At this point, this is normal. with open(datafolder + "tasks.json", "w") as f: f.write("{\n\"tasks\": 0,\n\"version\": \"1.1\"\n}") #Inform the user how many tasks have been found and how many of them are new status["text"] = str(len(tasks)) + " Aufgaben gefunden, davon " + str(len(newtasks)) + " neue." progress["maximum"]=len(newtasks) progress["value"]=1 main.update() print(str(len(tasks)) + " Aufgaben gefunden, davon " + str(len(newtasks)) + " neue.") tasks = newtasks #Consider only new tasks for further processing #Sort tasks by ID/creation date for i in range (len(tasks)): tasks[i] = tasks[i].rsplit("/", 1)[0] + "/" + tasks[i].split("/")[6].zfill(6) #Format all task numbers with 6 digits in order to sort them correctly tasks.sort() for i in range (len(tasks)): #Remove 0's after sorting in order to note down the URL's correctly tasks[i] = tasks[i].rsplit("/", 1)[0] + "/" + str(int(tasks[i].split("/")[6])) #Format all task numbers with 6 digits in order to sort them correctly #Download tasks for i in range(len(tasks)): status["text"] = "Lade Aufgabe " + str(i+1) + " von " + str(len(tasks)) + "..." main.update() print("Lade Aufgabe " + str(i+1) + " von " + str(len(tasks)) + "...") html = session.get(tasks[i]).text #Save data for later entry title = html.split(taskname1)[1].split(taskname2)[0] #Tasks name start = html.split(taskstart)[1].split(date1)[1].split(date2)[0] #Date when the task starts end = html.split(taskend)[1].split(date1)[1].split(date2)[0] #Date when the task ends description = html.split(textstart)[1].split(textend)[0].replace("\n", "\\n").replace("\"", "") #Task description url = tasks[i] while description.find("<") != -1: #Remove HTML tags description = description.split("<")[0] + description.split(">", 1)[1] files = 0 #Number of external files attached to the task. Will be increased later if there are files. filenames = [] filelinks = [] try: #Use <form> to check if attached files exist. html = html.split(att1)[1].split(att2)[0] #If necessary, download file(s) related to the task and link them correctly while html.find(fileurl) != -1: #Determine file data fileend = html.split(fileend1)[0].rsplit(".", 1)[1].split(fileend2)[0] filelink = "https://" + server + html.split(file1)[1].split("\"")[0] #Add file data to the array files = files + 1 filenames.append(html.split(".png\">")[1].split("</a></td>")[0]) filelinks.append(datafolder.replace('\\', '\\\\') + filelink.split("/")[7] + "." + fileend) #Download and save external file download["text"] = "Externe Datei wird heruntergeladen..." main.update() print("Externe Datei wird heruntergeladen...") with open(datafolder + filelink.split("/")[7] + "." + fileend, "wb") as f: f.write(session.get(filelink).content) #Replace HTML (if you have several files, do not download the same file again or mix up other things). html = html.replace(file1, "|", 1).replace(fileurl, "|", 1).replace(fileend1, "|", 1).replace(".png\">", "|", 1) download["text"] = "" except: pass #Note in JSON variable json.append("{\n\"title\": \"" + title + "\",\n\"start\": \"" + start + "\",\n\"end\": \"" + end + "\",\n\"description\": \"" + description + "\",\n\"url\": \"" + url + "\",\n\"files\": " + str(files)) if files != 0: json[-1] = json[-1] + ",\n\"filedetails\": [\n" for i in range(files): json[-1] = json[-1] + "{\"name\": \"" + filenames[i] + "\",\n\"link\": \"" + filelinks[i] + "\"},\n" json[-1] = json[-1].rsplit(",", 1)[0] + "\n]" json[-1] = json[-1] + "\n}" progress["value"] = progress["value"]+1 #Write overview status["text"] = "Schreibe in JSON-Datei..." main.update() print("Schreibe in JSON-Datei...") oldjson = open(datafolder + "tasks.json").read().rsplit("\n}", 1)[0] tasks = int(oldjson.split("\"tasks\": ")[1].split(",")[0]) for i in range(len(json)): oldjson = oldjson + ",\n\"" + str(i+tasks) + "\": " + json[i] #Write JSON to tasks.json with open(datafolder + "tasks.json", "w") as f: f.write(oldjson.replace(str(tasks), str(tasks+len(json)), 1) + "\n}") main.destroy()
def __init__(self,size): self.loadbar = Tk() self.loadbar.wm_title('Loading') self.pgb = Progressbar(self.loadbar,orient='horizontal',length='500',maximum=int(size)) self.pgb.pack() self.pgb.start()
class Example(Frame): def __init__(self, parent, q): Frame.__init__(self, parent) self.queue = q self.parent = parent self.initUI() def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N) def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.digits = int(self.ent1.get()) self.accuracy = int(self.ent2.get()) self.p1 = Process(target=self.generatePi, args=(self.queue,)) self.p1.start() self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onGetValue(self): if (self.p1.is_alive()): self.after(DELAY1, self.onGetValue) return else: try: self.txt.insert('end', self.queue.get(0)) self.txt.insert('end', "\n") self.pbar.stop() self.startBtn.config(state=NORMAL) except queue.Empty: print("queue is empty") def generatePi(self, queue): getcontext().prec = self.digits time.sleep(10) pi = Decimal(0) k = 0 n = self.accuracy while k < n: pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - (Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5)) - (Decimal(1)/(8*k+6))) k += 1 print(self.p1.is_alive()) queue.put(pi) print("end")
class MainForm(Tk, Observer): """ Defines a form object based from Tk in tkinter. """ def __init__(self): """ Initializes the control object and controls of the form. """ Tk.__init__(self) Observer.__init__(self) self.ctrl_anon = None self.resizable(0, 0) self._reset_controls() # Center window width = 800 height = 500 scr_width = self.winfo_screenwidth() scr_height = self.winfo_screenheight() # Calculate dimensions x = (scr_width/2) - (width/2) y = (scr_height/2) - (height/2) # Set window dimensions geo = str(width) + "x" + str(height) + "+" + str(x)[:-2] + "+" + str(y)[:-2] self.geometry(geo) def _reset_controls(self): """ Resets the controls on the form. """ image = ImageTk.PhotoImage(file="bg.png") # Initialize controls self.lbl_bg = Label(self, image=image) self.lbl_dir = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.lbl_anon = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.lbl_id = Label(self, bg="white", fg="#668FA7", font=("Courier", 14)) self.btn_dir_select = Button(self, text="Select data folder", command=self._btn_dir_press) self.btn_id = Button(self, text="Identify data", command=self._btn_id_press) self.btn_anon = Button(self, text="Anonymize data", command=self._btn_anon_press) self.tb_study = Entry(self, bg="#668FA7", fg="white") self.prg_id = Progressbar(self, orient="horizontal", length=200, mode="determinate") self.prg_anon = Progressbar(self, orient="horizontal", length=200, mode="determinate") # Place controls self.lbl_bg.place(x=0, y=0, relwidth=1, relheight=1) self.lbl_anon.place(x=400, y=400) self.lbl_id.place(x=400, y=325) self.btn_dir_select.place(x=250, y=250) self.btn_id.place(x=250, y=325) self.btn_anon.place(x=250, y=400) self.tb_study.place(x=250, y=175) self.prg_id.place(x=410, y=290) self.prg_anon.place(x=410, y=370) # Other formatting self.lbl_bg.image = image self.btn_id['state'] = "disabled" self.btn_anon['state'] = "disabled" self.prg_id['maximum'] = 100 self.prg_anon['maximum'] = 100 def _btn_dir_press(self): """ Allows user to select their data folder. """ self.ctrl_anon.reset() dir = filedialog.askdirectory(initialdir='.') if len(dir) > 0: self.lbl_dir.config(text=dir) self.btn_id['state'] = "active" self.btn_anon['state'] = "disabled" else: self.btn_id['state'] = "disabled" self.btn_anon['state'] = "disabled" def _btn_id_press(self): """ Calls the controller to identify data set. """ self.ctrl_anon.identify(self.lbl_dir['text']) self.btn_anon['state'] = "active" def _btn_anon_press(self): """ Calls the controller to anonymize the data set. """ if len(self.tb_study.get()) == 0: self.lbl_anon.config(text="Please enter a study name..") elif not self.tb_study.get().isalnum(): self.lbl_anon.config(text="Please enter a valid study name..") else: self.ctrl_anon.anonymize(self.tb_study.get(), self.lbl_dir['text']) def notify(self): """ Updates the progress of the anonymization and identification processes. """ self.prg_id['value'] = self.ctrl_anon.id_progress if self.prg_id['value'] == 100: self.lbl_id.config(text="Identification compelete") elif self.prg_id['value'] > 0: self.lbl_id.config(text="Identification in progress..") self.prg_anon['value'] = self.ctrl_anon.anon_progress if self.prg_anon['value'] == 100: self.lbl_anon.config(text="Anonymization compelete") elif self.prg_anon['value'] > 0: self.lbl_anon.config(text="Anonymization in progress..") def add_controller(self, control_anon): """ Adds a control anonymizer object to this gui. """ self.ctrl_anon = control_anon self.ctrl_anon.subscribe(self)
class Main: def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button def manage_config(self): if not os.path.isfile(os.path.expanduser("~\\documents\\lloader_cfg.ini")): with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.add_section('basic_config') # cfg file not exists so we make it config.set('basic_config', 'save_folder', self.save_folder) config.set('basic_config', 'html_tag1', ".filecontainer figcaption a") config.set('basic_config', 'html_tag2', ".filecontainer .file a") config.set('basic_config', 'url_1', "ylilauta.org") config.set('basic_config', 'url_2', "www.ylilauta.org") # .filecontainer .file a = ALL images (np included) but not mp4 # .filecontainer figcaption a = not np images, but all uploaded images & mp4 config.write(cfgfile) logger.debug("Created a config file") else: try: config.read(os.path.expanduser('~\\documents\\lloader_cfg.ini')) self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.save_folder = config.get('basic_config', 'save_folder') # get save folder from file self.folder_entry.insert(0, self.save_folder) # write to folder field self.folder_entry['state'] = 'readonly' # make it read-only again logger.debug("Read from config") except (IOError, OSError): logger.exception("Config error") except (configparser.MissingSectionHeaderError, configparser.NoSectionError): # correct section not found from file os.remove(os.path.expanduser("~\\documents\\lloader_cfg.ini")) self.manage_config() # delete file and try to create it from start def get_folder(self): dir_opt = options = {} # define options for get folder function options['initialdir'] = self.save_folder options['mustexist'] = False options['parent'] = self.master options['title'] = 'Choose a directory' self.save_folder = filedialog.askdirectory(**dir_opt) # actual function to get the folder name with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.set('basic_config', 'save_folder', self.save_folder) config.write(cfgfile) # write new save folder to config file self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.folder_entry.insert(0, self.save_folder) # update folder field self.folder_entry['state'] = 'readonly' # make it read-only again self.clear_savefolder_list() self.openfolderbutton['state'] = 'normal' # we can now press the open folder and url buttons self.urlbutton['state'] = 'normal' # because we have defined a save folder def openfolder(self): os.startfile(self.save_folder) # opens the save folder def clear_savefolder_list(self): del self.filenames[:] # clears the list of files in a folder self.filenames.append(next(os.walk(self.save_folder))[2]) # adds every file in folder to list def check_for_url(self): parse = urlparse(self.url_texti.lower()) # checks if url is ylilauta logging.debug("url started with %s" % parse.netloc) if (parse.netloc.startswith(self.url_1) or parse.netloc.startswith(self.url_2)): return True else: return False def is_image(self): if (self.image_url.lower().endswith(".jpg") or self.image_url.lower().endswith(".jpeg") or self.image_url.lower().endswith(".png")): # link seems to be image return True else: return False def is_mp4(self): if self.image_url.lower().endswith(".mp4"): # link ends in mp4 so its mp4 return True else: return False def is_mp3(self): if self.image_url.lower().endswith(".mp3"): # link ends in mp3 so its mp3 return True else: return False def we_want_it_anyway(self): if self.c2_selection.get() == 1: # checkbutton2 is selected so we want all files return True else: return False def getting_both(self): if self.r_selection.get() == 1: # first radio button is selected so dl both return True else: return False def getting_img(self): if self.r_selection.get() == 2: # second radio button is selected so dl images only return True else: return False def getting_mp4(self): if self.r_selection.get() == 3: # third radio button is selected so dl mp4 only return True else: return False def getting_mp3(self): if self.r_selection.get() == 4: # fourth radio button is selected so we get mp3 only return True else: return False def rename_file(self): get_filetype = os.path.splitext(os.path.basename(self.image_url))[1] # get filetype new_file_name_start = '' for i in range(0, 15): new_file_name_start += str(random.randint(0, 9)) # create random string of numbers self.name_of_file = (new_file_name_start + get_filetype) # create the whole new name def write_file(self): self.status_text.set('Downloading %s' % self.name_of_file) logger.info('Downloading %s' % self.name_of_file) self.master.update() self.res = requests.get(self.image_url) self.res.raise_for_status() try: with open(os.path.join(self.save_folder, self.name_of_file), 'wb') as self.imagefile: for chunk in self.res.iter_content(100000): self.imagefile.write(chunk) self.imagewritten = True except IOError: logger.exception("Exception with file write") self.status_text.set('File error') self.master.update() def file_get_logic(self): self.clear_savefolder_list() # need to update this list between files self.imagewritten = False # need to change this here because if same thread has same pictures if self.c1_selection.get() == 1: # if want new random name self.rename_file() else: self.name_of_file = os.path.basename(self.image_url) # using default filename if self.name_of_file in self.filenames[0]: # file exists if self.c2_selection.get() == 1: # we want to overwrite self.write_file() else: pass elif self.name_of_file not in self.filenames[0]: # file does not exist in folder self.write_file() # so we take it in self.master.update() def connect_logic(self): try: self.res = requests.get(self.url_texti, headers=self.headers, timeout=(10.0, self.read_timeout)) self.res.raise_for_status() except (requests.exceptions.ReadTimeout, requests.exceptions.HTTPError): logger.exception("Connection exception") self.status_text.set("Network error %s" % self.res.status_code) self.master.update() def logic(self): self.clear_savefolder_list() self.num_pics = 0 # make these 0 because we just called the function self.num_mp4 = 0 self.num_mp3 = 0 self.imagewritten = False self.url_texti = '' self.progressbar["value"] = 0 done = False if self.url_text != '': self.url_texti = (self.url_text.get()) # if url text is not empty we will set it to variable if not self.url_text or self.check_for_url() is False: # if url is wrong or empty self.status_text.set('URL not supported') logger.debug("URL is false: %s" % self.url_texti) while not done and self.check_for_url() is True: self.urlbutton['state'] = 'disabled' # disable buttons so they cant be pressed while run self.selectbutton['state'] = 'disabled' # we will enable them again in the end self.R1['state'] = 'disabled' self.R2['state'] = 'disabled' self.R3['state'] = 'disabled' self.R4['state'] = 'disabled' self.C1['state'] = 'disabled' self.C2['state'] = 'disabled' self.url_entry['state'] = 'readonly' self.status_text.set(("Getting from %s" % self.url_texti)) self.progressbar['value'] = 0 self.master.update() self.connect_logic() soup = bs4.BeautifulSoup(self.res.text, 'html.parser') # create soup total_stuff = 0 html_tag1 = config.get('basic_config', 'html_tag1') # we will fetch from these tags html_tag2 = config.get('basic_config', 'html_tag2') list_of_links = [] for imglink in soup.select(html_tag1): # grab items from tags and put them to list if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) for imglink in soup.select(html_tag2): if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) try: list_of_links = [x for x in list_of_links if x != "None"] # clear "none"s from list except ValueError: # there is no "none" in list pass total_stuff = len(list_of_links) # variable helps with progressbar logger.debug("total stuff is: %s" % total_stuff) for link in list_of_links: # iterate through list of links link = 'http:' + link # make item a valid link self.image_url = link # file get logic still uses global variable lol if (link.lower().endswith('.jpg') or link.lower().endswith('png') or link.lower().endswith('jpeg')): # we have an image if self.getting_both() or self.getting_img(): # we want an image self.file_get_logic() # we get an image if self.imagewritten: # logic is complete and image is written self.num_pics += 1 if link.lower().endswith('.mp4'): # same as above but with mp4 if self.getting_both() or self.getting_mp4(): self.file_get_logic() if self.imagewritten: self.num_mp4 += 1 if link.lower().endswith('.mp3'): if self.getting_both() or self.getting_mp3(): self.file_get_logic() if self.imagewritten: self.num_mp3 += 1 self.progressbar['value'] += 100 / total_stuff # progressbar fills self.status_text.set('Downloaded %s images, %s mp4, %s mp3.' % (self.num_pics, self.num_mp4, self.num_mp3)) self.urlbutton['state'] = 'normal' self.url_entry['state'] = 'normal' self.selectbutton['state'] = 'normal' self.R1['state'] = 'normal' self.R2['state'] = 'normal' self.R3['state'] = 'normal' self.R4['state'] = 'normal' self.C1['state'] = 'normal' self.C2['state'] = 'normal' # we have enabled all buttons to be used again logger.info("Done.") break logging.shutdown()
class MainView(Frame): def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs); self.toForeGround ################### init, main config ###################### container = Frame(self, bg=bgColor); container.pack(side="top", fill="both", expand=True); self.ft1 = font.Font(family='Arial', size=11); self.ft2 = font.Font(family='MS Gothic', size=10); self.ft3 = font.Font(family='Arial', size=9); self.ft4 = font.Font(family='Arial', size=10); self.ft5 = font.Font(family='Arial', size=14); self.ft6 = font.Font(family="Courier", size = 9); self.p1 = Page1(container, bg=container["background"]); self.p2 = Page2(container, bg=container["background"]); self.p3 = Page3(container, bg=container["background"]); self.p4 = Page4(container, bg=container["background"]); self.p5 = Page5(container, bg=container["background"]); self.p6 = Page6(container, bg=container["background"]); self.p7 = Page7(container, bg=container["background"]); self.p8 = Page8(container, bg=container["background"]); self.p9 = Page9(container, bg=container["background"]); topBar = Frame(container, bg=topBarColor, width=container.winfo_width() * framewidth, height=topBarHeight); topBar.place(x=0, y=0); self.p1.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p2.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p3.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p4.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p5.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p6.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p7.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p8.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p9.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); close= Button(topBar, text=u"\u2715", command= lambda: self.close(), bg=topBar["background"], bd=0, font = self.ft2, fg=fgColor, activebackground="#940000"); close.place(x = topBar["width"] - topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); minim = Button(topBar, text="_", command= lambda: self.toicon(), bg=topBar["background"], bd=0, font=self.ft2, fg=fgColor, activebackground="#364969"); minim.place(x = topBar["width"] - 2 * topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); label = Label(topBar, text=title, font=self.ft3, bg=topBar["background"], fg=fgColor); label.place(x = 5, y = 0, height= topBar["height"]); #event handlers so the window can be moved topBar.bind("<ButtonPress-1>", self.StartMove); topBar.bind("<ButtonRelease-1>", self.StopMove); topBar.bind("<B1-Motion>", self.OnMotion); label.bind("<ButtonPress-1>", self.StartMove); label.bind("<ButtonRelease-1>", self.StopMove); label.bind("<B1-Motion>", self.OnMotion); close.bind("<Enter>", self.closeEnterBG); close.bind("<Leave>", self.topBarButtonNormalBG); minim.bind("<Enter>", self.minimEnterBG); minim.bind("<Leave>", self.topBarButtonNormalBG); self.master.bind("<Unmap>", self.toiconify); self.master.bind("<Map>", self.todeiconify); ##################### page 1, intro ############################ T1 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T1.place(x=10, y=10); HelpButton = Label(self.p1, text = "help", background=bgColor, fg = hyperlinkColor, font = self.ft5, cursor="hand2"); HelpButton.place(x=8, y=53); underlineFont = font.Font(HelpButton, HelpButton.cget("font")); underlineFont.configure(underline = True); HelpButton.configure(font=underlineFont); HelpButton.bind("<Button-1>", lambda x: self.clickHelp()) T2 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T2.place(x=53, y=55); T1.insert(END, "Welcome to the ELS Scorion tool. Click next to select what tool to use, or press\n"); T2.insert(END, "to learn more about the tool."); T1.configure(state=DISABLED); T2.configure(state=DISABLED); nextButtonP1 = Button(self.p1, text = "Next", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); nextButtonP1.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); nextButtonP1.bind("<Enter>", self.buttonEnterBG); nextButtonP1.bind("<Leave>", self.buttonNormalBG); ################## page 2, task picker ######################### instrLabel = Label(self.p2, text = "Choose what tool to use", bg=self.p2["background"], fg=fgColor, font=self.ft5); instrLabel.place(x= 30, y = 10); buildGroupsButton = Button(self.p2, text = "Build Scorion groups", command=self.p3.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); buildGroupsButton.place(x = 75, y = 48, width = 250, height = 2*nextprevButtonHeight); buildGroupsButton.bind("<Enter>", self.buttonEnterBG); buildGroupsButton.bind("<Leave>", self.buttonNormalBG); splitGroupsButton = Button(self.p2, text = "Split Scorion file", command=self.p4.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); splitGroupsButton.place(x = 75, y = 120, width = 250, height = 2*nextprevButtonHeight); splitGroupsButton.bind("<Enter>", self.buttonEnterBG); splitGroupsButton.bind("<Leave>", self.buttonNormalBG); onlyFileButton = Button(self.p2, text = "Only create Scorion file", command=self.p5.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); onlyFileButton.place(x = 75, y = 192, width = 250, height = 2*nextprevButtonHeight); onlyFileButton.bind("<Enter>", self.buttonEnterBG); onlyFileButton.bind("<Leave>", self.buttonNormalBG); possibleErrorButton = Button(self.p2, text = "Find errors in file", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); possibleErrorButton.place(x = 75, y = 264, width = 250, height = 2*nextprevButtonHeight); possibleErrorButton.bind("<Enter>", self.buttonEnterBG); possibleErrorButton.bind("<Leave>", self.buttonNormalBG); previousButtonP2 = Button(self.p2, text = "Back", command=self.p1.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP2.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP2.bind("<Enter>", self.buttonEnterBG); previousButtonP2.bind("<Leave>", self.buttonNormalBG); ################## page 3, group builder ######################## previousButtonP3 = Button(self.p3, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP3.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP3.bind("<Enter>", self.buttonEnterBG); previousButtonP3.bind("<Leave>", self.buttonNormalBG); courseIdWrap = Frame(self.p3, bg= self.p3["background"]); courseIdWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar = StringVar(); self.courseVar.trace("w", lambda name, index, mode, courseVar=self.courseVar: self.firecallback()); courseIdLabel = Label(courseIdWrap, text = "Course Id:", bg=self.p3["background"], fg=fgColor, font=self.ft4); courseIdLabel.place(x= 0, y = 0, height = topBarHeight); courseId = Entry(courseIdWrap, width= 45, bg=bg2Color, textvariable=self.courseVar,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId.place(x = 65, y = 0, height=topBarHeight); fileWrap = Frame(self.p3, bg =self.p3["background"]); fileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel = Label(fileWrap, text = "File:", bg=self.p3["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 30, y = 0, height = topBarHeight); self.fileVar = StringVar(); self.fileVar.trace("w", lambda name, index, mode, fileVar=self.fileVar: self.firecallback()); self.fileName = Entry(fileWrap, width= 36, textvariable=self.fileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName.place(x = 65, y = 0, height= topBarHeight); #TODO: drag files into the text field self.browse = Button(fileWrap, text="Browse", command=self.load_file, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse.place(x=326, y=0, height = topBarHeight, width=60); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); seperatorWrap = Frame(self.p3, bg = self.p3["background"]); seperatorWrap.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel = Label(seperatorWrap, text="What seperator is used in the file?", bg=self.p3["background"], fg=fgColor, font=self.ft4); optionLabel.place(x = 0, y = 0, height = topBarHeight); optionList = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar = StringVar(); self.sepVar.set(optionList[0][1]); commaButton = Radiobutton(seperatorWrap, text=optionList[0][0], variable = self.sepVar, value=optionList[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton = Radiobutton(seperatorWrap, text=optionList[1][0], variable = self.sepVar, value=optionList[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton.place(x=260, y = topBarHeight + 2, width = 120); optionLabel = Label(self.p3, text="Do you already have a Scorion File?"); scorionCheckWrap = Frame(self.p3, bg = self.p3["background"]); scorionCheckWrap.place(x=10, y = 194, height=topBarHeight, width = framewidth - 20); self.checkVar = IntVar(); scorionCheck = Checkbutton(scorionCheckWrap, text="Create a Scorion file?", var = self.checkVar, font=self.ft4, fg=fgColor, bg=bg2Color, bd=0, highlightthickness = 0, selectcolor=bg2Color, activeforeground=fgColor, activebackground= bg2Color); scorionCheck.select(); scorionCheck.place(x=210, y=0, height=topBarHeight, width = 170); self.goButton = Button(self.p3, text = "Run", command=self.combineFuncs, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButton.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 4, split groups page ######################## previousButtonP4 = Button(self.p4, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP4.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP4.bind("<Enter>", self.buttonEnterBG); previousButtonP4.bind("<Leave>", self.buttonNormalBG); scorFileWrap = Frame(self.p4, bg =self.p4["background"]); scorFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight); fileLabel = Label(scorFileWrap, text = "Scorion File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 0, y = 0, height = topBarHeight); self.scorFileVar = StringVar(); self.scorFileVar.trace("w", lambda name, index, mode, scorFileVar=self.scorFileVar: self.firecallback1()); self.scorFileName = Entry(scorFileWrap, width= 34, textvariable=self.scorFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.scorFileName.place(x = 79, y = 0, height= topBarHeight); self.browse1 = Button(scorFileWrap, text="Browse", command=self.load_file1, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse1.place(x=326, y=0, height = topBarHeight, width=60); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); errFileWrap = Frame(self.p4, bg =self.p4["background"]); errFileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); errLabel = Label(errFileWrap, text = "Error File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); errLabel.place(x= 0, y = 0, height = topBarHeight); self.errFileVar = StringVar(); self.errFileVar.trace("w", lambda name, index, mode, errFileVar=self.errFileVar: self.firecallback1()); self.errFileName = Entry(errFileWrap, width= 36, textvariable=self.errFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.errFileName.place(x = 65, y = 0, height= topBarHeight); self.browse2 = Button(errFileWrap, text="Browse", command=self.load_file2, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse2.place(x=326, y=0, height = topBarHeight, width=60); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); self.goButtonP4 = Button(self.p4, text = "Run", command=self.combineFuncs2, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP4.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 5, only create groups page ################## previousButtonP5 = Button(self.p5, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP5.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP5.bind("<Enter>", self.buttonEnterBG); previousButtonP5.bind("<Leave>", self.buttonNormalBG); courseIdWrap2 = Frame(self.p5, bg= self.p5["background"]); courseIdWrap2.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar2 = StringVar(); self.courseVar2.trace("w", lambda name, index, mode, courseVar2=self.courseVar2: self.firecallback2()); courseIdLabel2 = Label(courseIdWrap2, text = "Course Id:", bg=self.p5["background"], fg=fgColor, font=self.ft4); courseIdLabel2.place(x= 0, y = 0, height = topBarHeight); courseId2 = Entry(courseIdWrap2, width= 45, bg=bg2Color, textvariable=self.courseVar2,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId2.place(x = 65, y = 0, height=topBarHeight); fileWrap2 = Frame(self.p5, bg =self.p5["background"]); fileWrap2.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel2 = Label(fileWrap2, text = "File:", bg=self.p5["background"], fg=fgColor, font=self.ft4); fileLabel2.place(x= 30, y = 0, height = topBarHeight); self.fileVar2 = StringVar(); self.fileVar2.trace("w", lambda name, index, mode, fileVar2=self.fileVar2: self.firecallback2()); self.fileName2 = Entry(fileWrap2, width= 36, textvariable=self.fileVar2,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName2.place(x = 65, y = 0, height= topBarHeight); self.browse3 = Button(fileWrap2, text="Browse", command=self.load_file3, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse3.place(x=326, y=0, height = topBarHeight, width=60); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); seperatorWrap2 = Frame(self.p5, bg = self.p5["background"]); seperatorWrap2.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel2 = Label(seperatorWrap2, text="What seperator is used in the file?", bg=self.p5["background"], fg=fgColor, font=self.ft4); optionLabel2.place(x = 0, y = 0, height = topBarHeight); optionList2 = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar2 = StringVar(); self.sepVar2.set(optionList2[0][1]); commaButton2 = Radiobutton(seperatorWrap2, text=optionList2[0][0], variable = self.sepVar2, value=optionList2[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton2 = Radiobutton(seperatorWrap2, text=optionList2[1][0], variable = self.sepVar2, value=optionList2[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton2.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton2.place(x=260, y = topBarHeight + 2, width = 120); self.goButtonP5 = Button(self.p5, text = "Run", command=self.combineFuncs3, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP5.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 6, progress page ########################### self.cancelButton = Button(self.p6, text = "cancel", command=lambda:sys.exit(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.cancelButton.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.cancelButton.bind("<Enter>", self.buttonEnterBG); self.cancelButton.bind("<Leave>", self.buttonNormalBG); self.progressLabel = Label(self.p6, text = "Working, this might take a couple of minutes...", bg=self.p6["background"], fg=fgColor, font=self.ft1) self.progressLabel.place(x=10, y=36); #TODO: make the progressbar actually progress to the things that are done style = Style(); style.theme_use('alt') style.configure("els.Horizontal.TProgressbar", background=fgColor); self.progress = Progressbar(self.p6, orient=HORIZONTAL, length = framewidth - 20, mode="indeterminate", style="els.Horizontal.TProgressbar", maximum=40); self.progress.place(x=10, y=10); self.progress.start(17); self.closeP6 = Button(self.p6, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); ################### page 7, error page ########################### #TODO: implement full stacktrace instead of only 2 #TODO: or: make a log file of the stacktrace that can be "downloaded" when clicked #TODO: error page is not working correctly anymore; errors are being cut off self.errorLabel = Label(self.p7, text = "Something went wrong, try again or contact Cas", bg=self.p7["background"], fg=errorColor, font=self.ft1); self.errorLabel.place(x=36, y=10); self.errorInfoLabel = Label(self.p7, text = "Error Info:", bg=self.p7["background"], fg=fgColor, font=self.ft1); self.errorInfoLabel.place(x=36, y=50); self.stackTraceStringVar1 = StringVar(); self.stackTraceStringVar2 = StringVar(); self.stackTraceLabel1 = Label(self.p7, textvariable = self.stackTraceStringVar1, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceLabel2 = Label(self.p7, textvariable = self.stackTraceStringVar2, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.stackTraceLabel1.place(x=36, y=70); self.stackTraceLabel2.place(x=36, y=110); self.backToMenu = Button(self.p7, text = "Back to menu", command=self.backtomenu, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.backToMenu.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.backToMenu.bind("<Enter>", self.buttonEnterBG); self.backToMenu.bind("<Leave>", self.buttonNormalBG); self.closeP7 = Button(self.p7, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.closeP7.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP7.bind("<Enter>", self.buttonEnterBG); self.closeP7.bind("<Leave>", self.buttonNormalBG); ################### page 8, find error page ########################### previousButtonP8 = Button(self.p8, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP8.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP8.bind("<Enter>", self.buttonEnterBG); previousButtonP8.bind("<Leave>", self.buttonNormalBG); checkErrFileWrap = Frame(self.p8, bg =self.p8["background"]); checkErrFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = 3*topBarHeight); checkErrLabel = Label(checkErrFileWrap, text = "File to check for Errors:", bg=self.p4["background"], fg=fgColor, font=self.ft4); checkErrLabel.place(x= 0, y = 0, height = topBarHeight); self.checkErrFileVar = StringVar(); self.checkErrFileVar.trace("w", lambda name, index, mode, checkErrFileVar=self.checkErrFileVar: self.firecallback3()); self.checkErrFileName = Entry(checkErrFileWrap, width= 45, textvariable=self.checkErrFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.checkErrFileName.place(x = 2, y = 25, height= topBarHeight); self.browse4 = Button(checkErrFileWrap, text="Browse", command=self.load_file4, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse4.place(x=326, y=25, height = topBarHeight, width=60); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); self.goButtonP8 = Button(self.p8, text = "Run", command=self.p9.lift, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP8.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 9, find error results ########################### previousButtonP9 = Button(self.p9, text = "Back", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP9.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP9.bind("<Enter>", self.buttonEnterBG); previousButtonP9.bind("<Leave>", self.buttonNormalBG); #testing self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, r"M:\ud\os\ssc\imos\bbsup\@ new folder_Surfdrive\7. Scorion\Vakmappen 171804\46597-171804\group_import_no_TAs.txt"); self.errors = errorChecker(self.checkErrFileVar.get()); self.croppedErrors = self.errors[0:7] if (len(self.errors) > 0): Label(self.p9, text = "Found %d possible errors, on the following lines:" %len(self.errors), fg = fgColor, bg = bgColor, font = self.ft1).place(x=16, y=12); openFile = Button(self.p9, text = "Open file", command=lambda: self.clickOpenFile(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); openFile.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); openFile.bind("<Enter>", self.buttonEnterBG); openFile.bind("<Leave>", self.buttonNormalBG); self.drawErrors(); else: Label(self.p9, text = "Found no errors", fg = fgColor, bg = bgColor, font = self.ft5).place(x=10, y=10); ################### finally, show page 1 to start ################ self.p1.show(); ################### window event handlers ########################## def StartMove(self, event): self.master.x = event.x; self.master.y = event.y; def StopMove(self, event): self.master.x = None; self.master.y = None; def OnMotion(self, event): deltax = event.x - self.master.x; deltay = event.y - self.master.y; x = self.master.winfo_x() + deltax; y = self.master.winfo_y() + deltay; self.master.geometry("+%s+%s" % (x, y)); def toForeGround(self): self.master.lift(); def toicon(self): self.master.update_idletasks(); self.master.overrideredirect(False); self.master.iconify(); def toiconify(self, event): self.master.overrideredirect(False); def todeiconify(self, event): self.master.overrideredirect(True); def closeEnterBG(self, event): event.widget.config(bg="#C40000"); def minimEnterBG(self, event): event.widget.config(bg="#455D85") def topBarButtonNormalBG(self, event): event.widget.config(bg=topBarColor); def buttonEnterBG(self, event): event.widget.config(bg=buttonHoverColor); def buttonNormalBG(self, event): event.widget.config(bg=buttonColor); def buttonEnterDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def buttonNormalDisabledBG(self, event): event.widget.config(bg=disabledButtonColor); def close(self): self.progress.stop(); self.progress.destroy(); self.master.quit(); ################### other functions ############################## def clickHelp(self): location = "manual.docx"; os.system("start " + location); def clickOpenFile(self): import subprocess; location = self.checkErrFileName.get(); program = resource_path("Notepad++\\notepad++.exe") subprocess.call([program, location]); def showNextErrors(self): startNumber = self.errors.index(self.croppedErrors[0]); self.croppedErrors = self.errors[startNumber + 7:startNumber + 14]; self.drawErrors(); def showPrevErrors(self): startNumber = self.errors.index(self.croppedErrors[0]) self.croppedErrors = self.errors[startNumber - 7:startNumber]; self.drawErrors(); def drawErrors(self): if (len(self.errors) > 7): startNumber = self.errors.index(self.croppedErrors[0]); self.nextErrors = Button(self.p9, text = ">", command=lambda: self.showNextErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); self.prevErrors = Button(self.p9, text = "<", command=lambda: self.showPrevErrors(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); if not (startNumber >= (len(self.errors) - 7)): self.nextErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX + nextprevButtonWidth/2 + 2, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: print("should hide"); self.hideNextButton(); if (startNumber > 0): self.prevErrors.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - 2 * nextprevButtonPaddingY, width = nextprevButtonWidth/2 - 2, height = nextprevButtonHeight); else: self.prevErrors.lower(); cropRange = 22; ErrorWrap = Frame(self.p9, bg = codeBGColor); ErrorWrap.place(x = 56, y = 40, width = framewidth - 72, height = frameheight - topBarHeight - 124) LineWrap = Frame(self.p9, bg = codeBG2Color); LineWrap.place(x=16, y = 40, width = 40, height = frameheight - topBarHeight - 124); for i in range(len(self.croppedErrors)): formattedLine = str((int(self.croppedErrors[i].getLineOccurence()) + 1)) for k in range(3 - len(formattedLine)): formattedLine = "0" + formattedLine; Label(LineWrap, text = formattedLine, bg = codeBG2Color, font = self.ft6, fg = fgColor).place(x = 6, y = 4+40*i) for i in range(len(self.croppedErrors)): sourceLine = self.croppedErrors[i].getSourceLine(); if (len(sourceLine) - self.croppedErrors[i].getColOccurence()) > cropRange: cropped = sourceLine[max(self.croppedErrors[i].getColOccurence() - cropRange, 0):max(self.croppedErrors[i].getColOccurence() + cropRange, 2 * cropRange)] Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = min(round(7.05 * cropRange), round(7.1*self.croppedErrors[i].getColOccurence())), y = 20 + 40*i) Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) else: EOLOccurence = len(sourceLine) - self.croppedErrors[i].getColOccurence() - 1; cropped = sourceLine[self.croppedErrors[i].getColOccurence() - (2 * cropRange - EOLOccurence):] Label(ErrorWrap, text=cropped, fg = fgColor, bg = codeBGColor, font = self.ft6).place(x = 2, y = 5+40*i) Label(ErrorWrap, text="^", fg = errorColor, bg = codeBGColor).place(x = round(7.05*((2*cropRange) - EOLOccurence)), y = 20 + 40*i) def hideNextButton(self): self.nextErrors.place_forget(); def firecallback(self): if len(self.courseVar.get()) == 0 or len(self.fileVar.get()) == 0: self.goButton.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButton.bind("<Enter>", self.buttonEnterDisabledBG); self.goButton.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButton.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButton.bind("<Enter>", self.buttonEnterBG); self.goButton.bind("<Leave>", self.buttonNormalBG); def firecallback1(self): if len(self.scorFileVar.get()) == 0 or len(self.errFileVar.get()) == 0: self.goButtonP4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP4.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP4.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP4.bind("<Enter>", self.buttonEnterBG); self.goButtonP4.bind("<Leave>", self.buttonNormalBG); def firecallback2(self): if len(self.courseVar2.get()) == 0 or len(self.fileVar2.get()) == 0: self.goButtonP5.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP5.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP5.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP5.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP5.bind("<Enter>", self.buttonEnterBG); self.goButtonP5.bind("<Leave>", self.buttonNormalBG); def firecallback3(self): if len(self.checkErrFileVar.get()) == 0: self.goButtonP8.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.goButtonP8.bind("<Enter>", self.buttonEnterDisabledBG); self.goButtonP8.bind("<Leave>", self.buttonNormalDisabledBG); else: self.goButtonP8.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.goButtonP8.bind("<Enter>", self.buttonEnterBG); self.goButtonP8.bind("<Leave>", self.buttonNormalBG); def combineFuncs(self): self.p6.lift(); try: self.createGroups(); except Exception as e: self.fireErrorPage(e); return def combineFuncs2(self): self.p6.lift(); try: self.split(); except Exception as e: self.fireErrorPage(e); return def combineFuncs3(self): self.p6.lift(); try: self.createFile(); except Exception as e: self.fireErrorPage(e); return def fireErrorPage(self, e): import traceback; global tb; tb = traceback.format_exc(); traceback.print_exc(); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.p7.lift(); def getStackTrace(self): if len(tb.split("\n")) == 1: return [tb, ""]; elif len(tb.split("\n")) < 4: return [tb.split("\n")[-2].lstrip(), ""]; return [tb.split("\n")[-2].lstrip(), tb.split("\n")[-4].lstrip()]; def load_file(self): self.browse.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse.bind("<Enter>", self.buttonEnterDisabledBG); self.browse.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName.delete(0, END); self.fileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); return def load_file1(self): self.browse1.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse1.bind("<Enter>", self.buttonEnterDisabledBG); self.browse1.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.scorFileName.delete(0, END); self.scorFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse1.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); return def load_file2(self): self.browse2.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse2.bind("<Enter>", self.buttonEnterDisabledBG); self.browse2.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.errFileName.delete(0, END); self.errFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse2.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); return def load_file3(self): self.browse3.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse3.bind("<Enter>", self.buttonEnterDisabledBG); self.browse3.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.fileName2.delete(0, END); self.fileName2.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse3.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); return def load_file4(self): self.browse4.config(state=DISABLED,background=disabledButtonColor, activebackground=disabledButtonColor); self.browse4.bind("<Enter>", self.buttonEnterDisabledBG); self.browse4.bind("<Leave>", self.buttonNormalDisabledBG); fname = askopenfile(filetypes=(("CSV files", "*.csv"), ("Text files", "*.txt"), ("All files", "*.*") )); if fname: try: self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, fname.name); except: # <- naked except is a bad idea showerror("Open Source File", "Failed to read file\n'%s'" % fname); self.browse4.config(state=NORMAL,background=buttonColor, activebackground=buttonPressedColor); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); return def createGroups(self): course_id = self.courseVar.get(); fileName = self.fileVar.get(); seperator = self.sepVar.get(); write = self.checkVar.get() == 1; groups = getGroups(course_id, fileName, seperator, write); driver = createScorionGroups(groups, course_id); #throws windowserror driver.quit(); self.finish(); def createFile(self): course_id = self.courseVar2.get(); fileName = self.fileVar2.get(); seperator = self.sepVar2.get(); getGroups(course_id, fileName, seperator, True); self.finish(); def split(self): scorFile = self.scorFileName.get(); errFile = self.errFileName.get(); splitGroups(scorFile, errFile); self.finish(); def finish(self): self.progress["mode"] = 'determinate'; self.progress.update_idletasks(); self.progress.stop(); self.progressLabel["text"] = "Finished!"; self.cancelButton["text"] = "Back to menu"; self.closeP6.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP6.bind("<Enter>", self.buttonEnterBG); self.closeP6.bind("<Leave>", self.buttonNormalBG) self.cancelButton.config(command=self.backtomenu); def backtomenu(self): self.scorFileVar.set(""); self.errFileVar.set(""); self.courseVar.set(""); self.courseVar2.set(""); self.fileVar.set(""); self.fileVar2.set(""); self.sepVar.set(","); self.sepVar2.set(","); self.p2.lift(); self.cancelButton.config(text = "cancel", command=exit); self.closeP6.place_forget(); self.progressLabel["text"] = "Working, this might take a couple of minutes..."; self.progress["mode"] = 'indeterminate';
class qbtConvertor(Tk): """ GUI Application for migration from uTorrent to qBittorrent """ def __init__(self): Tk.__init__(self) self.title("uT to qBt convertor") #main frame self.main_frame = Frame(self, padding="3 3 12 12") self.main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) self.main_frame.columnconfigure(0, weight=1) self.main_frame.rowconfigure(0, weight=1) #uT part self.ut_data = StringVar() self.ut_label = Label(self.main_frame, text="uT data") self.ut_label.grid(column=0, row=1, sticky=(W)) self.ut_entry = Entry(self.main_frame, width=100, textvariable=self.ut_data) self.ut_entry.grid(column=1, row=1, sticky=(W)) self.ut_button = Button(self.main_frame, text="Browse", command=self.load_file) self.ut_button.grid(column=2, row=1) #qBt part self.qbt_folder = StringVar() self.qbt_label = Label(self.main_frame, text="qBt folder") self.qbt_label.grid(column=0, row=4, sticky=(W)) self.qbt_entry = Entry(self.main_frame, width=100, textvariable=self.qbt_folder) self.qbt_entry.grid(column=1, row=4, sticky=(W)) self.qbt_button = Button(self.main_frame, text="Browse", command=self.open_dir) self.qbt_button.grid(column=2, row=4, sticky=(W, E)) #convertor self.convertor_button = Button(self.main_frame, text="Convert", command=self.convert, width=50) self.convertor_button.grid(column=1, columnspan=2, row=5) self.progress_bar = Progressbar(self.main_frame, orient=HORIZONTAL, length=300, mode="indeterminate") self.progress_bar.grid(column=1, columnspan=3, row=6) #set padding for each element for child in self.main_frame.winfo_children(): child.grid_configure(padx=5, pady=5) def convert(self): message = messagebox if not self.qbt_folder.get() or not self.ut_data.get(): message.showerror("ERROR", "Specify paths!") return self.progress_bar.start() convertor(self.ut_data.get(), self.qbt_folder.get()) self.progress_bar.stop() def load_file(self): file_name = filedialog.askopenfilename(filetypes=(("UT resume file", "*.dat"), ("All", "*"))) if file_name: self.ut_data.set(file_name) def open_dir(self): dir_name = filedialog.askdirectory() if dir_name: self.qbt_folder.set(dir_name)
from guizero import App, Box, Text from tkinter import Spinbox from tkinter.ttk import Progressbar app = App(title="Using tk widgets") Text(app, text="Spinbox") # add a spinbox widget to the app sp = Spinbox(from_=0, to=10) app.add_tk_widget(sp) Text(app, text="and Progressbar") box = Box(app, border=True) # add a progress bar to the boc pb = Progressbar(box.tk) box.add_tk_widget(pb) pb.start() Text(app, text="in guizero") app.display()
class OptimizeGroup(Group): def __init__(self, *args, **kwargs): self._app = kwargs.pop('wavesyn_root') self.__topwin = kwargs.pop('topwin') super().__init__(*args, **kwargs) parameter_frame = Frame(self) parameter_frame.pack(side='left', expand='yes', fill='y') self.__num = LabeledEntry(parameter_frame) set_attributes(self.__num, label_text = 'num', entry_text = '1', label_width = 5, entry_width = 8, checker_function = self._app.gui.value_checker.check_int ) self.__num.entry.bind('<Return>', lambda event: self._on_solve_click()) self.__num.pack(side='top') self.__pci = LabeledEntry(parameter_frame) set_attributes(self.__pci, label_text = 'PCI', entry_text = '100', label_width = 5, entry_width = 8, checker_function = self._app.gui.value_checker.check_int ) self.__pci.pack(side='top') self.__parallel_checker_variable = IntVar() self.__parallel_checker = Checkbutton(parameter_frame, text="Parallel", variable=self.__parallel_checker_variable, command=self._on_parallel_checker_click) self.__parallel_checker.pack() progfrm = Frame(self) progfrm.pack(side='left', expand='yes', fill='y') self.__genbtn = Button(progfrm, text='Generate', command=self._on_solve_click) self.__genbtn.pack(side='top') Button(progfrm, text='Stop', command=self._on_stop_button_click).pack(side='top') self.__progressbar_variable = IntVar() self.__finishedwav = IntVar() self.__progressbar = Progressbar(progfrm, orient='horizontal', variable=self.__progressbar_variable, maximum=100) self.__progressbar.pack(side='left') self.__progressbar.config(length=55) self.__finishedwavbar = Progressbar(progfrm, orient='horizontal', variable=self.__finishedwav) self.__finishedwavbar.pack(side='left') self.__finishedwavbar.config(length=30) self.name = 'Generate' self.getparams = None self.__stopflag = False def _on_solve_click(self): params = self.__topwin.parameter_group.get_parameters() repeat_times = self.__num.get_int() if self.__parallel_checker_variable.get(): run = self.__topwin.current_algorithm.process_run else: run = self.__topwin.current_algorithm.thread_run with code_printer(): run(on_finished=['store', 'plot'], progress_indicator='progress_dialog', repeat_times=repeat_times, **params) def _on_stop_button_click(self): self.__stopflag = True def _on_parallel_checker_click(self): topwin = self.__topwin if topwin.current_algorithm.need_cuda: self.__parallel_checker_variable.set(0) topwin.root_node.gui.dialogs.report(f'''{topwin.node_path}: Current algorithm "{topwin.current_algorithm.meta.name}" need CUDA worker, which does not support multi-cpu parallel. ''') def _cancel_parallel(self): self.__parallel_checker_variable.set(0)
for i in range(len(data) - 1 - 10, len(data), 1): x0 = (ctr) * x_stretch + (ctr) * x_width + x_gap y0 = 220 - (data[i] * y_stretch + y_gap) x1 = ctr * x_stretch + ctr * x_width + x_width + x_gap y1 = 220 - y_gap c.create_rectangle(x0 - 18, y0, x1 - 18, y1, fill="#ff8f00") c.create_text(x0 - 15, y0, anchor='sw', text=str(int(data[i])), font=("Purisa", 18), fill='white') ctr = ctr + 1 #progress-bar bar = Progressbar(length=390, style='orange.Horizontal.TProgressbar') bar.grid(row=5, column=1, columnspan=3, pady=10, padx=10, sticky=E + W + N + S) bar['value'] = 30 #label on progress bar label = Label(root, text=str(int(bar['value'])) + "%", style='transp.TLabel') label.grid(row=5, column=2, pady=10, padx=10, sticky=W) #Button that submits the weight weightButton = Button(root, text="Submit Weight", style='orange.TButton') weightButton.grid(row=2, column=1) #Type your weight here weightEntry = Entry(root, width=15,
class Window(Frame): def __init__(self, root=None): Frame.__init__(self, root) self.root = root self.root.title("Torrent") # ---- costanti controllo posizione ---- self.larg_bottoni = 8 self.imb_x = "3m" self.imb_y = "2m" self.imb_int_x = "3" self.imb_int_y = "1m" # ---- fine costanti di posizionamento --- self.pack(fill=BOTH, expand=1) self.createWidgets() self.file_aggiunti = [] def createWidgets(self): ## creazione di un menu e sua aggiunta ## menu = Menu(self.root) # self.root.config(menu=menu) ## creazione di un oggetto file ## file = Menu(menu) ## associazione azione all'oggetto ## file.add_command(label="Exit", command=self.client_exit) ## aggiunta del file al menu ## menu.add_cascade(label="File", menu=file) ## quadro gestione tracker self.quadro_tracker = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_tracker.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro login logout self.quadro_login = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_login.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro centrale della ricerca self.quadro_centrale_ricerca = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_centrale_ricerca.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro centrale della ricerca self.quadro_centrale_file = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_centrale_file.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ## quadro con file caricati self.quadro_console = Frame(self, background="white", borderwidth=0, relief=RIDGE) self.quadro_console.pack(side=TOP, fill=BOTH, ipadx=self.imb_int_x, ipady=self.imb_int_y) ##----------------quadro modifica del tracker------------------------ self.lb_tracker_ip4 = Label(self.quadro_tracker, text='IPv4 Tracker', background="white") self.lb_tracker_ip4.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.tracker_ip4 = StringVar() self.en_tracker_ip4 = Entry(self.quadro_tracker, textvariable=self.tracker_ip4, width=15) self.en_tracker_ip4.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.tracker_ip4.set(Utility.IPv4_TRACKER) self.lb_tracker_ip6 = Label(self.quadro_tracker, text='IPv6 Tracker', background="white") self.lb_tracker_ip6.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.tracker_ip6 = StringVar() self.en_tracker_ip6 = Entry(self.quadro_tracker, textvariable=self.tracker_ip6, width=35) self.en_tracker_ip6.pack(side=LEFT, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.tracker_ip6.set(Utility.IPv6_TRACKER) self.btn_tracker_config = Button(self.quadro_tracker, command=self.btn_conferma_config_click) self.btn_tracker_config.config(text="Conferma", width=self.larg_bottoni) self.btn_tracker_config.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y) ## ---------------aggiunta dei pulsanti di login e logout------------ self.btn_login = Button(self.quadro_login, command=self.btn_login_click) self.btn_login.configure(text="LOGIN", width=self.larg_bottoni) self.btn_login.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.btn_logout = Button(self.quadro_login, command=self.btn_logout_click) self.btn_logout.configure(text="LOGOUT", width=self.larg_bottoni) self.btn_logout.pack(side=LEFT, padx=self.imb_x, pady=self.imb_y) self.status = StringVar() self.lb_status = Label(self.quadro_login, textvariable=self.status, background="white") self.lb_status.pack(side=RIGHT, padx=self.imb_x, pady=self.imb_y) self.status.set("STATUS") ## ------------------fine parte login logout ----------------------- ##------------ quadri di divisione della ricerca e scaricamento------------- self.quadro_sinistro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE) self.quadro_sinistro_ricerca.pack(side=LEFT, fill=BOTH, expand=1, ipadx = self.imb_int_x, ipady = self.imb_int_y, padx=self.imb_x, pady=self.imb_y) self.quadro_destro_ricerca = Frame(self.quadro_centrale_ricerca, background="white", borderwidth=0, relief=RIDGE,) self.quadro_destro_ricerca.pack(side=LEFT, fill=BOTH, expand =1, ipadx=self.imb_int_x, ipady=self.imb_int_y, padx=self.imb_x, pady=self.imb_y) ## inserimento widget di ricerca e scaricamento self.en_ricerca = Entry(self.quadro_sinistro_ricerca) self.en_ricerca.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y) self.btn_ricerca = Button(self.quadro_sinistro_ricerca, command=self.btn_ricerca_click) self.btn_ricerca.configure(text="RICERCA", width=self.larg_bottoni) self.btn_ricerca.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.var_progresso = StringVar() self.lb_progresso = Label(self.quadro_sinistro_ricerca, textvariable=self.var_progresso, background="white") self.lb_progresso.pack(fill=BOTH, side=TOP, padx=self.imb_x, pady=self.imb_y) self.var_progresso.set('Progresso Scaricamento') self.prog_scaricamento = Progressbar(self.quadro_sinistro_ricerca, orient='horizontal', mode='determinate') self.prog_scaricamento.pack(side=TOP, fill=BOTH, padx=self.imb_x, pady=self.imb_y) ## inserimento listbox dei risultati della ricerca e bottone scarica dalla selezione self.list_risultati = Listbox(self.quadro_destro_ricerca) self.list_risultati.pack(side=TOP, fill=BOTH, pady=self.imb_y) self.btn_scarica = Button(self.quadro_destro_ricerca, command=self.btn_scarica_click) self.btn_scarica.configure(text="SCARICA", width=self.larg_bottoni) self.btn_scarica.pack(side=TOP) ##--------------- fine parte della ricerca scaricamento ------------------- ##---------------- parte di aggiunta dei file ----------------------------- ## quadri di divisione per l'aggiunta self.quadro_sinistro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE) self.quadro_sinistro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y) self.quadro_destro_file = Frame(self.quadro_centrale_file, background="white", borderwidth=0, relief=RIDGE) self.quadro_destro_file.pack(side=LEFT, fill=BOTH, expand=1, ipadx=self.imb_int_x, ipady=self.imb_int_y,padx=self.imb_x, pady=self.imb_y) self.lb_file = Label(self.quadro_sinistro_file, text='Gestione dei File', background="white") self.lb_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.btn_aggiungi_file = Button(self.quadro_sinistro_file, command=self.btn_aggiungi_file_click) self.btn_aggiungi_file.configure(text="AGGIUNGI", width=self.larg_bottoni) self.btn_aggiungi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.btn_rimuovi_file = Button(self.quadro_sinistro_file, command=self.btn_rimuovi_file_click) self.btn_rimuovi_file.configure(text="RIMUOVI", width=self.larg_bottoni) self.btn_rimuovi_file.pack(side=TOP, padx=self.imb_x, pady=self.imb_y) self.list_file = Listbox(self.quadro_destro_file) self.list_file.pack(side=TOP, fill=BOTH, pady=self.imb_y) ##---------------- fine parte gestione dei file --------------------------- ##---------------- parte di console per le scritture eventuali------------- self.text_console = Text(self.quadro_console, state=NORMAL) self.text_console.pack(side=TOP, fill=BOTH) ##---------------- fine della parte di console ---------------------------- def btn_conferma_config_click(self): Utility.IPv4_TRACKER = self.tracker_ip4.get() Utility.IPv6_TRACKER = self.tracker_ip6.get() Utility.IP_TRACKER = Utility.IPv4_TRACKER + "|" + Utility.IPv6_TRACKER self.print_console('aggiornamento tracker ip4: ' + self.tracker_ip4.get()) self.print_console('aggiornamento tracker ip6: ' + self.tracker_ip6.get()) def print_console(self, mess): self.text_console.insert(END,mess+'\n') ## evento bottone connessione def btn_login_click(self): try: sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER) Request.login(sock_end) Utility.sessionID = Response.login_ack(sock_end) Response.close_socket(sock_end) # creazione della cartella temporanea try: os.stat(Utility.PATHTEMP) shutil.rmtree(Utility.PATHTEMP) except FileNotFoundError as e: pass finally: os.mkdir(Utility.PATHTEMP) if Utility.sessionID != None: self.status.set("SEI LOGGATO come " + Utility.sessionID) self.print_console('LOGIN effettuato a ' + Utility.IP_TRACKER) else: self.status.set('SEI DISCONNESSO') self.print_console("LOGIN fallita") except Exception as e: logging.debug(e) ## evento bottone disconnessione def btn_logout_click(self): try: sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER) Request.logout(sock_end) success, n_part = Response.logout_ack(sock_end) Response.close_socket(sock_end) # se si e' sconnesso if success: self.status.set('DISCONNESSO - PARTI POSSEDUTE: ' + n_part) logging.debug('DISCONNESSO - PARTI POSSEDUTE: ' + n_part) ## si rimuove la cartella temporanea, i file ## e le parti dal database associate Utility.database.removeAllFileForSessionId(Utility.sessionID) Utility.sessionID = '' ## aggionamento lista con le rimozioni self.file_aggiunti.clear() self.list_file.delete(0,END) try: shutil.rmtree(Utility.PATHTEMP) except Exception as e: logging.debug('cartella non esistente') ## altrimenti rimane connesso else: self.status.set('FALLIMENTO DISCONNESSIONE - PARTI SCARICATE: ' + n_part) logging.debug('Disconnessione non consentita hai della parti non scaricate da altri') self.print_console('Disconnessione non consentita hai della parti non scaricate da altri') except Exception as e: logging.debug(e) def btn_aggiungi_file_click(self): if Utility.sessionID != '': path_file = askopenfilename(initialdir=Utility.PATHDIR) # controllo se il database ha gia' il file if path_file != '': result = Utility.database.findFile(Utility.sessionID, Utility.generateMd5(path_file), None, 1) if len(result) == 0: sock_end = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER) Request.add_file(sock_end, path_file) num_parts = Response.add_file_ack(sock_end) Response.close_socket(sock_end) if num_parts != None: md5_file = Utility.generateMd5(path_file) file_name = path_file.split('/')[-1] elem = (md5_file, file_name, num_parts) ## aggiornamento database ocn l'aggiunta del file e delle parti Utility.database.addFile(Utility.sessionID, file_name, md5_file, os.stat(path_file).st_size,Utility.LEN_PART) Utility.database.addPart(md5_file, Utility.sessionID, '1' * int(num_parts)) Divide.Divider.divide(Utility.PATHDIR, Utility.PATHTEMP, file_name, Utility.LEN_PART) self.file_aggiunti.append(elem) self.list_file.insert(END, file_name) self.print_console('elemento aggiunto: ' + str(elem)) logging.debug('aggiunto: ' + path_file) else: self.print_console('file già presente nella condivisione') else: self.print_console('file non selezionato') else: self.print_console('Non puoi aggiungere se non sei connesso al tracker') def btn_ricerca_click(self): try: if Utility.sessionID!= '': logging.debug("STAI CERCANDO: " + self.en_ricerca.get()) # prendo il campo di ricerca serch=self.en_ricerca.get().strip(' ') # Creo la socket di connessione al tracker sock = Request.create_socket(Utility.IP_TRACKER, Utility.PORT_TRACKER) # Invio richiesta look Request.look(sock, Utility.sessionID, serch) # Azzero la ricerca precedente Utility.listLastSearch=[] # Rimuovo la lista dei file scaricati self.list_risultati.delete(0,END) # Leggo la ALOO # Popolo la lista globale con i risultati dell'ultima ricerca self.risultati,Utility.listLastSearch = Response.look_ack(sock) Response.close_socket(sock) # inserisco tutti gli elementi della lista nella lista nel form for value in self.risultati: self.list_risultati.insert(END, value[1]) else: self.print_console('Non puoi ricercare se non sei collegato') except Exception as e: logging.debug(e) def btn_scarica_click(self): try: # Todo da testare in locale prima # indice elemento da scaricare index = self.list_risultati.curselection()[0] logging.debug("selezionato: " + str(self.risultati[index])) # prendo l'elemento da scaricare info = Utility.listLastSearch[index] #Classe che esegue il download di un file md5_selected = self.risultati[index][0] result = Utility.database.findFile(Utility.sessionID, md5_selected, None, 1) if len(result) == 0: down=Scaricamento(self.prog_scaricamento, self.var_progresso, self.file_aggiunti, self.list_file, info) down.start() else: self.print_console('hai già questo file! ') except Exception as e: logging.debug("NULLA SELEZIONATO: " + str(e)) def btn_rimuovi_file_click(self): try: index = self.list_file.curselection()[0] del self.file_aggiunti[index] self.list_file.delete(index, index) logging.debug("rimosso: " + str(index)) except Exception as e: logging.debug("NULLA SELEZIONATO")
def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs); self.toForeGround ################### init, main config ###################### container = Frame(self, bg=bgColor); container.pack(side="top", fill="both", expand=True); self.ft1 = font.Font(family='Arial', size=11); self.ft2 = font.Font(family='MS Gothic', size=10); self.ft3 = font.Font(family='Arial', size=9); self.ft4 = font.Font(family='Arial', size=10); self.ft5 = font.Font(family='Arial', size=14); self.ft6 = font.Font(family="Courier", size = 9); self.p1 = Page1(container, bg=container["background"]); self.p2 = Page2(container, bg=container["background"]); self.p3 = Page3(container, bg=container["background"]); self.p4 = Page4(container, bg=container["background"]); self.p5 = Page5(container, bg=container["background"]); self.p6 = Page6(container, bg=container["background"]); self.p7 = Page7(container, bg=container["background"]); self.p8 = Page8(container, bg=container["background"]); self.p9 = Page9(container, bg=container["background"]); topBar = Frame(container, bg=topBarColor, width=container.winfo_width() * framewidth, height=topBarHeight); topBar.place(x=0, y=0); self.p1.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p2.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p3.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p4.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p5.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p6.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p7.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p8.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); self.p9.place(in_=container, x=0, y= topBar["height"], relwidth=1, relheight=1); close= Button(topBar, text=u"\u2715", command= lambda: self.close(), bg=topBar["background"], bd=0, font = self.ft2, fg=fgColor, activebackground="#940000"); close.place(x = topBar["width"] - topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); minim = Button(topBar, text="_", command= lambda: self.toicon(), bg=topBar["background"], bd=0, font=self.ft2, fg=fgColor, activebackground="#364969"); minim.place(x = topBar["width"] - 2 * topBar["height"], y = 0, width = topBar["height"], height= topBar["height"]); label = Label(topBar, text=title, font=self.ft3, bg=topBar["background"], fg=fgColor); label.place(x = 5, y = 0, height= topBar["height"]); #event handlers so the window can be moved topBar.bind("<ButtonPress-1>", self.StartMove); topBar.bind("<ButtonRelease-1>", self.StopMove); topBar.bind("<B1-Motion>", self.OnMotion); label.bind("<ButtonPress-1>", self.StartMove); label.bind("<ButtonRelease-1>", self.StopMove); label.bind("<B1-Motion>", self.OnMotion); close.bind("<Enter>", self.closeEnterBG); close.bind("<Leave>", self.topBarButtonNormalBG); minim.bind("<Enter>", self.minimEnterBG); minim.bind("<Leave>", self.topBarButtonNormalBG); self.master.bind("<Unmap>", self.toiconify); self.master.bind("<Map>", self.todeiconify); ##################### page 1, intro ############################ T1 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T1.place(x=10, y=10); HelpButton = Label(self.p1, text = "help", background=bgColor, fg = hyperlinkColor, font = self.ft5, cursor="hand2"); HelpButton.place(x=8, y=53); underlineFont = font.Font(HelpButton, HelpButton.cget("font")); underlineFont.configure(underline = True); HelpButton.configure(font=underlineFont); HelpButton.bind("<Button-1>", lambda x: self.clickHelp()) T2 = Text(self.p1, height = 8, width = 31, font=self.ft5, bg=bgColor, fg=fgColor, bd=0); T2.place(x=53, y=55); T1.insert(END, "Welcome to the ELS Scorion tool. Click next to select what tool to use, or press\n"); T2.insert(END, "to learn more about the tool."); T1.configure(state=DISABLED); T2.configure(state=DISABLED); nextButtonP1 = Button(self.p1, text = "Next", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); nextButtonP1.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); nextButtonP1.bind("<Enter>", self.buttonEnterBG); nextButtonP1.bind("<Leave>", self.buttonNormalBG); ################## page 2, task picker ######################### instrLabel = Label(self.p2, text = "Choose what tool to use", bg=self.p2["background"], fg=fgColor, font=self.ft5); instrLabel.place(x= 30, y = 10); buildGroupsButton = Button(self.p2, text = "Build Scorion groups", command=self.p3.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); buildGroupsButton.place(x = 75, y = 48, width = 250, height = 2*nextprevButtonHeight); buildGroupsButton.bind("<Enter>", self.buttonEnterBG); buildGroupsButton.bind("<Leave>", self.buttonNormalBG); splitGroupsButton = Button(self.p2, text = "Split Scorion file", command=self.p4.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); splitGroupsButton.place(x = 75, y = 120, width = 250, height = 2*nextprevButtonHeight); splitGroupsButton.bind("<Enter>", self.buttonEnterBG); splitGroupsButton.bind("<Leave>", self.buttonNormalBG); onlyFileButton = Button(self.p2, text = "Only create Scorion file", command=self.p5.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); onlyFileButton.place(x = 75, y = 192, width = 250, height = 2*nextprevButtonHeight); onlyFileButton.bind("<Enter>", self.buttonEnterBG); onlyFileButton.bind("<Leave>", self.buttonNormalBG); possibleErrorButton = Button(self.p2, text = "Find errors in file", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft5, activebackground=buttonPressedColor, activeforeground=fgColor); possibleErrorButton.place(x = 75, y = 264, width = 250, height = 2*nextprevButtonHeight); possibleErrorButton.bind("<Enter>", self.buttonEnterBG); possibleErrorButton.bind("<Leave>", self.buttonNormalBG); previousButtonP2 = Button(self.p2, text = "Back", command=self.p1.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP2.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP2.bind("<Enter>", self.buttonEnterBG); previousButtonP2.bind("<Leave>", self.buttonNormalBG); ################## page 3, group builder ######################## previousButtonP3 = Button(self.p3, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP3.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP3.bind("<Enter>", self.buttonEnterBG); previousButtonP3.bind("<Leave>", self.buttonNormalBG); courseIdWrap = Frame(self.p3, bg= self.p3["background"]); courseIdWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar = StringVar(); self.courseVar.trace("w", lambda name, index, mode, courseVar=self.courseVar: self.firecallback()); courseIdLabel = Label(courseIdWrap, text = "Course Id:", bg=self.p3["background"], fg=fgColor, font=self.ft4); courseIdLabel.place(x= 0, y = 0, height = topBarHeight); courseId = Entry(courseIdWrap, width= 45, bg=bg2Color, textvariable=self.courseVar,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId.place(x = 65, y = 0, height=topBarHeight); fileWrap = Frame(self.p3, bg =self.p3["background"]); fileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel = Label(fileWrap, text = "File:", bg=self.p3["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 30, y = 0, height = topBarHeight); self.fileVar = StringVar(); self.fileVar.trace("w", lambda name, index, mode, fileVar=self.fileVar: self.firecallback()); self.fileName = Entry(fileWrap, width= 36, textvariable=self.fileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName.place(x = 65, y = 0, height= topBarHeight); #TODO: drag files into the text field self.browse = Button(fileWrap, text="Browse", command=self.load_file, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse.place(x=326, y=0, height = topBarHeight, width=60); self.browse.bind("<Enter>", self.buttonEnterBG); self.browse.bind("<Leave>", self.buttonNormalBG); seperatorWrap = Frame(self.p3, bg = self.p3["background"]); seperatorWrap.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel = Label(seperatorWrap, text="What seperator is used in the file?", bg=self.p3["background"], fg=fgColor, font=self.ft4); optionLabel.place(x = 0, y = 0, height = topBarHeight); optionList = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar = StringVar(); self.sepVar.set(optionList[0][1]); commaButton = Radiobutton(seperatorWrap, text=optionList[0][0], variable = self.sepVar, value=optionList[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton = Radiobutton(seperatorWrap, text=optionList[1][0], variable = self.sepVar, value=optionList[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton.place(x=260, y = topBarHeight + 2, width = 120); optionLabel = Label(self.p3, text="Do you already have a Scorion File?"); scorionCheckWrap = Frame(self.p3, bg = self.p3["background"]); scorionCheckWrap.place(x=10, y = 194, height=topBarHeight, width = framewidth - 20); self.checkVar = IntVar(); scorionCheck = Checkbutton(scorionCheckWrap, text="Create a Scorion file?", var = self.checkVar, font=self.ft4, fg=fgColor, bg=bg2Color, bd=0, highlightthickness = 0, selectcolor=bg2Color, activeforeground=fgColor, activebackground= bg2Color); scorionCheck.select(); scorionCheck.place(x=210, y=0, height=topBarHeight, width = 170); self.goButton = Button(self.p3, text = "Run", command=self.combineFuncs, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButton.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 4, split groups page ######################## previousButtonP4 = Button(self.p4, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP4.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP4.bind("<Enter>", self.buttonEnterBG); previousButtonP4.bind("<Leave>", self.buttonNormalBG); scorFileWrap = Frame(self.p4, bg =self.p4["background"]); scorFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight); fileLabel = Label(scorFileWrap, text = "Scorion File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); fileLabel.place(x= 0, y = 0, height = topBarHeight); self.scorFileVar = StringVar(); self.scorFileVar.trace("w", lambda name, index, mode, scorFileVar=self.scorFileVar: self.firecallback1()); self.scorFileName = Entry(scorFileWrap, width= 34, textvariable=self.scorFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.scorFileName.place(x = 79, y = 0, height= topBarHeight); self.browse1 = Button(scorFileWrap, text="Browse", command=self.load_file1, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse1.place(x=326, y=0, height = topBarHeight, width=60); self.browse1.bind("<Enter>", self.buttonEnterBG); self.browse1.bind("<Leave>", self.buttonNormalBG); errFileWrap = Frame(self.p4, bg =self.p4["background"]); errFileWrap.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); errLabel = Label(errFileWrap, text = "Error File:", bg=self.p4["background"], fg=fgColor, font=self.ft4); errLabel.place(x= 0, y = 0, height = topBarHeight); self.errFileVar = StringVar(); self.errFileVar.trace("w", lambda name, index, mode, errFileVar=self.errFileVar: self.firecallback1()); self.errFileName = Entry(errFileWrap, width= 36, textvariable=self.errFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.errFileName.place(x = 65, y = 0, height= topBarHeight); self.browse2 = Button(errFileWrap, text="Browse", command=self.load_file2, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse2.place(x=326, y=0, height = topBarHeight, width=60); self.browse2.bind("<Enter>", self.buttonEnterBG); self.browse2.bind("<Leave>", self.buttonNormalBG); self.goButtonP4 = Button(self.p4, text = "Run", command=self.combineFuncs2, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP4.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 5, only create groups page ################## previousButtonP5 = Button(self.p5, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP5.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP5.bind("<Enter>", self.buttonEnterBG); previousButtonP5.bind("<Leave>", self.buttonNormalBG); courseIdWrap2 = Frame(self.p5, bg= self.p5["background"]); courseIdWrap2.place(x = 10, y = 10, width = framewidth - 20, height = topBarHeight) self.courseVar2 = StringVar(); self.courseVar2.trace("w", lambda name, index, mode, courseVar2=self.courseVar2: self.firecallback2()); courseIdLabel2 = Label(courseIdWrap2, text = "Course Id:", bg=self.p5["background"], fg=fgColor, font=self.ft4); courseIdLabel2.place(x= 0, y = 0, height = topBarHeight); courseId2 = Entry(courseIdWrap2, width= 45, bg=bg2Color, textvariable=self.courseVar2,fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); courseId2.place(x = 65, y = 0, height=topBarHeight); fileWrap2 = Frame(self.p5, bg =self.p5["background"]); fileWrap2.place(x = 10, y = 44, width = framewidth - 20, height = topBarHeight); fileLabel2 = Label(fileWrap2, text = "File:", bg=self.p5["background"], fg=fgColor, font=self.ft4); fileLabel2.place(x= 30, y = 0, height = topBarHeight); self.fileVar2 = StringVar(); self.fileVar2.trace("w", lambda name, index, mode, fileVar2=self.fileVar2: self.firecallback2()); self.fileName2 = Entry(fileWrap2, width= 36, textvariable=self.fileVar2,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.fileName2.place(x = 65, y = 0, height= topBarHeight); self.browse3 = Button(fileWrap2, text="Browse", command=self.load_file3, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse3.place(x=326, y=0, height = topBarHeight, width=60); self.browse3.bind("<Enter>", self.buttonEnterBG); self.browse3.bind("<Leave>", self.buttonNormalBG); seperatorWrap2 = Frame(self.p5, bg = self.p5["background"]); seperatorWrap2.place(x=10, y = 106, height = 2*topBarHeight + 2, width = framewidth - 20); optionLabel2 = Label(seperatorWrap2, text="What seperator is used in the file?", bg=self.p5["background"], fg=fgColor, font=self.ft4); optionLabel2.place(x = 0, y = 0, height = topBarHeight); optionList2 = [("Comma ( , )", ","),("Semicolon ( ; )", ";")]; self.sepVar2 = StringVar(); self.sepVar2.set(optionList2[0][1]); commaButton2 = Radiobutton(seperatorWrap2, text=optionList2[0][0], variable = self.sepVar2, value=optionList2[0][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); semiColonButton2 = Radiobutton(seperatorWrap2, text=optionList2[1][0], variable = self.sepVar2, value=optionList2[1][1], anchor="w", padx=5, bg=bg2Color, fg=fgColor, activebackground=bg2Color, activeforeground=fgColor, selectcolor=bg2Color); commaButton2.place(x=260, y=0, height=topBarHeight, width = 120); semiColonButton2.place(x=260, y = topBarHeight + 2, width = 120); self.goButtonP5 = Button(self.p5, text = "Run", command=self.combineFuncs3, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP5.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 6, progress page ########################### self.cancelButton = Button(self.p6, text = "cancel", command=lambda:sys.exit(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.cancelButton.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.cancelButton.bind("<Enter>", self.buttonEnterBG); self.cancelButton.bind("<Leave>", self.buttonNormalBG); self.progressLabel = Label(self.p6, text = "Working, this might take a couple of minutes...", bg=self.p6["background"], fg=fgColor, font=self.ft1) self.progressLabel.place(x=10, y=36); #TODO: make the progressbar actually progress to the things that are done style = Style(); style.theme_use('alt') style.configure("els.Horizontal.TProgressbar", background=fgColor); self.progress = Progressbar(self.p6, orient=HORIZONTAL, length = framewidth - 20, mode="indeterminate", style="els.Horizontal.TProgressbar", maximum=40); self.progress.place(x=10, y=10); self.progress.start(17); self.closeP6 = Button(self.p6, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); ################### page 7, error page ########################### #TODO: implement full stacktrace instead of only 2 #TODO: or: make a log file of the stacktrace that can be "downloaded" when clicked #TODO: error page is not working correctly anymore; errors are being cut off self.errorLabel = Label(self.p7, text = "Something went wrong, try again or contact Cas", bg=self.p7["background"], fg=errorColor, font=self.ft1); self.errorLabel.place(x=36, y=10); self.errorInfoLabel = Label(self.p7, text = "Error Info:", bg=self.p7["background"], fg=fgColor, font=self.ft1); self.errorInfoLabel.place(x=36, y=50); self.stackTraceStringVar1 = StringVar(); self.stackTraceStringVar2 = StringVar(); self.stackTraceLabel1 = Label(self.p7, textvariable = self.stackTraceStringVar1, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceLabel2 = Label(self.p7, textvariable = self.stackTraceStringVar2, bg=self.p7["background"], fg=errorColor, font=self.ft1, wraplength = 350, justify=LEFT); self.stackTraceStringVar1.set(self.getStackTrace()[0]); self.stackTraceStringVar2.set(self.getStackTrace()[1]); self.stackTraceLabel1.place(x=36, y=70); self.stackTraceLabel2.place(x=36, y=110); self.backToMenu = Button(self.p7, text = "Back to menu", command=self.backtomenu, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.backToMenu.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.backToMenu.bind("<Enter>", self.buttonEnterBG); self.backToMenu.bind("<Leave>", self.buttonNormalBG); self.closeP7 = Button(self.p7, text = "Close", command=self.close, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); self.closeP7.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); self.closeP7.bind("<Enter>", self.buttonEnterBG); self.closeP7.bind("<Leave>", self.buttonNormalBG); ################### page 8, find error page ########################### previousButtonP8 = Button(self.p8, text = "Back", command=self.p2.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP8.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP8.bind("<Enter>", self.buttonEnterBG); previousButtonP8.bind("<Leave>", self.buttonNormalBG); checkErrFileWrap = Frame(self.p8, bg =self.p8["background"]); checkErrFileWrap.place(x = 10, y = 10, width = framewidth - 20, height = 3*topBarHeight); checkErrLabel = Label(checkErrFileWrap, text = "File to check for Errors:", bg=self.p4["background"], fg=fgColor, font=self.ft4); checkErrLabel.place(x= 0, y = 0, height = topBarHeight); self.checkErrFileVar = StringVar(); self.checkErrFileVar.trace("w", lambda name, index, mode, checkErrFileVar=self.checkErrFileVar: self.firecallback3()); self.checkErrFileName = Entry(checkErrFileWrap, width= 45, textvariable=self.checkErrFileVar,bg=bg2Color, fg=fgColor, borderwidth = 0, font=self.ft4, insertbackground=fgColor, insertofftime= 500, insertontime= 500); self.checkErrFileName.place(x = 2, y = 25, height= topBarHeight); self.browse4 = Button(checkErrFileWrap, text="Browse", command=self.load_file4, background=buttonColor, foreground=fgColor, bd=0, font=self.ft4, activebackground=buttonPressedColor, activeforeground=fgColor, anchor="center"); self.browse4.place(x=326, y=25, height = topBarHeight, width=60); self.browse4.bind("<Enter>", self.buttonEnterBG); self.browse4.bind("<Leave>", self.buttonNormalBG); self.goButtonP8 = Button(self.p8, text = "Run", command=self.p9.lift, state=DISABLED,background=disabledButtonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=disabledButtonColor, activeforeground=fgColor, disabledforeground=fg2Color); self.goButtonP8.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); ################### page 9, find error results ########################### previousButtonP9 = Button(self.p9, text = "Back", command=self.p8.lift, background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); previousButtonP9.place(x = nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); previousButtonP9.bind("<Enter>", self.buttonEnterBG); previousButtonP9.bind("<Leave>", self.buttonNormalBG); #testing self.checkErrFileName.delete(0, END); self.checkErrFileName.insert(0, r"M:\ud\os\ssc\imos\bbsup\@ new folder_Surfdrive\7. Scorion\Vakmappen 171804\46597-171804\group_import_no_TAs.txt"); self.errors = errorChecker(self.checkErrFileVar.get()); self.croppedErrors = self.errors[0:7] if (len(self.errors) > 0): Label(self.p9, text = "Found %d possible errors, on the following lines:" %len(self.errors), fg = fgColor, bg = bgColor, font = self.ft1).place(x=16, y=12); openFile = Button(self.p9, text = "Open file", command=lambda: self.clickOpenFile(), background=buttonColor, foreground=fgColor, bd=0, font=self.ft1, activebackground=buttonPressedColor, activeforeground=fgColor); openFile.place(x = framewidth - nextprevButtonWidth - nextprevButtonPaddingX, y = frameheight - nextprevButtonHeight - nextprevButtonPaddingY, width = nextprevButtonWidth, height = nextprevButtonHeight); openFile.bind("<Enter>", self.buttonEnterBG); openFile.bind("<Leave>", self.buttonNormalBG); self.drawErrors(); else: Label(self.p9, text = "Found no errors", fg = fgColor, bg = bgColor, font = self.ft5).place(x=10, y=10); ################### finally, show page 1 to start ################ self.p1.show();
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 Surprisecortexfile(self): top = Toplevel(self) top.grab_set() top.title("BCOT") top.wm_iconbitmap('logo.ico') progress = Progressbar(top, orient=HORIZONTAL, length=100, mode='determinate') progress.pack(pady=10) progress['value'] = 0 width_of_window = 250 height_of_window = 100 screen_width = top.winfo_screenwidth() screen_height = top.winfo_screenheight() x_coordinate = (screen_width / 2) - (width_of_window / 2) y_coordinate = (screen_height / 2) - (height_of_window / 2) top.geometry( "%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate)) url = "wss://localhost:6868" user = { "license": "", "client_id": "", "client_secret": "", "debit": 100, "number_row_data": 10 } self.cortex = Cortex(url, user, debug_mode=True) self.headset_id = self.cortex.query_headset() self.cortex.connect_headset() self.cortex.request_access() auth = self.cortex.authorize() self.cortex.create_session(auth, self.headset_id) profile_name = 'shreyas' training_action = 'surprise' number_of_train = 5 stream = ['sys'] self.cortex.sub_request(stream) profiles = self.cortex.queryProfile() # if self.profile_name not in profiles: # status = 'create' # self.cortex.setup_profile(self.profile_name, status) status = 'load' self.cortex.setup_profile(profile_name, status) print('begin train -----------------------------------') num_train = 0 while num_train < number_of_train: num_train = num_train + 1 progress['value'] = 20 + progress['value'] top.update_idletasks() time.sleep(1) print('start training {0} time {1} ---------------'.format( training_action, num_train)) print('\n') status = 'start' self.cortex.train_request(detection='facialExpression', action=training_action, status=status) print('accept {0} time {1} ---------------'.format( training_action, num_train)) print('\n') status = 'accept' self.cortex.train_request(detection='facialExpression', action=training_action, status=status) if num_train == 5: self.surpriseReleased() print('save trained action') status = "save" self.cortex.setup_profile(profile_name, status) status = 'unload' self.cortex.setup_profile(profile_name, status) self.cortex.close_session() w = Label(top, text="SURPRISE TRAINING COMPLETED", font=("Helvetica", 10)) w.pack() Button(top, width=10, height=2, text='ok', command=lambda win=top: win.destroy()).pack(pady=10) top.grab_release() sys.exit( ) # this helps in the binding the thread with daemon and kill the thread using dameon when the frame is closed
class AppGUI(Frame): def __init__(self, master=None): # Avoiding to send it continuously. self.lock = False Frame.__init__(self, master) self.grid() self.master = master # Setting for ComboBox. self.url_lang_combobox_str = StringVar() self.url_lang_combobox_list = lang_list # UI components. self.receiver_email_text = Label(self, text="Receiver:") self.receiver_email_field = Entry(self, width=50) self.subject_text = Label(self, text='Subject:') self.subject_field = Entry(self, width=50) self.receiver_name_text = Label(self, text='Name:') self.receiver_name_field = Entry(self, width=50) self.url_lang_text = Label(self, text='Link lang:') self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly') self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300) self.send_button = Button(self, text='Send', command=self._send_mail) self.quit_button = Button(self, text='Exit', command=self.__exit) self.log_msg_text = ScrolledText(self) # Attachment. self.mail_attachment_list = attachment_list[:] self.url_lang_link_title = None self.url_lang_link = copy.deepcopy(content_link) # Mailer self._mailer = None # Let Mailer can control components. Mailer.window_content = self self.__create_widgets() def _send_mail(self): if not self.lock: threading.Thread(target=self.__send_mail).start() else: messagebox.showinfo('Warning', "Now it's processing...") def _choose(self, event): # arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) # Get the array by choosing language. pass def _modify_content_url_link(self): link_arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) content = self._mailer.content for index in range(len(link_arr)): content_index = content.index(self.url_lang_link_title[index]) + len(self.url_lang_link_title[index]) content = content[:content_index] + '\n' + link_arr[index] + content[content_index:] self._mailer.content = content return False def _make_mailer(self): self.mail_attachment_list = attachment_list[:] # Clone a list. if atta_lang_list[self.url_lang_combobox.current()]: for i in range(len(self.mail_attachment_list)): # Only from the third file to the end file can change language. if i > 2: # Modify the file name. att = self.mail_attachment_list[i].split('.') self.mail_attachment_list[i] = ''.join([' ', atta_lang_list[self.url_lang_combobox.current()], '.']).join(att) # ** IMPORTANT, we set the content path here!! path = 'content.docx' if self.url_lang_combobox.get() == lang_list[2] or self.url_lang_combobox.get() == lang_list[3]: path = 'content chinese.docx' if debug_log: print(self.mail_attachment_list) # ** IMPORTANT, we have to new an object here. Otherwise, we couldn't check the error checking. return Mailer(content_path=path, attachment_list=self.mail_attachment_list) def __create_widgets(self): """ Construct all of the UI components. """ self.receiver_email_text.grid(row=0, column=0) self.receiver_email_field.grid(row=0, column=1, columnspan=6) self.subject_text.grid(row=1, column=0) self.subject_field.grid(row=1, column=1, columnspan=6) self.subject_field.insert(0, 'Osaka Mariko Apartment Location & Condition') self.receiver_name_text.grid(row=2, column=0) self.receiver_name_field.grid(row=2, column=1, columnspan=6) self.url_lang_text.grid(row=3, column=0) self.url_lang_combobox.grid(row=3, column=2, columnspan=2) self.send_progressbar.grid(row=4, column=0, columnspan=7) self.send_button.grid(row=5, column=2) self.quit_button.grid(row=5, column=3) self.log_msg_text.grid(row=6, column=0, columnspan=7) # Default setting. self.url_lang_combobox.current(0) self.url_lang_combobox.bind("<<ComboboxSelected>>", self._choose) def __exit(self): if not self.lock: self.log_msg_text.insert(END, '\n\n -- Bye Bye --\n') self.master.quit() else: messagebox.showinfo('Error', "Now it's processing...please wait it ;)") @DecoratorThreadLockerApp() @DecoratorErrorCheckAndInitApp() def __send_mail(self): self.send_progressbar.start() # Start processing the progress. ending = 'Welcome to use my application :)' if self._mailer.send_mail() \ else '** Your sending was failed :( please send it again!' self.log_msg_text.insert(END, ending) self.send_progressbar.stop() # Stop processing the progress.
def loadDataPage(): #window loadingPage = Tk() loadingPage.title('Data Collection Page') loadingPage.geometry('385x105') loadingPage.config(bg=DARK_BLUE) loadingPage.wm_iconbitmap('images/mercuryLogoIcon.ico') #window label titleLabel = Label(loadingPage, text="Loading Data...", font=("Times New Roman Bold", 14), bg=BRIGHT_ORANGE, fg='black') #create object titleLabel.grid(column=0, row=0, padx=12, pady=10) #progress bar loadingBar = Progressbar(loadingPage, length=300) loadingBar.grid(column=0, row=1, padx=12, pady=10) def bar(): import backendFunctions as bf from time import sleep loadingBar['value'] = 20 if bf.user_signed_in(usersWebsite, username, password): sleep(1) loadingBar['value'] = 50 dict_main = bf.readDataToDictionary() #makes and saves df if len(dict_main) != 0: sleep(1) loadingBar['value'] = 80 df = pd.DataFrame(dict_main) #pre analysis setup: for attribute in df.columns: if attribute not in ['Ticker', 'Company Name']: df[attribute] = df[attribute].str.replace( ',', '').str.replace("M", '').str.replace( "%", '').str.replace('+', '').astype(float) df['1yr Est Profit'] = df['1yr Est'] - df['Last Price'] df['1yr Est %Gain'] = df['1yr Est'] / df['Last Price'] - 1 pd.options.display.float_format = "{:,.2f}".format df.to_csv(filePath) def loadTotalInvested(): totalInvested = bf.getTotalInvested() with open('data/totalInvestedData.txt', 'w') as file1: file1.write(totalInvested) loadTotalInvested() #updates previously loaded only if data loaded successfully with open('data/previouslyLoaded.txt', 'w') as file1: file1.write("Data Has Been Previously Loaded") loadingPage.destroy() portfolioPage(df) else: # loadingPage.destroy() messagebox.askretrycancel("Data Loading Error.", "Data Collection Failed.") else: # loadingPage.destroy() messagebox.askretrycancel("Sign in Error", "Data Collection Failed.") bar()
def __init__(self): self.results = {} self.num_photos_to_delete = 0 self.root = Tk() self.root.title('Duplicates finder') self.root.attributes('-fullscreen', True) # create all of the main containers self.frame_header1 = Frame(self.root, padx=15, pady=5, bg=self.COLOR_FRAMES1) self.frame_header2 = Frame(self.root, padx=15, pady=5, bg=self.COLOR_FRAMES1) self.frame_center = Frame(self.root) self.frame_bottom = Frame(self.root, padx=15, pady=15, bg=self.COLOR_FRAMES1) # layout all of the main containers self.root.grid_rowconfigure(2, weight=1) self.root.grid_columnconfigure(0, weight=1) self.frame_header1.grid(row=0, sticky="ew") self.frame_header2.grid(row=1, sticky="ew") self.frame_center.grid(row=2, sticky="nsew") self.frame_bottom.grid(row=3, sticky="ew") # widgets frame_header1 self.frame_header1.grid_columnconfigure(1, weight=1) self.label_title = Label(self.frame_header1, text='DUPLICATES FINDER', font="-weight bold", bg=self.COLOR_FRAMES1) self.label_title.grid(row=0, column=0) self.folder_path = StringVar() self.label_folder = Entry(self.frame_header1, state='disabled', width=40, textvariable=self.folder_path, highlightbackground=self.COLOR_FRAMES1) self.label_folder.grid(row=0, column=2) self.btn_browse_folder = Button(self.frame_header1, text="Choose folder", command=self.action_browse, highlightbackground=self.COLOR_FRAMES1) self.btn_browse_folder.grid(row=0, column=3, padx=(5, 50)) self.btn_scan = Button(self.frame_header1, text="Scan", command=self.action_scan, state='disabled', highlightbackground=self.COLOR_FRAMES1) self.btn_scan.grid(row=0, column=4) # widgets frame_header1 self.prgs_bar = Progressbar(self.frame_header2) self.prgs_bar.grid(row=0, column=0) self.prgs_bar.pack(expand=True, fill='both') # widgets frame_bottom self.frame_bottom.grid_columnconfigure(2, weight=1) self.label_delete_num = Label(self.frame_bottom, text='0', bg=self.COLOR_FRAMES1) self.label_delete_num.grid(row=0, column=0) self.label_delete_str = Label(self.frame_bottom, text='photos to delete', bg=self.COLOR_FRAMES1) self.label_delete_str.grid(row=0, column=1) self.btn_delete_photos = Button(self.frame_bottom, text="Delete photos", state=DISABLED, command=self.action_delete, highlightbackground=self.COLOR_FRAMES1) self.btn_delete_photos.grid(row=0, column=3) # frames frame_center self.frame_center.grid_columnconfigure(1, weight=1) self.frame_center.grid_rowconfigure(0, weight=1) self.frame_center1 = Frame(self.frame_center, bg=self.COLOR_FRAMES2, padx=15, pady=5) self.frame_center1.grid(row=0, column=0) self.frame_center1.grid(row=0, sticky="nsew") self.frame_center2 = Frame(self.frame_center, pady=15, bg=self.COLOR_FRAMES3) self.frame_center2.grid(row=0, column=1) self.frame_center2.grid(row=0, sticky="nsew") # widgets frame_center1 self.frame_center1.grid_rowconfigure(1, weight=1) self.label_list = Label(self.frame_center1, text="Duplicates", bg=self.COLOR_FRAMES2) self.label_list.grid(row=0, column=0) self.lb_ids = [] self.lb = Listbox(self.frame_center1, font=("Courier", 12), height=600) self.lb.grid(row=1, column=0) self.lb.bind('<<ListboxSelect>>', self.onselect) self.lb.bind('1', self.toggle_photo_key) self.lb.bind('2', self.toggle_photo_key) self.lb.bind('3', self.toggle_photo_key) self.lb.bind('4', self.toggle_photo_key) self.lb.bind('5', self.toggle_photo_key) self.lb.bind('6', self.toggle_photo_key) self.lb.bind('7', self.toggle_photo_key) self.lb.bind('8', self.toggle_photo_key) self.lb.bind('9', self.toggle_photo_key) self.labels_memory = [] self.labels_img_memory = []
class MonApp(Tk): def __init__(self): super().__init__() self.btn = Button(self, text='Source', command=self.open_src) self.btn2 = Button(self, text='Destination', command=self.open_dst) self.btn3 = Button(self, text='Start', command=self.start) self.btn.grid(row=0, column=0) self.btn2.grid(row=1, column=0) self.btn3.grid(row=2, column=0) self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='determinate') self.progress['value'] = 0 self.progress.grid(row=3, column=0) # Open the source directory def open_src(self): self.filename = filedialog.askdirectory( title="Select a source directory") # Open the deestination directory def open_dst(self): self.filename2 = filedialog.askdirectory( title="Select a destination directory") # method for beginning photo processing def start(self): self.btn['state'] = 'disabled' self.btn2['state'] = 'disabled' self.btn3['state'] = 'disabled' self.progress['value'] = 0 if os.path.isdir(self.filename) and os.path.isdir(self.filename2): self.exceute(self.filename, self.filename2) self.btn['state'] = 'normal' self.btn2['state'] = 'normal' self.btn3['state'] = 'normal' def gamma_correct_lab(self, img, gamma): out = cv.cvtColor(img, cv.COLOR_BGR2LAB) out[:, :, 0] = np.power((out[:, :, 0]) / 255, (1 / gamma)) * 255 out = cv.cvtColor(out, cv.COLOR_LAB2BGR) return out # Gamma correct image (to deepen shadows/blacks) def gamma_correct(self, img, gamma): out = img.copy() out[:, :, 0] = np.power((out[:, :, 0]) / 255, (1 / gamma)) * 255 out[:, :, 1] = np.power((out[:, :, 1]) / 255, (1 / gamma)) * 255 out[:, :, 2] = np.power((out[:, :, 2]) / 255, (1 / gamma)) * 255 return out # Auto white balance based on grayworld assumption def white_balance(self, img): result = cv.cvtColor(img, cv.COLOR_BGR2LAB) avg_a = np.average(result[:, :, 1]) avg_b = np.average(result[:, :, 2]) result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, 0] / 255.0) * 1.1) result[:, :, 2] = result[:, :, 2] - ((avg_b - 128) * (result[:, :, 0] / 255.0) * 1.1) result = cv.cvtColor(result, cv.COLOR_LAB2BGR) return result # Adjust saturation given a factor def saturation_adjustment(self, img, factor): result = cv.cvtColor(img, cv.COLOR_BGR2HSV) result[:, :, 1] = result[:, :, 1] * factor result = cv.cvtColor(result, cv.COLOR_HSV2BGR) return result # Decrease the green of an image (by 5%) def reduce_green(self, im): out = im.copy() out[:, :, 1] = out[:, :, 1] * .95 return out # draw an image with detected objects def face_boxes(self, filename, result_list): data = pyplot.imread(filename) w, h = Image.open(filename).size a = w * h ax = pyplot.gca() # create each box area = 0 for result in result_list: # get box coordinates x, y, width, height = result['box'] # Calculate the area taken up by the face box area = area + ((height * width) / a) return area # Classify if the given image is a portrait def classify_portrait(self, filename): pixels = pyplot.imread(filename) # create the detector, using default weights detector = MTCNN() # detect faces in the image faces = detector.detect_faces(pixels) x = self.face_boxes(filename, faces) # If the face boxes are at least .8% of the image, it should be classiied as a portrait if x >= .008: return True else: return False # Main logic loop of the program def exceute(self, src, dst): os.chdir(src) # Get all the files in the source directory that are jpegs pics = glob.glob("./*.jpg") num_pics = len(list(pics)) i = 0 # Loop through pics for pic in pics: img = cv.imread(pic) img2 = img.copy() lst = pic.split(".jpg") # Check if the image is a portrait if self.classify_portrait(pic): os.chdir(dst) # If it is a portrait blur it more (to even out skin tones) and label it a portrait in the destination directory cv.imwrite( (lst[0] + "-EditedPortrait.jpg"), cv.GaussianBlur( self.gamma_correct( self.saturation_adjustment( self.white_balance(self.reduce_green(img2)), 1), .9), (7, 7), 0)) else: os.chdir(dst) # If it isn't a portrait edit the image accordingly cv.imwrite( (lst[0] + "-Edited.jpg"), cv.GaussianBlur( self.gamma_correct( self.saturation_adjustment( self.white_balance(self.reduce_green(img2)), 1), .9), (3, 3), 0)) os.chdir(src) i = i + 1 # Update the progressbar self.progress['value'] = round((i / num_pics) * 100) self.progress.update() return