def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) options = [ "Date", "Amount", "Account Name", "Category Name", "Description" ] self.__sort_by.set(options[0]) op = OptionMenu(frm_base, self.__sort_by, *options) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) order = ["Ascending", "Descending"] self.__order.set(order[0]) op = OptionMenu(frm_base, self.__order, *order) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) frm_date = Frame(frm_base) frm_date.pack() return frm_base
class ChooseDialog(Dialog): def __init__(self, title, prompt, options, defaultValue=None, parent=None): if not parent: parent = tkinter._default_root self.selected = None self.optionMenu = None self.prompt = prompt if not options: raise Exception("No options given") # If options is not a dict type, assume it's a list and convert it to a dict if isinstance(options, abc.Mapping): self.options = options else: self.options = {str(v): v for v in options} self.defaultValue = defaultValue Dialog.__init__(self, parent, title) def destroy(self): self.optionMenu = None self.selected = None Dialog.destroy(self) def body(self, master): self.selected = StringVar(master) w = Label(master, text=self.prompt, justify=LEFT) w.grid(row=0, padx=5, sticky=W) self.optionMenu = OptionMenu(master, self.selected, *self.options.keys()) self.optionMenu.configure() self.optionMenu.grid(row=1, padx=1, sticky=W + E) if self.defaultValue: self.selected.set(str(self.defaultValue)) return self.optionMenu def validate(self): try: result = self.getresult() except KeyError: messagebox.showwarning("Illegal value", "Invalid choice\nPlease try again", parent=self) return 0 self.result = result return 1 def getresult(self): return self.options[self.selected.get()]
def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) Label(frm_base, height="2", width="30", text="Category:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__category.set(self.__categories[0]) op = OptionMenu(frm_base, self.__category, *self.__categories) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) return frm_base
def __init__(self, controller, title: str, label: str, values: Optional[Dict] = None, buttons: Optional[Dict] = None): if values is None: values = {} if buttons is None: buttons = {"ok": {}, "cancel": {}} super().__init__(controller, title, label, buttons, allow_exit=False) self.values = values self.entry_frame = Frame(self.top, bg=self.tk_format.bg) self.entry_frame.pack(pady=(10, 20)) self.labels = {} self.entries = {} self.mins = {} self.maxes = {} for val in values: frame = Frame(self.entry_frame, bg=self.tk_format.bg) frame.pack(pady=(5, 5)) self.labels[val] = Label(frame, text="{0:>15}".format(val) + ": ", fg=self.tk_format.textcolor, bg=self.tk_format.bg) self.labels[val].pack(side=LEFT, padx=(3, 3)) if val != "Tray position": self.entries[val] = Entry( frame, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) self.entries[val].pack(side=LEFT) else: self.entries[val] = StringVar() self.entries[val].set("White reference") print(self.entries["Tray position"].get()) menu = OptionMenu( frame, self.entries[val], "{0:15}".format("White reference"), "{0:18}".format("1"), "2 ", "3 ", "4 ", "5 ", ) menu.configure(width=15, highlightbackground=self.tk_format. highlightbackgroundcolor) menu.pack() self.set_buttons(buttons)
def render(self): self.root.configure(padx=20, pady=20) self.root.title("Chrispy Address Book") self.root.iconbitmap("../favicon.ico") self.root.resizable(False, False) back_button_image = ImageTk.PhotoImage( Image.open("../Back.png").resize((70, 38)), Image.ANTIALIAS) back_button = Button(self.root, image=back_button_image) back_button.grid(row=0, column=0) title_label = Label(self.root, text="Search For A Contact", font=("Helvatica 18 bold")) title_label.grid(row=0, column=1, columnspan=4) search_by_label = Label(self.root, text="I wish to search by:", font=("Helvatica 16")) search_by_label.grid(row=1, column=1) fields = [ "Forename", "Surname", "Address Line 1", "Address Line 2", "Town/City", "County", "Country", "Postcode", "Phone Number", "Email Address" ] options_var = StringVar() options_var.set(fields[0]) search_by_dropdown = OptionMenu(self.root, options_var, *fields) search_by_dropdown.configure(font=("Helvatica 14"), width=10) search_by_dropdown.grid(row=1, column=2) search_field = Entry(self.root, font=("Helvatica 14"), width=30) search_field.grid(row=1, column=3, padx=10, pady=5) search_button = Button(self.root, text="SEARCH", font=("Helvatica 14"), width=10) search_button.grid(row=1, column=4) self.root.mainloop()
def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) accounts = self.__user.accounts_names Label(frm_base, height="2", width="30", text="Account:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__account.set(accounts[0]) op = OptionMenu(frm_base, self.__account, *accounts) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) return frm_base
def MP3PLAYING(): #Main interface which initiates the MP3 player global seek global oc2 global listofsongs global listofsongs2 global songlist global songname global len1 global time1 songname=Label(root5,textvariable=m,width=90,bg="#220047",fg="#CE9141",font=("roboto",13)) songname.place(x=-120,y=450) pygame.mixer.init() songlist=Listbox(root5,selectbackground="#CE9141",height=14,width=60,relief=GROOVE,bd=3,bg="#220047",fg="#CE9141",font=("fixedsys",10)) songlist.place(x=20,y=205) a=StringVar() a.set("Default") oc=StringVar(root5) oc.set("Select") listofsongs2.reverse() for h in listofsongs2: songlist.insert(0,h) listofsongs2.reverse() #currentsong=Label(root5,text="Current Song:",font=("georgia",15),bg="#220047",fg="#CE9141") #currentsong.place(x=230,y=500) orderofsongs=Label(root5,text="Your Playlist",font=("georgia",15),bg="#220047",fg="#CE9141") orderofsongs.place(x=40,y=170) startbutton=Button(root5,text="Start",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) startbutton.place(x=400,y=480) playnext=Button(root5,text=">>>",bg="#CE9141",relief=RAISED,fg="#220047",bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) playnext.place(x=355,y=480) playbefore=Button(root5,text="<<<",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) playbefore.place(x=190,y=480) stop=Button(root5,text="Stop",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) stop.place(x=137,y=480) pause=Button(root5,text="Pause",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) pause.place(x=237,y=480) play=Button(root5,text="Play",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) play.place(x=300,y=480) volume1=Label(root5,text="Volume",font=("georgia",11),fg="#CE9141",bg="#220047") volume1.place(x=533,y=190) selection=MP3(listofsongs[0]) len1=selection.info.length len1//=1 seek=Scale(root5,from_=0,to=len1,orient=HORIZONTAL,length=400,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=seek1) seek.place(x=100,y=530) oc1=StringVar(root5) oc1.set("Welcome"+ " "+ user11) options=["Home","Back","Close"] dropdown=OptionMenu(root5,oc1,*options,command=choice1) dropdown.configure(font=("georgia",15),fg="#220047",bg="#CE9141",activebackground="#CE9141",activeforeground="#220047") dropdown.place(x=200,y=110) oc2=StringVar(root5) oc2.set("Options") options1=["Shuffle[]","Random[?]","Delete[-]","Add[+]"] dropdown1=OptionMenu(root5,oc2,*options1,command=choice2) dropdown1.configure(text="Options",font=("georgia",10),fg="#220047",bg="#CE9141",activebackground="#220047",activeforeground="#CE9141") dropdown1.place(x=500,y=50) volume2=Scale(root5,from_=100,to=0,orient=VERTICAL,length=210,cursor="cross",bd=1,bg="#CE9141",fg="#220047",activebackground="#220047",command=volume) volume2.set(100) volume2.place(x=540,y=215) pygame.mixer.music.set_volume(100) if conditionalval==2: saveplaylist=Button(root5,text="Save",bg="#CE9141",fg="#220047",relief=RAISED,bd=1,activebackground="#220047",activeforeground="#CE9141",font=("fixedsys",10)) saveplaylist.place(x=40,y=560) saveplaylist.bind("<Button>",createplay) elif conditionalval==3: orderofsongs.place_forget() defer="Your Playlist :"+" "+appendlist orderofsongs=Label(root5,text=defer,font=("georgia",15),bg="#220047",fg="#CE9141") orderofsongs.place(x=40,y=170) else: print("okay") """time1=IntVar() time1.set(0) timer1= Label(root5, textvar= time1,font=("georgia",8),fg="#220047",bg="#CE9141") timer1.place(x= 250, y= 550)""" pause.bind("<Button-1>",pausesong) play.bind("<Button-1>",unpause) startbutton.bind("<Button-1>",playmusic) playnext.bind("<Button-1>",nextsong) playbefore.bind("<Button-1>",previous) stop.bind("<Button-1>",stopmusic) pygame.mixer.music.load(listofsongs[0]) pygame.mixer.music.play() updatename() """timer()
class PageOptions(): def __init__(self): self.root = Tk() self.createWidgets() self.root.mainloop() def initialize_variables(self): # Initial size of the app self.HEIGHT = 600 self.WIDTH = 800 self.root.title("Categorization Dialog Widget") self.root.minsize(750, 550) def createWidgets(self): self.initialize_variables() # Background self.canvas = Canvas(self.root, height=self.HEIGHT, width=self.WIDTH) self.background_label = Label(self.root, bg='#3C1E5F') self.background_label.place(relwidth=1, relheight=1) self.canvas.pack() # Upper frame with logo and info message self.higher_frame = Frame(self.root, bg='#FFD164', bd=5) self.higher_frame.place(relx=0.5, rely=0.1, relwidth=0.85, relheight=0.35, anchor='n') self.logo = Canvas(self.higher_frame, bd=1) self.logo.place(relx=0, rely=0, relwidth=1, relheight=0.5) self.img = PhotoImage(file="logo.png") self.img = self.img.subsample(6) self.logo.create_image(0, 0, anchor='nw', image=self.img) self.var = "Sentiment Classification and Categorization of txt files" self.infoMessage = Message(self.higher_frame, text=self.var, justify='center', width=350, font=("Courier bold", 16)) self.infoMessage.place(relx=0.4, rely=0.05, relwidth=0.5, relheight=0.3) # Menubar with Option, Result and Direct input self.menubar() # Lower frame with scrollbars for displaying of categories and file names self.lower_frame = Frame(self.root, bg='#FFD164', bd=5) self.lower_frame.place(relx=0.5, rely=0.35, relwidth=0.85, relheight=0.55, anchor='n') self.lower_frame.grid_rowconfigure(0, weight=1) self.lower_frame.grid_columnconfigure(0, weight=1) self.optionCanvas = Canvas(self.lower_frame, bg='white', bd=3) self.optionCanvas.place(relwidth=1, relheight=1) # select language (English or Swedish) self.selectLanguage(self.optionCanvas) # open folder with input files self.openFolder = Label(self.optionCanvas, text="Open a folder with input files", justify='left', bg='white', font=("Courier bold", 12)) self.openFolder.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.2) self.button = Button(self.optionCanvas, text="Browse", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.5, rely=0.4, relwidth=0.3, relheight=0.15) # save result in excel file self.CheckVar = IntVar() self.excelFileCheckbutton = Checkbutton(self.optionCanvas, text="Save as excel", variable=self.CheckVar, \ onvalue=1, offvalue=0, bg='white', font=("Courier bold", 12), height=5, width=20) self.excelFileCheckbutton.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.15) # Middle frame with buttons bar def menubar(self): self.middle_frame = Frame(self.root, bg='#FFD164', bd=5) self.middle_frame.place(relx=0.5, rely=0.25, relwidth=0.85, relheight=0.1, anchor='n') self.button = Button(self.middle_frame, text="Options", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.1, relwidth=0.2, relheight=1) self.button = Button(self.middle_frame, text="Result", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.4, relwidth=0.2, relheight=1) self.button = Button(self.middle_frame, text="Direct input", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.7, relwidth=0.2, relheight=1) # select language (English or Swedish) def selectLanguage(self, parentWidget): # Create a Tkinter variable self.tkvar = StringVar() # Dictionary with options self.choices = {'English', 'Swedish'} self.tkvar.set('English') # set the default option # Popup menu with languages self.popupMenu = OptionMenu(parentWidget, self.tkvar, *self.choices) self.popupLabel = Label(parentWidget, text="Choose a language", bg='white', justify='left', font=("Courier bold", 12)) self.popupLabel.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.2) self.popupMenu.configure(bd=3, bg='#EE7C7D') self.popupMenu.place(relx=0.5, rely=0.1, relwidth=0.3, relheight=0.15) # on change dropdown value def change_dropdown(*args): print(self.tkvar.get()) # link function to change dropdown self.tkvar.trace('w', change_dropdown) # Gets the selected folder by the user and uses keywordSearch in txt files, then presents categories and file names def fileDialog(self): try: self.folderSelected = filedialog.askdirectory() self.categorizer = Categorizer(self.folderSelected) self.dict_obj = self.categorizer.categorizeFilesFromDirectoryInMapAndSubDirectory() self.results.insert(END, "Category".ljust(20, ' ') + "File name") self.results.insert(END, "\n") for key, val in self.dict_obj.items(): self.results.insert(END, str(key).ljust(20, ' ') + str(val)) except UnicodeDecodeError: self.results.insert(END, "Selected folder does not contain txt files.")
class FilePickEdit(Frame): def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'): """ file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) """ self.master = master self.directory = directory self.user_onChange = user_onChange Frame.__init__(self, master) row = 0 self.unmodified = True self.allowNone = allowNone self.file_extension = "" if type(file_mask) != list: file_mask = [file_mask] if "." in file_mask[0]: self.file_extension = file_mask[0][file_mask[0].rfind('.'):] # read filenames self.file_mask = file_mask self.updateList() # filename frame self.list_frame = Frame(self) self.list_frame.grid(row=row, column=0, sticky="WE") self.list_frame.columnconfigure(0, weight=1) # create list self.picked_name = StringVar() self.makelist() # refresh button self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1) self.refresh_button.grid(row=0, column=1, sticky='E') # save button self.save_button = Button(self.list_frame, text="save", command=self.save, height=1) self.save_button.grid(row=0, column=2, sticky="E") # editor row += 1 if coloring: self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter) else: self.editor = ScrolledText2(self, self.onEdit) if font is not None: self.editor.configure(font=font) if edit_height is not None: self.editor.configure(height=edit_height) self.editor.grid(row=row, column=0, sticky="NEWS") self.rowconfigure(row, weight=1) self.columnconfigure(0, weight=1) # option to change filename on edit row += 1 self.options_frame = Frame(self) self.options_frame.grid(row=row, column=0, sticky=W) self.rename_on_edit = IntVar() self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit) self.cb.pack(side=LEFT) self.cb.configure(command=self.onChangeRename) self.rename_on_edit.set(rename_on_edit) # filename frame row += 1 self.filename_frame = Frame(self) self.filename_frame.grid(row=row, column=0, sticky="WE") self.filename_frame.columnconfigure(0, weight=1) # save as filename self.save_name = StringVar() self.save_edit = Entry(self.filename_frame, textvariable = self.save_name) self.save_edit.grid(row=0, column=0, sticky="WE") self.save_name.trace("w", self.onSaveChange) # pick default if applicableButton self.select(default_file) self.row = row def setDirectory(self, directory, keep=False): self.directory = directory self.updateList() self.makelist() # menu = self.list["menu"] scrolledlist # menu = self.list.listbox#["scrolledlist"] # menu.delete(0, 'end') # add the new ones # for filename in self.files: # menu.add_command(label=filename, command=_setit(self.picked_name, filename, None)) # if keep is true, only the files list will be updated but the content of the # text area will not be altered/removed if not keep: self.select("") def refresh(self): sel = self.get() self.updateList() self.select(sel, notify=False) def reloadFile(self): self.editor.delete("1.0", END) filename = self.picked_name.get() if os.path.exists(os.path.join(self.directory, filename)): new_text = open(os.path.join(self.directory, filename)).read() if new_text.strip() == "": new_text = "// %s is empty\n" % filename new_text = new_text.replace("\r", "") else: new_text = "" self.editor.insert(INSERT, new_text) def setText(self, txt): """ Replaces the text in the edit field as by typing into it. """ self.select("") if txt.strip() == "": txt = "// empty database\n" self.editor.insert(INSERT, txt) self.onEdit() def onSelChange(self): self.reloadFile() filename = self.picked_name.get() self.save_name.set(filename) self.save_edit.configure(state=DISABLED) self.unmodified = True if self.user_onChange is not None: self.user_onChange(filename) def onSaveChange(self, name, index, mode): pass def autoRename(self): # modify "save as" name filename = self.picked_name.get() if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename ext = "" extpos = filename.rfind(".") if extpos != -1: ext = filename[extpos:] base = filename[:extpos] hpos = base.rfind("-") num = 0 if hpos != -1: try: num = int(base[hpos+1:]) base = base[:hpos] except: pass while True: num += 1 filename = "%s-%d%s" % (base, num, ext) if not os.path.exists(filename): break self.save_name.set(filename) # user callback if self.user_onChange is not None: self.user_onChange(filename) def onEdit(self): if self.unmodified: self.unmodified = False # do auto rename if it's enabled or there is no file selected (editing new file) if self.rename_on_edit.get() == 1 or self.picked_name.get() == "": self.autoRename() # enable editing of save as name self.save_edit.configure(state=NORMAL) def onChangeRename(self): # called when clicking on "rename on edit" checkbox if self.rename_on_edit.get() == 1: if (not self.unmodified) and self.save_name.get() == self.picked_name.get(): self.autoRename() else: self.save_name.set(self.picked_name.get()) def updateList(self): self.files = [] if self.allowNone: self.files.append("") if os.path.exists(self.directory): for filename in os.listdir(self.directory): for fm in self.file_mask: if fnmatch(filename, fm): self.files.append(filename) self.files.sort() if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask)) def select(self, filename, notify=True): """ selects the item given by filename """ if filename in self.files: if not havePMW: self.picked_name.set(filename) else: self.list.selectitem(self.files.index(filename)) if notify: self.onSelChange(filename) else: self.editor.delete("1.0", END) def makelist(self): if havePMW: self.list = ComboBox(self.list_frame, selectioncommand = self.onSelChange, scrolledlist_items = self.files, ) self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS") self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised') self.picked_name = self.list else: self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files)) self.list.grid(row=0, column=0, sticky="NEW") self.picked_name.trace("w", self.onSelChange) def save(self): self.get() def set(self, selected_item): self.select(selected_item) def get(self): """ gets the name of the currently selected file, saving it first if necessary """ filename = self.save_name.get() if self.unmodified == False: self.unmodified = True # save the file f = open(os.path.join(self.directory, filename), "w") f.write(self.editor.get("1.0", END).encode('utf-8')) f.close() # add it to the list of files # if not filename in self.files: # self.files.append(filename) # self.files.sort() # self.list.destroy() # self.makelist() # set it as the new pick #if havePMW: # self.picked_name.selectitem(self.files.index(filename), 1) #else: # self.picked_name.set(filename) # self.select(filename) self.refresh() self.select(filename, notify=False) self.save_edit.configure(state=DISABLED) return filename def get_text(self): return self.editor.get("1.0", END) def get_filename(self): return self.save_name.get() def set_enabled(self, state): self.editor.configure(state=state) if havePMW: self.list.component('entryfield_entry').configure(state=state) # self.list.component('arrowbutton').configure(state=state) self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList) else: self.list.configure(state=state) self.save_button.configure(state=state) self.cb.configure(state=state) self.save_edit.configure(state=state)
class S3Zilla: def __init__(self, master): error_msg = "Ensure S3 is configured on your machine:" try: self.s3 = boto3.resource('s3') except Exception as e: print("%s: %s" % (error_msg, e)) exit(1) try: self.s3c = boto3.client('s3') except Exception as err: print("%s: %s" % (error_msg, err)) exit(1) self.colors = { 'light-grey': '#D9D9D9', 'blue': '#2B547E', 'black': '#000000', 'red': '#FF3346', 'grey': '#262626', 'cyan': '#80DFFF' } self.master = master self.master.title("Amazon S3 File Transfer Client") self.master.configure(bg=self.colors['grey']) self.master.geometry("885x645") menu = Menu(self.master) menu.config(background=self.colors['grey'], fg=self.colors['light-grey']) self.master.config(menu=menu) file = Menu(menu) file.add_command(label="Exit", command=self.quit) menu.add_cascade(label="File", menu=file) refresh = Menu(menu) refresh.add_command(label="Local", command=self.refresh_local) refresh.add_command(label="S3", command=self.refresh_s3) menu.add_cascade(label="Refresh", menu=refresh) self.dir, self.drp_sel, self.bucket_name = '', '', '' self.folder_path = StringVar() self.dropdown = StringVar() self.dropdown_data = self.populate_dropdown() if not self.dropdown_data: self.dropdown_data = ['none available'] self.deleted = False self.local_sel, self.s3_sel = ([] for i in range(2)) self.title_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], font="Helvetica 10 bold", width=120) self.local_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="LOCAL FILE SYSTEM", font="Helvetica 10 bold underline", width=60) self.s3_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="AMAZON S3", font="Helvetica 10 bold underline", underline=True, width=60) self.dropdown_box = OptionMenu(master, self.dropdown, *self.dropdown_data, command=self.set_drop_val) self.dropdown_box.configure(fg=self.colors['light-grey'], bg=self.colors['blue'], width=27, highlightbackground=self.colors['black'], highlightthickness=2) self.browse_button = Button(master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="Browse", width=30, highlightbackground=self.colors['black'], highlightthickness=2, command=self.load_dir) self.browse_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="No directory selected", width=37, font="Helvetica 10") self.bucket_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="No bucket selected", width=37, font="Helvetica 10") self.refresh_btn_local = Button( master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="REFRESH", width=30, highlightbackground=self.colors['black'], highlightthickness=2, command=self.refresh_local) self.refresh_btn_s3 = Button(master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="REFRESH", width=30, highlightbackground=self.colors['black'], highlightthickness=2, command=self.refresh_s3) self.explorer_label_local = Label(master, fg=self.colors['light-grey'], bg=self.colors['blue'], width=30, text="Local File System: ") self.explorer_label_s3 = Label(master, fg=self.colors['light-grey'], bg=self.colors['black'], width=30, text="S3 File System") self.ex_loc = Listbox(master, fg=self.colors['cyan'], bg=self.colors['black'], width=49, height=18, highlightcolor=self.colors['black'], selectmode="multiple") self.ex_s3 = Listbox(master, fg=self.colors['cyan'], bg=self.colors['black'], width=49, height=18, highlightcolor=self.colors['black'], selectmode="multiple") self.upload_button = Button(master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="Upload ->", width=20, highlightbackground=self.colors['black'], highlightthickness=2, command=self.upload) self.download_button = Button(master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="<- Download", width=20, highlightbackground=self.colors['black'], highlightthickness=2, command=self.download) self.delete_local = Button(master, fg=self.colors['light-grey'], bg=self.colors['red'], text="DELETE", width=20, highlightbackground=self.colors['black'], command=self.delete_local_records) self.delete_s3 = Button(master, fg=self.colors['light-grey'], bg=self.colors['red'], text="DELETE", width=20, highlightbackground=self.colors['black'], command=self.delete_s3_records) self.found_label_local = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="found local", width=54) self.found_label_s3 = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="found s3", width=54) self.status_label = Label(master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="Hello " + getuser(), width=54) self.create_bucket_label = Label( master, fg=self.colors['light-grey'], bg=self.colors['grey'], text="New Bucket:", ) self.create_bucket_name = Text(master, fg=self.colors['cyan'], bg=self.colors['black'], width=25, height=1) self.create_bucket_button = Button( master, fg=self.colors['light-grey'], bg=self.colors['blue'], text="Create", width=5, highlightbackground=self.colors['black'], highlightthickness=2, command=self.create_bucket) # ####### begin grid placement ####### # self.title_label.grid(row=0, sticky=E + W, padx=20, pady=5) self.local_label.grid(row=0, sticky=W, padx=8, pady=5) self.s3_label.grid(row=0, sticky=E, padx=0, pady=5) self.browse_button.grid(row=1, sticky=W, padx=86, pady=10) self.dropdown_box.grid(row=1, sticky=E, padx=86, pady=5) self.browse_label.grid(row=2, sticky=W, padx=86, pady=5) self.bucket_label.grid(row=2, sticky=E, padx=86, pady=5) self.refresh_btn_local.grid(row=3, sticky=W, padx=86, pady=10) self.refresh_btn_s3.grid(row=3, sticky=E, padx=86, pady=10) self.explorer_label_local.grid(row=4, sticky=W, padx=20) self.explorer_label_s3.grid(row=4, sticky=E, padx=20) self.ex_loc.grid(row=4, sticky=W, padx=20) self.ex_s3.grid(row=4, sticky=E, padx=20) self.upload_button.grid(row=5, sticky=W, padx=224, pady=0) self.download_button.grid(row=5, sticky=E, padx=224, pady=0) self.delete_local.grid(row=5, sticky=W, padx=20, pady=0) self.delete_s3.grid(row=5, sticky=E, padx=20, pady=0) self.found_label_local.grid(row=6, sticky=W, padx=0, pady=20) self.found_label_s3.grid(row=6, sticky=E, padx=0, pady=20) self.status_label.grid(row=7, sticky=W, padx=0, pady=20) self.create_bucket_label.grid(row=7, sticky=E, padx=330, pady=0) self.create_bucket_name.grid(row=7, sticky=E, padx=100, pady=0) self.create_bucket_button.grid(row=7, sticky=E, padx=20, pady=0) n1 = "%s files found" % str(self.ex_loc.size()) self.set_found_local_label(n1) n2 = "%s files found" % str(self.ex_s3.size()) self.set_found_s3_label(n2) def quit(self): exit() def get_local_sel(self): return [self.ex_loc.get(i) for i in self.ex_loc.curselection()] def get_s3_sel(self): return [self.ex_s3.get(i) for i in self.ex_s3.curselection()] def set_drop_val(self, selection): self.drp_sel = selection def delete_local_records(self): files = self.get_local_sel() if not files: message = "Please select a file(s) to delete" self.set_status_label(message) else: self.del_local(files) def del_local(self, files_remaining): if len(files_remaining) > 0: f = files_remaining.pop(0) if not isdir(self.dir + "/" + f): try: remove("%s/%s" % (self.dir, f)) except Exception as err: self.set_status_label("%s" % err) self.status_label.update_idletasks() self.del_local(files_remaining) else: try: rmtree("%s/%s" % (self.dir, f)) except Exception as err: self.set_status_label("%s" % err) self.status_label.update_idletasks() self.del_local(files_remaining) self.deleted = True self.refresh_local() def delete_s3_records(self): removal = '' if not self.drp_sel: m = "Please select a bucket..." self.set_status_label(m) else: removal = self.get_s3_sel() if not removal: m = "Please select at least 1 object to delete" self.set_status_label(m) else: bucket = self.s3.Bucket(self.drp_sel) for rm in removal: for k in bucket.objects.all(): if k.key != rm: continue k.delete() break self.deleted = True self.refresh_s3() def load_dir(self): self.dir = askdirectory() self.set_local_browse_label(self.dir) def refresh_local(self): if not self.dir: m = "Use the browse button to select a directory" self.set_status_label(m) else: self.set_local_browse_label(self.dir) self.ex_loc.delete(0, 'end') x = self.dir + "/" d = [ f if not isdir(x + f) else f + '/' for f in sorted(listdir(x)) ] self.ex_loc.insert('end', *d) if not self.deleted: m = "Hello %s" % getuser() else: m = "FINISHED DELETING" self.deleted = False self.set_status_label(m) n = "%s files found" % str(self.ex_loc.size()) self.set_found_local_label(n) def refresh_s3(self): if 'none available' in self.dropdown_data: m = "Please create at least one S3 bucket" self.set_status_label(m) elif not self.drp_sel: m = "Please select a bucket from the drop-down list" self.set_status_label(m) else: self.ex_s3.delete(0, 'end') self.ex_s3.insert('end', *self.get_bucket_contents()) self.set_status_label("Hello %s" % getuser()) self.set_s3_bucket_label(self.drp_sel) n = "%s files found" % str(self.ex_s3.size()) self.set_found_s3_label(n) self.found_label_s3.update_idletasks() if not self.deleted: m = "Hello %s" % getuser() else: m = "FINISHED DELETING" self.deleted = False self.set_status_label(m) def finished(self, incoming_message): d = "FINISHED %s" % incoming_message for letter in enumerate(d): self.set_status_label(d[0:letter[0] + 1]) self.status_label.update_idletasks() sleep(.1) def upload(self): if not self.drp_sel or not self.dir: m = "Ensure a local path and S3 bucket are selected" self.set_status_label(m) elif not self.get_local_sel(): m = "Ensure files are selected to upload" self.set_status_label(m) else: for selection in self.get_local_sel(): file_ = "%s/%s" % (self.dir, selection) if not isdir(file_): self.s3c.upload_file(file_, self.drp_sel, basename(file_)) else: zipd = make_archive(file_, 'zip', self.dir, selection) self.s3c.upload_file(zipd, self.drp_sel, basename(zipd)) remove(zipd) m = "Uploaded: %s" % selection self.set_status_label(m) self.status_label.update_idletasks() self.refresh_s3() self.finished("UPLOAD") def download(self): if not self.drp_sel or not self.dir: m = "Ensure a file and bucket have been selected" self.set_status_label(m) elif not self.get_s3_sel(): m = "Ensure files are selected to download" self.set_status_label(m) else: for selection in self.get_s3_sel(): file_ = "%s/%s" % (self.dir, selection) self.s3c.download_file(self.drp_sel, selection, file_) self.refresh_local() self.finished("DOWNLOAD") def get_bucket_contents(self): bucket = self.s3.Bucket(self.drp_sel) return [s3_file.key for s3_file in bucket.objects.all()] def populate_dropdown(self): return [bucket.name for bucket in self.s3.buckets.all()] def set_local_browse_label(self, incoming): if len(incoming) > 35: self.browse_label.config(text=basename(incoming) + '/') else: self.browse_label.config(text=incoming) def set_s3_bucket_label(self, incoming): self.bucket_label.config(text=incoming) def set_status_label(self, incoming): self.status_label.config(text=incoming) def set_found_local_label(self, incoming): self.found_label_local.config(text=incoming) def set_found_s3_label(self, incoming): self.found_label_s3.config(text=incoming) def create_bucket(self): self.bucket_name = self.create_bucket_name.get("1.0", END).strip() if not self.bucket_name: m = "Please enter a new bucket name" self.set_status_label(m) else: pre_exists = False try: self.s3.create_bucket(Bucket=self.bucket_name) except ClientError as ce: pre_exists = True m = "Bucket name is already in use. " m += "Choose a different name." self.set_status_label(m) if not pre_exists: m = "%s created: restarting..." % self.bucket_name self.set_status_label(m) self.status_label.update_idletasks() res = executable execl(res, res, *argv)
class MyApp: def __init__(self): self.myContainer1 = tk.Tk() self.myContainer1.wm_attributes('-type', 'splash') self.myContainer1.title("Monsterrhino Printer") self.myContainer1.geometry("800x480") self.myContainer1.configure(bg="black") # Set up variables self.im_height = 1240 # Maximum step number of axis self.im_width = 2000 # Maximum step number of axis self.pix_per_step = 2 self.pos = [0, 0, 0] self.ser = serial.Serial() self.ser.baudrate = 115200 self.port_name = "/dev/ttyUSB0" self.laser_status = "off" self.laser_pin = 26 GPIO.setmode(GPIO.BCM) GPIO.setup(self.laser_pin, GPIO.OUT) self.laser(0) self.hight_factor = 0.66 self.rot_count = 90 self.homing = False # Show image self.tkpi = PhotoImage(file="images/monsterrhino.png") self.label = Label(self.myContainer1, image=self.tkpi, bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=0, highlightbackground="black", font="none 18") self.load_img = Button(self.myContainer1, text="Load Image!", command=self.new_img, bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 18") self.connect = Button(self.myContainer1, text="X", command=self.restart_app, bg='black', activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 18", fg="red") self.status_bar = Label(self.myContainer1, text="Status") self.spinnbox_label = Label(self.myContainer1, text="Image height:", bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 8") self.go_zero = Button(self.myContainer1, text="Home", command=self.home_xy_axis, bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 18") self.res_label = Label(self.myContainer1, text="{}x{} px".format(self.im_height, self.im_width), bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 8") self.burn = Button(self.myContainer1, text="Start plotting!", command=self.start_printing, bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 18") self.xdir_label = Label(self.myContainer1, text="y_max = 1500 steps ------------> y", bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 8") self.rotate_img = Button(self.myContainer1, text="Rotate Image!", command=self.rotate_image) self.variable = StringVar(self.myContainer1) self.variable.set("700") # default value self.drop_down = OptionMenu(self.myContainer1, self.variable, "500", "600", "700", "800", "900", "1000", "1100", "1200", "1300", "1400", "1500") self.drop_down.configure(bg='black', fg="white", activebackground=HOVERCOLER, borderwidth=2, highlightbackground="black", font="none 18") self.var1 = tk.IntVar() self.checkbox = tk.Checkbutton(self.myContainer1, text='Curved', variable=self.var1, onvalue=1, offvalue=0, bg='black', activebackground=HOVERCOLER, borderwidth=0, highlightbackground="black", font="none 18", fg="red") # Organize layout using grid self.label.place(x=520, y=440, anchor="s", height=430, width=500) self.load_img.place(x=140, y=90, anchor="s", height=80, width=240) self.spinnbox_label.place(x=100, y=115, anchor="s") self.drop_down.place(x=140, y=200, anchor="s", height=80, width=240) self.go_zero.place(x=140, y=285, anchor="s", height=80, width=240) self.burn.place(x=140, y=370, anchor="s", height=80, width=240) # self.checkbox.place(x=140, y=430, anchor="s") self.connect.place(x=770, y=50, anchor="s", height=40, width=40) self.xdir_label.place(x=140, y=470, anchor="s") # self.res_label.place(x=140, y=470, anchor="s") self.tc_receive_CAN_task = BackgroundTask(self.tc_receive_CAN) self.querry_y_pos_const_task = BackgroundTask(self.querry_y_pos_const) self.blink_led_task = BackgroundTask(self.blink_LED) self.print_task = BackgroundTask(self.draw_img_new) self.run = False if not PC: print("Startup CAN!") os.system("sudo /sbin/ip link set can0 up type can bitrate 1000000" ) # brings up CAN self.can_bus = can.interface.Bus(bustype="socketcan", channel="can0", bitrate=1000000) time.sleep(0.1) # start receive task self.tc_receive_CAN_task.start() print("Start can querry task") self.led = LED() self.led.init_led() self.led.set_green() self.querry_y_pos_const_task.start() def start_printing(self): """Starts printing """ self.print_task.start() def restart_app(self): """Restarts app, only from debugg area callable """ os._exit(0) def tc_receive_CAN(self, par): """Starts receiver task to receive and set tc_status """ try: print("-> Enter CAN receive loop!") while True: # Wait until a message is received. # print("----> Waiting...") message = self.can_bus.recv() # print("<---- Received...") # print("message length ---> " + str(len(message.data))) if len(message.data) > 1: # print("enter if <-------<") #print("ID length: ") #print(message.arbitration_id.bit_length()) msb0 = '{0:x} '.format(message.data[0]) # print("id----> " + str(int(msb0, 16))) id = int(msb0, 16) msb1 = '{0:x} '.format(message.data[1]) # print("value----> " + str(int(msb1, 16))) value = int(msb1, 16) to_temp = int(message.arbitration_id) >> 18 to_can = int(to_temp & int('000001111', 2)) #print("To can ID: " + str(to_can)) s = '' for i in range(message.dlc): s += '{0:x} '.format(message.data[i]) #print('CAN receive----> {}'.format(s)) # Lock status if to_can == 1 and id == 35: # Check if it is not the other value # print("Y pos") #self.pos[1] = value self.y_current = value #self.pos_label.configure(text="x: {} y: {} z: {}".format(self.pos[0], self.pos[1], self.pos[2])) except OSError: print('Cannot find PiCAN board') def new_img(self): folder_path = filedialog.askopenfilename() try: self.orig_im_cv2 = cv2.imread(folder_path) self.orig_im = Image.open(folder_path) self.orig_im = self.orig_im.convert('L') width, height = self.orig_im.size print("Original size: {} x {}".format(width, height)) basewidth = 430 wpercent = np.divide(basewidth, width) print("wpercent: " + str(wpercent)) hsize = int(height * wpercent) print("basewidth {} hsize {}".format(basewidth, hsize)) self.im = self.orig_im.resize((basewidth, hsize), Image.ANTIALIAS) self.spinnbox_label.configure( text="Orig. {}x{} px".format(width, height)) print("Set new image as label") self.tkpi = ImageTk.PhotoImage(self.im) self.label.config(image=self.tkpi) except: self.status_bar.configure(text="No valid image selected!") def stripe_img(self): print("stripe image") def laser(self, state): if state is 1: print("laser on") GPIO.output(self.laser_pin, 0) else: print("laser off") GPIO.output(self.laser_pin, 1) def x_move_relative(self, steps=100): """Moves to a given target position of the given motor """ _steps = steps * 1 print("Print straight!") address, data = cmd_to_CAN(command="m", sub_command="mr", motor_nr=2, usr_fnct_id=1, err=0, data=_steps, toAddress=2, fromAddress=1, respondMessage=1) if not PC: # Send CAN message self.send_CAN(address, data) address, data = cmd_to_CAN(command="m", sub_command="mr", motor_nr=2, usr_fnct_id=1, err=0, data=_steps, toAddress=2, fromAddress=1, respondMessage=1) if not PC: # Send CAN message self.send_CAN(address, data) def x_move_curve(self, steps=100): """Moves to a given target position of the given motor """ print("Print curved!") address, data = uf_to_CAN(fromAddress=1, toAddress=2, respondMessage=1, usr_fnct_id=1, command="f", sub_command="s", uf_nr=1, par=2) if not PC: # Send CAN message print("curve") #self.send_CAN(address, data) def y_move_targetposition(self, pos=700): """Moves to a given target position of the given motor """ _steps = pos * 1 address, data = cmd_to_CAN(command="m", sub_command="tp", motor_nr=1, usr_fnct_id=1, err=0, data=_steps, toAddress=2, fromAddress=1, respondMessage=1) if not PC: # Send CAN message self.send_CAN(address, data) def home_xy_axis(self): """Homes x and y axis and moves back to starting position """ if self.homing == False: address, data = uf_to_CAN(fromAddress=1, toAddress=2, respondMessage=1, usr_fnct_id=1, command="f", sub_command="s", uf_nr=1, par=4) if not PC: # Send CAN message self.send_CAN(address, data) self.querry_y_pos() self.homing = True self.laser(0) def querry_y_pos_const(self, par): """ Variables: userFunctionVariable1 = 30 158 userFunctionVariable2 = 31 159 userFunctionVariable3 = 32 160 userFunctionVariable4 = 33 161 userFunctionVariable5 = 34 162 userFunctionVariable6 = 35 163 """ # Start receive task # self.tc_receive_CAN_tc_row_task.start() # Transform CAN command 163 = ID 35 # Transform CAN command 158 = ID 30 while True: address, data = uv_from_CAN(fromAddress=1, toAddress=2, respondMessage=1, get_val=163, command=3, uf_nr=2, sub_command=35, data=0) # print("-------> Querry!") # Send CAN message if not PC: # Send CAN message self.send_CAN(address, data) time.sleep(0.02) def querry_y_pos(self): """ Variables: userFunctionVariable1 = 30 158 userFunctionVariable2 = 31 159 userFunctionVariable3 = 32 160 userFunctionVariable4 = 33 161 userFunctionVariable5 = 34 162 userFunctionVariable6 = 35 163 """ # Start receive task # self.tc_receive_CAN_tc_row_task.start() # Transform CAN command 163 = ID 35 # Transform CAN command 158 = ID 30 #while True: address, data = uv_from_CAN(fromAddress=1, toAddress=2, respondMessage=1, get_val=163, command=3, uf_nr=2, sub_command=35, data=0) # Send CAN message if not PC: # Send CAN message self.send_CAN(address, data) # self.myParent.after(20, self.querry_y_pos) #print("Querry!") #time.sleep(0.5) def send_CAN(self, address, data): """Translates command to CAN frame and sends it :param message: command to be translated and send over CAN """ # Try to write the message try: msg = can.Message(arbitration_id=address, data=data, is_extended_id=True) # print(msg) except AttributeError as error: print("error:Create message") print(error) return # Try to send the message try: self.can_bus.send(msg) # print("Message sent on {}".format(self.can_bus.channel_info)) except can.CanError: print("Message could NOT be sent!") def serial_connect(self): try: if self.ser.is_open == False: self.ser.port = self.port_name self.ser.open() if self.ser.is_open == True: #self.connect.configure(text="Disconnect!", foreground="green") self.status_bar.configure(text="CNC found!") elif self.ser.is_open == True: self.ser.close() if self.ser.is_open == False: #self.connect.configure(text="Connect!", foreground="black") self.status_bar.configure(text="Disconnected") except: self.connect.configure(text="No Device!", foreground="red") def move_step(self, axis, step=1): # int(self.step_spinnbox.get()) try: if self.ser.is_open == True: directions = ['x', 'y', 'z', 'c', 's', 'u'] if directions.index(axis) < 3: self.pos[directions.index(axis)] += step if directions.index(axis) >= 3: self.pos[directions.index(axis) - 3] -= step self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) self.ser.write(b'{}{}\n'.format(step, axis)) elif self.ser.is_open == False: self.status_bar.configure(text="Serial not open!") except: self.status_bar.configure(text="No Device connected!") def set_zero(self): for i in range(3): self.pos[i] = 0 self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) def move_zero(self): try: if self.ser.is_open == True: if self.pos[0] < 0: self.ser.write(b'{}{}\n'.format(self.pos[0] * -1, "x")) self.pos[0] = 0 self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) elif self.pos[0] > 0: self.ser.write(b'{}{}\n'.format(self.pos[0], "c")) self.pos[0] = 0 self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) elif self.pos[1] < 0: self.ser.write(b'{}{}\n'.format(self.pos[1] * -1, "y")) self.pos[1] = 0 self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) elif self.pos[1] > 0: self.ser.write(b'{}{}\n'.format(self.pos[1], "s")) self.pos[1] = 0 self.pos_label.configure(text="x: {} y: {} z: {}".format( self.pos[0], self.pos[1], self.pos[2])) elif self.ser.is_open == False: self.status_bar.configure(text="Serial not open!") except: self.status_bar.configure(text="No Device connected!") def rotate_image( self ): # rotation behavior not working properly yet, also mirror function introducing: ImageOps.rotate try: if self.rot_count == 360: self.rot_count = 0 self.im = self.orig_im.rotate(self.rot_count) self.rot_count += 90 width, height = self.im.size new_width = int( np.divide(width, int(self.pix_per_step_spinnbox.get()))) new_height = int((new_width * height / width) * self.hight_factor) self.im = self.im.resize((new_width, new_height), Image.ANTIALIAS) self.tkpi = ImageTk.PhotoImage(self.im) self.label.config(image=self.tkpi) self.label.config(height=200, width=200) except: self.status_bar.configure(text="No image defined!") # def burn_image(self): # try: # if self.ser.is_open == True and self.pos[0] == 0 and self.pos[1] == 0: # pix = np.array(self.im) # pix = 255 - pix # nrow, ncol = pix.shape # # for r in range(nrow): # if self.pos[0] == 0: # print ("Forward x") # for c in range(ncol): # self.ser.write( # b'{}a\n'.format(int(np.multiply(pix[r, c], float(self.burn_time_factor.get()))))) # time.sleep( # np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # self.move_step("x", int(self.scale_val.get())) # time.sleep(0.1) # else: # print ("Backward x") # for c in reversed(range(ncol)): # self.ser.write( # b'{}a\n'.format(int(np.multiply(pix[r, c], float(self.burn_time_factor.get()))))) # time.sleep( # np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # self.move_step("c", int(self.scale_val.get())) # time.sleep(0.1) # # self.move_step("y", int(self.scale_val.get())) # time.sleep(0.10) # print ("x: {} y: {} z: {}".format(self.pos[0], self.pos[1], self.pos[2])) # # self.move_zero() # # elif self.ser.is_open == False: # self.status_bar.configure(text="Serial not open!") # except: # self.status_bar.configure(text="No Device connected!") # # def burn_image_with_skip(self): # """ # Function to switch laser on and off and move through each pixel. White pixel are skipped # """ # try: # if self.ser.is_open == True and self.pos[0] == 0 and self.pos[1] == 0: # pix = np.array(self.im) # pix = 255 - pix # nrow, ncol = pix.shape # # for r in range(nrow): # ncol_count_f = 0 # ncol_count_b = 0 # if self.pos[0] == 0: # print ("Forward x") # print ("Row: %d" % r) # for c in range(ncol): # if pix[r, c] > 0: # self.move_step("x", int(self.scale_val.get()) * ncol_count_f) # time.sleep(0.1 * ncol_count_f) # self.ser.write(b'{}a\n'.format(int(np.multiply(pix[r, c], # float(self.burn_time_factor.get()))))) # time.sleep( # np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # ncol_count_f = 0 # if c == (ncol - 1): # self.move_step("x", (ncol_count_f + 1) * int(self.scale_val.get())) # print ("Return to zero steps forward") # time.sleep(0.02 * ncol_count_f) # ncol_count_f += 1 # # else: # print ("Backward x") # print ("Row: %d" % r) # for c in reversed(range(ncol)): # if pix[r, c] > 0: # self.move_step("c", int(self.scale_val.get()) * ncol_count_b) # time.sleep(0.1 * ncol_count_b) # self.ser.write(b'{}a\n'.format(int(np.multiply(pix[r, c], # float(self.burn_time_factor.get()))))) # time.sleep( # np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # ncol_count_b = 0 # if c == 0: # self.move_step("c", self.pos[0]) # print ("Return to zero steps backward") # time.sleep(0.02 * self.pos[0]) # ncol_count_b += 1 # # self.move_step("y", int(self.scale_val.get())) # time.sleep(0.10) # print ("x: {} y: {} z: {}".format(self.pos[0], self.pos[1], self.pos[2])) # # self.move_zero() # # elif self.ser.is_open == False: # self.status_bar.configure(text="Serial not open!") # except: # self.status_bar.configure(text="No Device connected!") # # # def burn_image_with_skip_jump(self): # """ # Function to switch laser on and off and move through each pixel. White pixel are skipped # """ # try: # if self.pos[0] == 0 and self.pos[1] == 0: # pix = np.array(self.im) # pix = 255 - pix # nrow, ncol = pix.shape # # for c in range(ncol): # nrow_count_f = 0 # nrow_count_b = 0 # if self.pos[1] == 0: # print ("Forward y") # print ("Col: %d" % c) # for r in range(nrow): # if pix[r, c] > 0: # # self.move_step("y", int(self.scale_val.get()) * nrow_count_f) # #time.sleep(0.1 * nrow_count_f) # #self.ser.write(b'{}a\n'.format(int(np.multiply(pix[r, c], float(self.burn_time_factor.get()))))) # #time.sleep(np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # nrow_count_f = 0 # if r == (nrow - 1): # #self.move_step("y", (nrow_count_f + 1) * int(self.scale_val.get())) # print ("Return to zero steps forward") # time.sleep(0.02 * nrow_count_f) # nrow_count_f += 1 # # else: # print ("Backward y") # print ("Col: %d" % c) # for r in reversed(range(nrow)): # if pix[r, c] > 0: # self.move_step("s", int(self.scale_val.get()) * nrow_count_b) # time.sleep(0.1 * nrow_count_b) # self.ser.write(b'{}a\n'.format(int(np.multiply(pix[r, c], # float(self.burn_time_factor.get()))))) # time.sleep( # np.divide(np.multiply(pix[r, c], float(self.burn_time_factor.get())), 1000) + 0.15) # nrow_count_b = 0 # if r == 0: # self.move_step("s", self.pos[1]) # print ("Return to zero steps backward") # time.sleep(0.02 * self.pos[1]) # nrow_count_b += 1 # # self.move_step("x", int(self.scale_val.get())) # time.sleep(0.10) # print ("x: {} y: {} z: {}".format(self.pos[0], self.pos[1], self.pos[2])) # # self.move_zero() # # elif self.ser.is_open == False: # self.status_bar.configure(text="Serial not open!") # except: # self.status_bar.configure(text="No Device connected!") def image_resize(self, image, width=None, height=None, inter=cv2.INTER_AREA): # initialize the dimensions of the image to be resized and # grab the image size dim = None (h, w) = image.shape[:2] # if both the width and height are None, then return the # original image if width is None and height is None: return image # check to see if the width is None if width is None: # calculate the ratio of the height and construct the # dimensions r = height / float(h) dim = (int(w * r), height) # otherwise, the height is None else: # calculate the ratio of the width and construct the # dimensions r = width / float(w) dim = (width, int(h * r)) # resize the image resized = cv2.resize(image, dim, interpolation=inter) # return the resized image return resized def wait_to_finish(self): self.y_current = 1 while self.y_current != 0: # self.querry_y_pos() print("y current 1: " + str(self.y_current)) time.sleep(0.2) def blink_LED(self, par): while True: if self.run == True: self.led.set_orange_green_mix() time.sleep(0.5) self.led.set_orange_green_mix2() time.sleep(0.5) def draw_img_new(self, par): if self.homing == True: print("Start printing ...") self.run = True if not PC: self.blink_led_task.start() wait_for_pen = 1.4 or_nrow, or_ncol = self.orig_im_cv2.shape[:2] print("Original Nraws {} Original Ncols {}".format( or_nrow, or_ncol)) print("Curved: " + str(self.var1.get())) # Get desired image height image_height = int(self.variable.get()) print("image_height: " + str(image_height)) scale_factor = np.divide(or_nrow, image_height) print("scale factor: " + str(scale_factor)) image_width = int(np.divide(or_ncol, scale_factor)) image_width = int(np.divide(image_width, 7)) print("Image height set to: " + str(image_height) + " image width set to: " + str(image_width)) # image_height = 700 invert = False # draw black or white # self.orig_im_cv2 = self.image_resize(self.orig_im_cv2, height = image_height) self.orig_im_cv2 = cv2.resize(self.orig_im_cv2, (image_width, image_height)) self.orig_im_cv2 = cv2.cvtColor(self.orig_im_cv2, cv2.COLOR_BGR2GRAY) __, self.orig_im_cv2 = cv2.threshold( self.orig_im_cv2, 128, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) nrow, ncol = self.orig_im_cv2.shape[:2] c = ncol - 1 r = nrow print("Nraws {} Ncols {}".format(r, c)) if invert: self.orig_im_cv2 = (255 - self.orig_im_cv2) # print(self.orig_im_cv2) # cv2.imshow("im", self.orig_im_cv2) # cv2.waitKey() img = self.orig_im_cv2 positive = True prev_pix = 255 for c in range(ncol - 1, -1, -1): print("c: " + str(c)) if sum(img[:, c]) == ncol * 255: print("Empty line -- skip to next line!") print("----") prev_pix = 255 else: if positive: print("Positive!") for idx, pix in enumerate(reversed(img[:, c])): # print(idx, pix) # ----------------Plotting-------------------- if pix == prev_pix: pass # print("same color!") elif pix < prev_pix: # draw color is black print((len(img[:, c]) - idx), pix) print( "Laser off - move to idx: {}!".format(idx)) if not PC: self.laser(0) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition(idx) self.wait_to_finish() # time.sleep(wait_for_pen) elif pix > prev_pix: # draw color is white print((len(img[:, c]) - idx), pix) print( "Laser on - move to idx: {}!".format(idx)) if not PC: self.laser(1) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition(idx) self.wait_to_finish() # time.sleep(wait_for_pen) if idx == len(img[:, c]) - 1: # move to the end print( "Move to the end to idx: {}!".format(idx)) print((len(img[:, c]) - idx), pix) if pix > 0: # draw color is black print( "Laser off - move to idx: {}!".format( idx)) if not PC: self.laser(0) # time.sleep(wait_for_pen) self.wait_to_finish() # self.y_move_targetposition(idx) # self.wait_to_finish() elif pix == 0: # draw color is white print("Laser on - move to idx: {}!".format( idx)) if not PC: self.laser(1) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition(idx) self.wait_to_finish() # time.sleep(wait_for_pen) prev_pix = pix # ------------------------------------------ print("----") positive = False prev_pix = 255 else: print("Negative!") for idx, pix in enumerate(img[:, c]): # print(idx, pix) # ----------------Plotting-------------------- if pix == prev_pix: pass # print("same color!") elif pix < prev_pix: # draw color is black print((len(img[:, c]) - idx), pix) print("Laser off - move to idx: {}!".format( (len(img[:, c]) - idx))) if not PC: self.laser(0) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition( (len(img[:, c]) - idx)) self.wait_to_finish() # time.sleep(wait_for_pen) elif pix > prev_pix: # draw color is white print((len(img[:, c]) - idx), pix) print("Laser on - move to idx: {}!".format( (len(img[:, c]) - idx))) if not PC: self.laser(1) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition( (len(img[:, c]) - idx)) self.wait_to_finish() # time.sleep(wait_for_pen) if idx == len(img[:, c]) - 1: # move to the end print((len(img[:, c]) - idx), pix) print("Move to the end to idx: {}!".format( (len(img[:, c]) - idx))) if pix > 0: # draw color is black print( "Laser off - move to idx: {}!".format( (len(img[:, c]) - idx))) if not PC: self.laser(0) # time.sleep(wait_for_pen) self.wait_to_finish() # self.y_move_targetposition(0) # self.wait_to_finish() elif pix == 0: # draw color is white print("Laser on - move to idx: {}!".format( (len(img[:, c]) - idx))) if not PC: self.laser(1) # time.sleep(wait_for_pen) self.wait_to_finish() self.y_move_targetposition(0) self.wait_to_finish() # time.sleep(wait_for_pen) prev_pix = pix # ------------------------------------------ print("----") positive = True prev_pix = 255 # X MOVE with wheels print("Move to next line!") print("Laser off!") self.laser(0) print("----> x ") # time.sleep(wait_for_pen) self.wait_to_finish() if not self.var1.get(): print("Straight print!") self.x_move_relative(steps=6) time.sleep(0.2) else: print("Curve print!") self.x_move_curve() time.sleep(0.4) # Done # self.pos_label.configure(text="Done printing!") self.run = False time.sleep(0.5) self.led.set_blue() self.homing = False
def body(self, master): frm_base = Frame(master) frm_base.pack(fill=BOTH) Label(frm_base, height="2", width="30", text="Account:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=15, pady=5) accounts = self.__user.accounts_names self.__account_from.set(accounts[0]) op = OptionMenu(frm_base, self.__account_from, *accounts) op.pack(padx=5, pady=5) op.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) Label(frm_base, height="2", width="30", text="Category:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__category_to.set(self.__categories[0]) op1 = OptionMenu(frm_base, self.__category_to, *self.__categories) op1.pack(padx=5, pady=5) op1.configure(relief=GROOVE, width="25", height="2", bg=DATA_COLOR, font=DATA_FONT, fg=DATA_FONT_COLOR) Label(frm_base, height="2", width="30", text="Amount:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__amount = Entry(frm_base, width="30") self.__amount.insert(END, "0.0") self.__amount.pack(padx=5, pady=5) Label(frm_base, height="2", width="30", text="Date:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__date = tkcalendar.DateEntry(frm_base, date_pattern='dd-mm-y') self.__date.pack(padx=5, pady=5) self.__date.set_date(datetime.date.today()) Label(frm_base, height="2", width="30", text="Description:", bg=BUTTON_COLOR, font=BUTTON_FONT, fg=BUTTON_FONT_COLOR).pack(padx=5, pady=5) self.__description = Entry(frm_base, width="30") self.__description.pack(padx=5, pady=5) return frm_base
class S3Zilla: def __init__(self, master): self.s3 = boto3.resource('s3') self.s3c = boto3.client('s3') light_gray = '#D9D9D9', blue = '#181B42', red = '#FF0000', black = '#000000', cyan = '#80DFFF' bold = 'Helvetica 10 bold underline' normal = 'Helvetica 10' rpath = realpath(__file__)[:-len(basename(__file__))] self.finish_thread = None self.greeting = 'Hello %s' % getuser() self.master = master self.master.title('Amazon S3 File Transfer Client') self.master.configure(bg=black) if platform != 'win32': desktop = {'plasma': '695x700', 'ubuntu': '625x700'} env = environ.get('DESKTOP_SESSION') if env is None or env not in desktop or env == 'ubunutu': self.master.maxsize('625', '700') self.master.minsize('625', '550') else: self.master.maxsize('695', '700') self.master.minsize('695', '550') self.master.geometry(desktop[env]) self.icon = PhotoImage(file=rpath + 'icon.png') master.iconphoto(False, self.icon) else: self.master.geometry('485x600') self.master.iconbitmap(rpath + 'icon.ico') self.master.maxsize('485', '700') self.master.minsize('485', '550') menu = Menu(self.master) menu.config(background=black, fg=light_gray) self.master.config(menu=menu) file = Menu(menu) file.add_command(label='Exit', command=self.quit_app) menu.add_cascade(label='File', menu=file) refresh = Menu(menu) refresh.add_command(label='Local', command=self.refresh_local) refresh.add_command(label='S3', command=self.refresh_s3) menu.add_cascade(label='Refresh', menu=refresh) self.dir, self.drp_sel, self.bucket_name = ['' for _ in range(3)] self.folder_path = StringVar() self.dropdown = StringVar() self.dropdown_data = self.populate_dropdown() if not self.dropdown_data: self.dropdown_data = ['none available'] self.deleted = False self.local_sel, self.s3_sel = ([] for _ in range(2)) self.local_label = Label(master, fg=light_gray, bg=black, text='LOCAL FILE SYSTEM', font=bold, width=24) self.local_label.grid(row=0, column=0, sticky=E + W, padx=10, pady=20) self.s3_label = Label(master, fg=light_gray, bg=black, text='AMAZON S3', font=bold, underline=True, width=24) self.s3_label.grid(row=0, column=1, sticky=E + W, padx=10, pady=20) self.dropdown_box = OptionMenu(master, self.dropdown, *self.dropdown_data, command=self.set_drop_val) self.dropdown_box.configure(fg=light_gray, bg=blue, width=16, highlightbackground=black, highlightthickness=2) self.dropdown_box.grid(row=1, column=1, sticky=E + W, padx=52, pady=10) self.browse_button = Button(master, fg=light_gray, bg=blue, text='Browse', width=16, highlightbackground=black, highlightthickness=2, command=self.load_dir) self.browse_button.grid(row=1, column=0, sticky=E + W, padx=52, pady=10) self.browse_label = Label(master, fg=light_gray, bg=black, text='No directory selected', width=24, font=normal) self.browse_label.grid(row=2, column=0, sticky=E + W, padx=10, pady=10) self.bucket_label = Label(master, fg=light_gray, bg=black, text='No bucket selected', width=24, font=normal) self.bucket_label.grid(row=2, column=1, sticky=E + W, padx=10, pady=10) self.refresh_btn_local = Button(master, fg=light_gray, bg=blue, text='REFRESH', width=10, highlightbackground=black, highlightthickness=2, command=self.refresh_local) self.refresh_btn_local.grid(row=3, column=0, sticky=E + W, padx=50, pady=10) self.refresh_btn_s3 = Button(master, fg=light_gray, bg=blue, text='REFRESH', width=10, highlightbackground=black, highlightthickness=2, command=self.refresh_s3) self.refresh_btn_s3.grid(row=3, column=1, sticky=E + W, padx=50, pady=10) self.ex_loc = Listbox(master, fg=cyan, bg=black, width=36, height=18, highlightcolor=black, selectmode='multiple') self.ex_loc.grid(row=5, column=0, sticky=E + W, padx=10, pady=10) self.ex_s3 = Listbox(master, fg=cyan, bg=black, width=36, height=18, highlightcolor=black, selectmode='multiple') self.ex_s3.grid(row=5, column=1, sticky=E + W, padx=10, pady=10) self.upload_button = Button(master, fg=light_gray, bg=blue, text='Upload ->', width=14, highlightbackground=black, highlightthickness=2, command=self.upload) self.upload_button.grid(row=6, column=0, sticky=E, padx=10, pady=10) self.download_button = Button(master, fg=light_gray, bg=blue, text='<- Download', width=14, highlightbackground=black, highlightthickness=2, command=self.download) self.download_button.grid(row=6, column=1, sticky=W, padx=10, pady=10) self.delete_local = Button(master, fg=light_gray, bg=blue, text='DELETE', width=14, highlightbackground=red, activebackground=red, command=self.delete_local_records) self.delete_local.grid(row=6, column=0, sticky=W, padx=10, pady=10) self.delete_s3 = Button(master, fg=light_gray, bg=blue, text='DELETE', width=14, highlightbackground=red, activebackground=red, command=self.delete_s3_records) self.delete_s3.grid(row=6, column=1, sticky=E, padx=10, pady=10) self.found_label_local = Label(master, fg=light_gray, bg=black, text='found local', width=16) self.found_label_local.grid(row=7, column=0, sticky=E + W, padx=10, pady=10) self.found_label_s3 = Label(master, fg=light_gray, bg=black, text='found s3', width=16) self.found_label_s3.grid(row=7, column=1, sticky=E + W, padx=10, pady=10) self.status_label = Label(master, fg=light_gray, bg=black, text=self.greeting, width=8) self.status_label.grid(row=8, column=0, sticky=E + W, padx=10, pady=10) self.create_bucket_label = Label(master, fg=light_gray, bg=black, text='New Bucket:', width=10) self.create_bucket_label.grid(row=8, column=1, sticky=W, padx=1, pady=1) if platform != 'win32': self.create_bucket_name = Text(master, fg=cyan, bg=black, width=15, height=1) self.create_bucket_button = Button(master, fg=light_gray, bg=blue, text='Create', width=5, highlightbackground=black, highlightthickness=2, command=self.create_bucket) else: self.create_bucket_name = Text(master, fg=cyan, bg=black, width=11, height=1) self.create_bucket_button = Button(master, fg=light_gray, bg=blue, text='Create', width=7, highlightbackground=black, highlightthickness=2, command=self.create_bucket) self.create_bucket_name.grid(row=8, column=1, padx=1, pady=10) self.create_bucket_button.grid(row=8, column=1, sticky=E, padx=10, pady=10) self.master.grid_columnconfigure(0, weight=1) self.master.grid_columnconfigure(1, weight=1) self.master.grid_rowconfigure(5, weight=1) self.set_found_local_label('%d files found' % self.ex_loc.size()) self.set_found_s3_label('%d files found' % self.ex_s3.size()) @staticmethod def quit_app(): exit() def get_local_sel(self): return [self.ex_loc.get(i) for i in self.ex_loc.curselection()] def get_s3_sel(self): return [self.ex_s3.get(i) for i in self.ex_s3.curselection()] def set_drop_val(self, selection): self.drp_sel = selection def delete_local_records(self): files = self.get_local_sel() if not files: self.set_status_label('Please select a file(s) to delete') else: title = 'DELETE FROM LOCAL FILE SYSTEM?' msg = 'The following will be removed:\n\n%s' % '\n'.join(files) if askyesno(title, msg): self.del_local(files) def del_local(self, files_remaining): if len(files_remaining) > 0: current = files_remaining.pop(0) if not isdir(self.dir + '/' + current): try: remove('%s/%s' % (self.dir, current)) except Exception as e: self.set_status_label('%s' % e) self.del_local(files_remaining) else: try: rmtree('%s/%s' % (self.dir, current)) except Exception as e: self.set_status_label('%s' % e) self.del_local(files_remaining) self.deleted = True self.refresh_local() def delete_s3_records(self): removal = [] if not self.drp_sel: self.set_status_label('Please select a bucket...') else: removal = self.get_s3_sel() if not removal: self.set_status_label('Please select at least 1 object to delete') else: title = 'DELETE FROM AMAZON S3?' msg = 'The following will be removed:\n\n%s' % '\n'.join(removal) if askyesno(title, msg): bucket = self.s3.Bucket(self.drp_sel) for rm in removal: for k in bucket.objects.all(): if k.key != rm: continue k.delete() break self.deleted = True self.refresh_s3() def load_dir(self): self.dir = askdirectory() if not self.dir: self.set_status_label('Ensure a directory is selected') self.dir = '' elif not isdir(self.dir): self.set_status_label('Ensure a directory is selected') self.dir = '' else: self.set_local_browse_label(self.dir) def refresh_local(self): if not self.dir: self.set_status_label('Please select a directory (browse button)') else: self.set_local_browse_label(self.dir) self.ex_loc.delete(0, 'end') x = self.dir + '/' d = [ f if not isdir(x + f) else f + '/' for f in sorted(listdir(x)) ] self.ex_loc.insert('end', *d) if not self.deleted: msg = self.greeting else: msg = 'FINISHED DELETING' self.deleted = False self.set_status_label(msg) files_found = '%d files found' % self.ex_loc.size() self.set_found_local_label(files_found) def refresh_s3(self): if 'none available' in self.dropdown_data: self.set_status_label('Please create at least one S3 bucket') elif not self.drp_sel: self.set_status_label('Select a bucket from the drop-down list') else: self.ex_s3.delete(0, 'end') try: self.ex_s3.insert('end', *self.get_bucket_contents()) except Exception: self.set_status_label('Unable to find bucket') else: self.set_status_label(self.greeting) self.set_s3_bucket_label(self.drp_sel) files_found = '%d files found' % self.ex_s3.size() self.set_found_s3_label(files_found) if not self.deleted: msg = self.greeting else: msg = 'FINISHED DELETING' self.deleted = False self.set_status_label(msg) def finish(self, incoming_message): marquee = 'FINISHED %s' % incoming_message for letter in enumerate(marquee): self.set_status_label(marquee[0:letter[0] + 1]) sleep(.04) def upload(self): if not self.drp_sel or not self.dir: self.set_status_label('Ensure a path & S3 bucket are selected') elif not self.get_local_sel(): self.set_status_label('Ensure files are selected to upload') else: for selection in self.get_local_sel(): file_ = '%s/%s' % (self.dir, selection) if not isdir(file_): self.s3c.upload_file(file_, self.drp_sel, basename(file_)) else: zipd = make_archive(file_, 'zip', self.dir, selection) self.s3c.upload_file(zipd, self.drp_sel, basename(zipd)) remove(zipd) self.set_status_label('Uploaded: %s' % selection) self.refresh_s3() self.finish_thread = Thread(target=self.finish, args=['UPLOAD']) self.finish_thread.start() def download(self): if not self.drp_sel or not self.dir: self.set_status_label('Ensure a file & bucket are selected') elif not self.get_s3_sel(): self.set_status_label('Ensure files are selected to download') else: for selection in self.get_s3_sel(): file_ = '%s/%s' % (self.dir, selection) self.s3c.download_file(self.drp_sel, selection, file_) self.refresh_local() self.finish_thread = Thread(target=self.finish, args=['DOWNLOAD']) self.finish_thread.start() def get_bucket_contents(self): bucket = self.s3.Bucket(self.drp_sel) return [s3_file.key for s3_file in bucket.objects.all()] def populate_dropdown(self): return [bucket.name for bucket in self.s3.buckets.all()] def set_local_browse_label(self, incoming): if len(incoming) > 35: self.browse_label.config(text=basename(incoming) + '/') else: self.browse_label.config(text=incoming) def set_s3_bucket_label(self, incoming): self.bucket_label.config(text=incoming) def set_status_label(self, incoming): self.status_label.config(text=incoming) self.status_label.update_idletasks() def set_found_local_label(self, incoming): self.found_label_local.config(text=incoming) self.found_label_local.update_idletasks() def set_found_s3_label(self, incoming): self.found_label_s3.config(text=incoming) self.found_label_s3.update_idletasks() def create_bucket(self): self.bucket_name = self.create_bucket_name.get('1.0', END).strip() if not self.bucket_name: self.set_status_label('Please enter a new bucket name') else: try: self.s3.create_bucket(Bucket=self.bucket_name) except ClientError: self.set_status_label('Bucket name is already in use') else: msg = '%s created: restarting...' % self.bucket_name self.set_status_label(msg) self.status_label.update_idletasks() res = executable execl(res, res, *argv)
def __top_frame(self): """ Create top frame content """ self._selected_modulation = StringVar(self._tk_obj) self._selected_channel = StringVar(self._tk_obj) self._selected_sync_mode = StringVar(self._tk_obj) self._cbx_manchester_value = IntVar(self._tk_obj) frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff') frame.grid(column=0, row=0, padx=15, pady=15, sticky=W + E) frame.grid_rowconfigure(0, weight=1) frame.grid_columnconfigure(0, weight=1) # headline lab_section = Label(frame, text="Default RF Settings") lab_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E) lab_section.configure(font=self.__FONT_HEADLINE) # frequency lab_frequency = Label(frame, text='Frequency') lab_frequency.grid(column=0, row=1, padx=5, pady=5, sticky=E) lab_frequency.configure(font=self.__FONT_STYLE) self._ety_frequency = Entry(frame) self._ety_frequency.grid(column=1, row=1, padx=5, pady=5, sticky=W) self._ety_frequency.configure(font=self.__FONT_STYLE) value_frequency = self.rf_object.getFreq() self._ety_frequency.insert(0, int(value_frequency[0])) # modulation lab_modulation = Label(frame, text='Modulation') lab_modulation.grid(column=0, row=2, padx=5, pady=5, sticky=E) lab_modulation.configure(font=self.__FONT_STYLE) opm_modulation = OptionMenu(frame, self._selected_modulation, *self.__MODULATION_OPTIONS) opm_modulation.grid(column=1, row=2, padx=5, pady=5, sticky=W) opm_modulation.configure(font=self.__FONT_STYLE) value_modulation = self.rf_object.getMdmModulation() if value_modulation == 0: self._selected_modulation.set(self.__MODULATION_OPTIONS[1]) elif value_modulation == 16: self._selected_modulation.set(self.__MODULATION_OPTIONS[2]) elif value_modulation == 48: self._selected_modulation.set(self.__MODULATION_OPTIONS[3]) elif value_modulation == 112: self._selected_modulation.set(self.__MODULATION_OPTIONS[4]) else: self._selected_modulation.set(self.__MODULATION_OPTIONS[0]) # channel lab_channel = Label(frame, text='Channel') lab_channel.grid(column=0, row=3, padx=5, pady=5, sticky=E) lab_channel.configure(font=self.__FONT_STYLE) sbx_channel = Spinbox(frame, state='readonly') sbx_channel.grid(column=1, row=3, padx=5, pady=5, sticky=W) sbx_channel.configure(font=self.__FONT_STYLE) self._selected_channel.set(self.rf_object.getChannel()) sbx_channel.configure(from_=0, to=10, increment=1, textvariable=self._selected_channel) # baud rate lab_baud = Label(frame, text='Baud Rate') lab_baud.grid(column=2, row=1, padx=5, pady=5, sticky=E) lab_baud.configure(font=self.__FONT_STYLE) self._ety_baud = Entry(frame) self._ety_baud.grid(column=3, row=1, padx=5, pady=5, sticky=W) self._ety_baud.configure(font=self.__FONT_STYLE) self._ety_baud.insert(0, int(self.rf_object.getMdmDRate())) # deviation lab_deviation = Label(frame, text='Deviation') lab_deviation.grid(column=2, row=2, padx=5, pady=5, sticky=E) lab_deviation.configure(font=self.__FONT_STYLE) self._ety_deviation = Entry(frame) self._ety_deviation.grid(column=3, row=2, padx=5, pady=5, sticky=W) self._ety_deviation.configure(font=self.__FONT_STYLE) self._ety_deviation.insert(0, int(self.rf_object.getMdmDeviatn())) self._ety_deviation.configure(state='readonly') # channel bandwidth lab_channel_bandwidth = Label(frame, text='Channel BW') lab_channel_bandwidth.grid(column=2, row=3, padx=5, pady=5, sticky=E) lab_channel_bandwidth.configure(font=self.__FONT_STYLE) self._ety_channel_bandwidth = Entry(frame) self._ety_channel_bandwidth.grid(column=3, row=3, padx=5, pady=5, sticky=W) self._ety_channel_bandwidth.configure(font=self.__FONT_STYLE) self._ety_channel_bandwidth.insert(0, int(self.rf_object.getMdmChanBW())) self._ety_channel_bandwidth.configure(state='readonly') # sync mode lab_sync_mode = Label(frame, text='Sync Mode') lab_sync_mode.grid(column=4, row=1, padx=5, pady=5, sticky=E) lab_sync_mode.configure(font=self.__FONT_STYLE) sbx_sync_mode = Spinbox(frame, state='readonly') sbx_sync_mode.grid(column=5, row=1, padx=5, pady=5, sticky=W) sbx_sync_mode.configure(font=self.__FONT_STYLE) self._selected_sync_mode.set(self.rf_object.getMdmSyncMode()) sbx_sync_mode.configure(from_=0, to=7, increment=1, textvariable=self._selected_sync_mode) # sync word lab_sync_word = Label(frame, text='Sync Word') lab_sync_word.grid(column=4, row=2, padx=5, pady=5, sticky=E) lab_sync_word.configure(font=self.__FONT_STYLE) self._ety_sync_word = Entry(frame) self._ety_sync_word.grid(column=5, row=2, padx=5, pady=5, sticky=W) self._ety_sync_word.configure(font=self.__FONT_STYLE) self._ety_sync_word.insert(0, self.rf_object.getMdmSyncWord()) self._ety_sync_word.configure(state='readonly') # channel spacing lab_channel_spacing = Label(frame, text='Channel Spacing') lab_channel_spacing.grid(column=4, row=3, padx=5, pady=5, sticky=E) lab_channel_spacing.configure(font=self.__FONT_STYLE) self._ety_channel_spacing = Entry(frame) self._ety_channel_spacing.grid(column=5, row=3, padx=5, pady=5, sticky=W) self._ety_channel_spacing.configure(font=self.__FONT_STYLE) value_channel_spacing = self.rf_object.getMdmChanSpc() self._ety_channel_spacing.insert(0, int(value_channel_spacing)) self._ety_channel_spacing.configure(state='readonly') # enable manchester lab_manchester = Label(frame, text='Enable Manchester') lab_manchester.grid(column=0, row=4, padx=5, pady=5, sticky=E) lab_manchester.configure(font=self.__FONT_STYLE) cbx_manchester = Checkbutton(frame) cbx_manchester.grid(column=1, row=4, padx=5, pady=5, sticky=W) if self.rf_object.getEnableMdmManchester() == 1: self._cbx_manchester_value.set(1) else: self._cbx_manchester_value.set(0) cbx_manchester.configure(onvalue=1, offvalue=0, variable=self._cbx_manchester_value) # save settings self._btn_save_settings = Button(frame, text='Save all Settings', command=self.__action_store_settings) self._btn_save_settings.grid(column=5, row=4, padx=5, pady=5) self._btn_save_settings.configure(font=self.__FONT_STYLE) self._btn_save_settings.bind( "<Enter>", lambda event: event.widget.config(fg='indian red')) self._btn_save_settings.bind( "<Leave>", lambda event: event.widget.config(fg='black'))
choices=["Deposit","Withdraw","Zero"] ch.set(choices[0]) def ch_getter(selection): if selection=="Withdraw": b["text"]="Withdrawal" if selection=="Deposit": b["text"]="Deposit" if selection=="Zero": b["text"]="Zero" selection=ch.get() popupMenu = OptionMenu(root, ch, *choices,command=ch_getter) popupMenu.config(width=10, font=('Helvetica', 12)) popupMenu.configure(bg='pale violet red') popupMenu.place(x=255,y=200) root.mainloop() print(dict_entries) """ if __name__=="__main__": #just in case I use this file in the future as a module init()
class ObjFormatter: """ The main widget """ def __init__(self, root): # if MY_OS == 'Windows': imgpad = 155 xpadd = 5 ypadd = 5 basefont = 10 entryfont = 11 buttonpad = 202 elif MY_OS == 'Linux': imgpad = 170 xpadd = 5 ypadd = 5 basefont = 12 entryfont = 14 buttonpad = 210 else: imgpad = 190 xpadd = 5 ypadd = 5 basefont = 14 entryfont = 16 buttonpad = 210 # # Main widget background image frame0 = Frame(root) logoimgpath = resource_path("UPackLogo300.jpg") logo = Image.open(logoimgpath) self.logoimage = ImageTk.PhotoImage(logo) self.logoimglabel = Label(frame0, image=self.logoimage) self.logoimglabel.configure(bg='black', bd=0, relief='flat') self.logoimglabel.grid(column=0, row=0, pady=7, padx=imgpad, sticky='e') frame0.configure(bg=hokiestone, bd=5, relief='sunken') frame0.grid(column=0, row=0, pady=0, padx=0, sticky='nsew') # Entry for the Folder that contains the items frame1 = Frame(root) itemfolder = StringVar(frame1) labl1 = Label(frame1, text='Folder of\nItems:') labl1.configure(fg='black', bg=vtgray, bd=0, font=('Arial', basefont), height=2, width=9, justify='center') labl1.grid(column=0, row=0, pady=5, padx=5, sticky='e') browse1 = Button(frame1, text='Browse', command=lambda: self.ask_folder(itemfolder)) browse1.configure(bg=vtsmoke, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont)) browse1.grid(column=2, row=0, pady=5, padx=5, sticky='w') self.e1 = Entry(frame1, width=50, textvariable=itemfolder) self.e1.configure(bg=vtsmoke, relief='sunken', bd=2, font=('Arial', entryfont + 2), justify='left') self.e1.grid(column=1, row=0, pady=5, padx=0, sticky='w') # Entry for the master CSV metadata file csvfile = StringVar(frame1) labl2 = Label(frame1, text='CSV File:') labl2.configure(fg='black', bg=vtgray, bd=0, font=('Arial', basefont), height=2, width=9, justify='center') labl2.grid(column=0, row=1, pady=5, padx=5, sticky='e') browse2 = Button(frame1, text='Browse', command=lambda: self.ask_file(csvfile)) browse2.configure(bg=vtsmoke, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont), relief='raised') browse2.grid(column=2, row=1, pady=5, padx=5, sticky='w') self.e2 = Entry(frame1, width=50, textvariable=csvfile) self.e2.configure(bg=vtsmoke, relief='sunken', bd=2, font=('Arial', entryfont + 2), justify='left') self.e2.grid(column=1, row=1, pady=5, padx=0, sticky='w') # Drop-Down of the column headings in the master CSV file labl3 = Label(frame1, text='CSV Col.\nw/ ID\'s:') labl3.configure(fg='black', bg=vtgray, bd=0, font=('Arial', basefont), height=2, width=9, justify='center') labl3.grid(column=0, row=2, pady=5, padx=5, sticky='e') self.variable = StringVar(frame1) self.options = StringVar(frame1) self.options.trace('r', self.get_headers) firstone = ["Select CSV", "Then \'Refresh\'"] self.hdmenu = OptionMenu(frame1, self.variable, *firstone) self.hdmenu.configure(width=20, bg=vtmaroon, font=('Arial', basefont + 2)) self.hdmenu.grid(column=1, row=2, pady=5, padx=0, sticky='e') self.e3 = Entry(frame1, width=24, textvariable=self.variable) self.e3.configure(bg=vtsmoke, relief='sunken', bd=2, font=('Arial', entryfont + 2), justify='left') self.e3.grid(column=1, row=2, pady=5, padx=0, sticky='w') refresh1 = Button(frame1, text='Refresh', command=lambda: self.get_headers(csvfile)) refresh1.configure(bg=vtsmoke, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont)) refresh1.grid(column=2, row=2, pady=5, padx=5, sticky='w') frame1.configure(bg=vtmaroon, bd=5, relief='raised') frame1.grid(column=0, row=1, pady=0, padx=0, sticky='nsew') # Checkbuttons frame2 = ToggleFrame(root) frame2.configure(bg=hokiestone, bd=5, relief='sunken') frame2.grid(column=0, row=2, pady=0, padx=0, sticky='n') # Buttons for Quit, Instructions, and Submit frame3 = Frame(root) cancel1 = Button(frame3, text='Quit', command=root.quit) cancel1.configure(bg=vtwhite, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont)) cancel1.grid(column=0, row=0, pady=5, padx=xpadd, sticky='e') instruct = Button(frame3, text='Instructions', command=lambda: instructions(basefont)) instruct.configure(bg=vtwhite, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont)) instruct.grid(column=1, row=0, pady=5, padx=buttonpad, sticky='e') submit1 = Button(frame3, text='Submit', command=lambda: self.run_procs(root, frame2)) submit1.configure(bg=vtwhite, fg='black', highlightbackground=vtmaroon, font=('Arial', entryfont)) submit1.grid(column=2, row=0, pady=5, padx=xpadd, sticky='e') frame3.configure(bg=vtmaroon, bd=5, relief='raised') frame3.grid(column=0, row=3, pady=0, padx=0, sticky='nsew') def ask_folder(self, foname): foname.set( path.abspath( askdirectory(initialdir=getcwd(), title='Select the Folder'))) return foname def ask_file(self, fname): fname.set( path.abspath( askopenfilename(initialdir=getcwd(), title='Select the master CSV File'))) return fname def get_headers(self, *args): """ Retrieves the options for the drop-down menu of CSV headers """ csvfi = self.e2.get() csvpath = path.join(str(csvfi)) if path.exists(csvpath) and path.splitext(csvpath)[1] == '.csv': with open(csvfi, 'r', encoding='utf-8') as cfile: hreader = csv.DictReader(cfile) opts = hreader.fieldnames else: opts = ["Select CSV", "Then \'Refresh\'"] self.variable.set(opts[0]) menu = self.hdmenu['menu'] menu.delete(0, 'end') for headr in opts: menu.add_command( label=headr, command=lambda idcolumn=headr: self.variable.set(idcolumn)) def make_rdf(self, metacsv): """ Turns 'metadata.csv' into an RDF metadata file, called 'metadata.xml' This could be done using a CSV-to-XML conversion, but it's easier to just read the values for the fields and write the RDF file manually. """ if not path.exists(metacsv): messagebox.showwarning( message= "Error: The \'metadata.csv\' was not found.\nRDF file not created." ) return False with open(metacsv, 'r', encoding='utf-8') as src: reader2 = csv.DictReader(src) headrow2 = reader2.fieldnames for row in reader2: sysUUID = str(row['System UUID']) localID = str(row['Local ID']) deptName = str(row['Department Responsible']) persVTID = str(row['Person Responsible']) collName = str(row['Collection']) description = str(row['Brief Description']) objURI = str(row['Object URI']) collURI = str(row['Collection URI']) src.close() # messagebox.showwarning(message="It got this far! Next step is create the Graph.") g = Graph() # Namespaces rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#") g.bind('rdf', rdf, False) rdfs = Namespace("http://www.w3.org/2000/01/rdf-schema#") g.bind('rdfs', rdfs, False) dc = Namespace("http://dublincore.org/2012/06/14/dcelements.rdf#") g.bind('dc', dc, False) dcterms = Namespace("http://purl.org/dc/terms#") g.bind('dcterms', dcterms, False) dcmitype = Namespace("http://purl.org/dc/dcmitype#") g.bind('dcmitype', dcmitype, False) foaf = Namespace("http://xmlns.com/foaf/spec/index.rdf#") g.bind('foaf', foaf, False) owl = Namespace("http://www.w3.org/2002/07/owl#") g.bind('owl', owl, False) premis = Namespace("http://www.loc.gov/premis/rdf/v3#") g.bind('premis', premis, False) mets = Namespace("http://www.loc.gov/standards/mets/mets.xsd#") g.bind('mets', mets, False) # Establishing subjects for triples object = URIRef(objURI) persID = BNode() g.bind('personID', persID, False) deptID = BNode() g.bind('departmentID', deptID, False) collectID = URIRef(collURI) g.bind('collectionID', collectID, False) metsCustodian = URIRef( 'http://www.loc.gov/standards/mets/mets.xsd#CUSTODIAN') g.bind('custodian', metsCustodian, False) # Adding the triples to the Graph g.add((object, dcterms.identifier, Literal('%s' % sysUUID))) g.add((object, mets.OBJID, Literal('%s' % sysUUID))) g.add((object, mets.altRecordID, Literal('%s' % localID))) g.add((object, dc.contributor, deptID)) g.add((deptID, rdf.type, foaf.Group)) g.add((deptID, mets.ROLE, metsCustodian)) g.add((deptID, foaf.name, Literal('%s' % deptName))) g.add((object, dc.contributor, persID)) g.add((persID, rdf.type, foaf.Person)) g.add((persID, mets.ROLE, metsCustodian)) g.add((persID, foaf.mbox, Literal('%s (at) vt (dot) edu' % persVTID))) # g.add((persID, foaf.name, Literal('%s' %persName))) g.add((object, dcterms.isPartOf, collectID)) g.add((collectID, foaf.name, Literal('%s' % collName))) g.add((object, dcterms.description, Literal('%s' % description))) newrdf = path.join(path.dirname(metacsv), 'metadata.xml') serialrdf = g.serialize(format='pretty-xml') # serialjson = g.serialize(format='json-ld') with open(newrdf, 'wb') as outrdf: outrdf.write(serialrdf) outrdf.close() # jsonfile = path.join(path.dirname(metacsv), 'metadata.json') # with open(jsonfile, 'w', encoding='utf-8') as outjson: # outjson.write(serialjson) # outjson.close() return True def meta_from_csv(self, csvIn, locids, fpath): nfiles = 0 rfiles = 0 overwrite_all = False firstone = True with open(csvIn, 'r', encoding='utf-8') as incsv: reader = csv.DictReader(incsv) headers = reader.fieldnames verifyHeadrs = [ 'System UUID', 'Local ID', 'Department Responsible', 'Person Responsible', 'Collection', 'Brief Description', 'Object URI', 'Collection URI' ] if not headers == verifyHeadrs: messagebox.showwarning( message= "Your input CSV is not formatted correctly.\n\nQuitting action." ) return [0, 0] for row in reader: skip1 = False foldname = row['%s' % locids] foldpath = path.join(fpath, foldname) if not path.exists(foldpath): skip1 = True # The function skips objects that are Bags or already have a # 'metadata.csv' file. Thus it skips creating a 'metadata.xml' # for these objects also. if path.exists(path.join(foldpath, 'data')): skip1 = messagebox.askyesno( message= "It appears that \'%s\' is a bag.\n\nSkip creating \'metadata.csv\' for this one item?" % foldname) if path.exists(path.join(foldpath, 'metadata.csv')) and firstone == True: firstone = False overwrite_all = messagebox.askyesno( message= "At least one \'metadata.csv\' already\nexists. Overwrite ALL of them?" ) if path.exists(path.join( foldpath, 'metadata.csv')) and overwrite_all == False: skip1 = True if skip1 == False: metafile = path.join(foldpath, 'metadata.csv') with open(metafile, 'w') as newmeta: metawriter = csv.DictWriter(newmeta, fieldnames=headers) metawriter.writeheader() metawriter.writerow(row) nfiles += 1 newmeta.close() rdfok = self.make_rdf(metafile) if rdfok == True: rfiles += 1 return [nfiles, rfiles] def create_meta(self, root, folderpath, myfile, idcolname, moreopts1): """ Generates minimal metadata files, 'metadata.csv' and 'metadata.xml' based on a master CSV or a METS xml file """ sourcetype = 'csv' # default counts = [0, 0] # default if path.splitext(myfile)[1] == '.csv': sourcetype = 'csv' else: messagebox.showwarning( message= "The metadata source file must be CSV.\nQuitting action.") runnext1 = False return runnext1 if sourcetype == 'csv': counts = self.meta_from_csv(myfile, idcolname, folderpath) if not moreopts1 == 0: if self.prompting == 0: runnext1 = True else: runnext1 = messagebox.askyesno( message= "Created %d \'metadata.csv\' and %d \'metadata.xml\' files.\n\nProceed with the next action?" % (counts[0], counts[1])) else: runnext1 = False messagebox.showwarning( message= "Created %d \'metadata.csv\' and %d \'metadata.xml\' files." % (counts[0], counts[1])) return runnext1 def gen_ID(self): """ Function to generate a System UUID. In future this will request a NOID and ARK from the naming authority """ SysUID = 'vtdata_' + str(uuid.uuid4()) return SysUID def register_obj(self, ofolder, moreopts2): """ Function to assign System UUID's to objects and register them in the UDCS (a) generate UUID from single naming authority (b) log the obj. in a system Processing Log (c) create placeholder metadata on the Metadata Server (d) update the minimal 'metadata' files with the System UUID """ renamed = 0 rfiles = 0 logfile = path.join(ofolder, 'log4preservation.csv') if not path.exists(logfile): with open(logfile, 'w', encoding='utf-8') as lfile: headrow = ['SysUID', 'LocalID', 'RegisDateTime', 'RegisPerson'] writer = csv.DictWriter(lfile, fieldnames=headrow) writer.writeheader() lfile.close() for fo in listdir(ofolder): skip3 = False fopath = path.join(ofolder, fo) if not path.isdir(fopath): skip3 = True elif path.isdir(fopath): metapath = path.join(fopath, 'metadata.csv') oldrdf = path.join(fopath, 'metadata.xml') # oldjson = path.join(fopath, 'metadata.json') if not path.exists(metapath): skip3 = True messagebox.showwarning( message= "Could not find:\n\'%s\'.\n\nSkipping registration of:\n%s." % (metapath, fo)) if not skip3: newID = self.gen_ID() with open(metapath, 'r', encoding='utf-8') as oldmeta: r = csv.reader(oldmeta) lines = list(r) lines[1][0] = newID log1 = newID log2 = lines[1][1] log3 = time.strftime("%Y.%m.%d %H:%M:%S") log4 = lines[1][3] logline = [log1, log2, log3, log4] with open(logfile, 'a', encoding='utf-8') as logoutf: cwriter = csv.writer(logoutf) cwriter.writerow(logline) with open(metapath, 'w', encoding='utf-8') as outmeta: w = csv.writer(outmeta) w.writerows(lines) if path.exists(oldrdf): remove(oldrdf) # if path.exists(oldjson): # remove(oldjson) rdfok = self.make_rdf(metapath) if rdfok == True: rfiles += 1 newpath = path.join(path.dirname(fopath), '%s' % newID) rename(fopath, newpath) renamed += 1 if not moreopts2 == 0: if self.prompting == 0: runnext2 = True else: runnext2 = messagebox.askyesno( message= "Registered %d objects.\n\nProceed with the next action?" % renamed) else: runnext2 = False messagebox.showwarning(message="Registered %d objects." % renamed) return runnext2 def md5(self, finame): """ Data Services requested Md5 hashes but Md5 is deprecated """ hash_md5 = hashlib.md5() with open(finame, "rb") as md5file: for chunk in iter(lambda: md5file.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def sha3hash(self, filname): """ Generates SHA3-256 hashes """ chunksize = io.DEFAULT_BUFFER_SIZE hash_sha3 = hashlib.sha3_256() with open(filname, "rb") as sha3file: for chunks in iter(lambda: sha3file.read(chunksize), b""): hash_sha3.update(chunks) return hash_sha3.hexdigest() def convert_size(self, size): """ Converts bytes to human readable denominations """ if (size == 0): return '0B' # size_name = ("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB") # i = int(math.floor(math.log(size,1024))) # p = math.pow(1024,i) size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size, 1000))) p = math.pow(1000, i) s = round(size / p, 2) return '%s%s' % (s, size_name[i]) def run_inventory(self, indir, moreopts3): """ Runs an inventory and generates 'manifest.csv' files for each object """ manifiles = 0 for obj in listdir(indir): objpath = path.join(indir, obj) skipit = False counter = 0 if not path.isdir(objpath): skipit = True elif path.isdir(objpath): if path.exists(path.join(objpath, 'data')): isabag = messagebox.askyesno( message= "It appears that \'%s\' is a bag.\nSkip this object?" % obj) if isabag == True: skipit = True if path.exists(path.join(objpath, 'manifest.csv')): skipit = True messagebox.showwarning( message= "The file \'manifest.csv\' already exists.\nSkipping inventory of the object: \n\'%s\'" % obj) if skipit == False: manifiles += 1 tempmani = open(path.join(indir, 'temp_manifest.csv'), 'w', encoding='utf-8') tempmani.write( "No., Filename, Filesize, Filetype, C-Time, Modified, Accessed, MD5_Sum, SHA3_256, ChecksumDateTime, RelPath, => , mode, inode, device, enlink, user, group\n" ) workdir = path.dirname(objpath) for base, dirs, files in walk(objpath): for name in files: filepathname = path.join(base, name) # Deletes .DS_Store Files if path.basename(filepathname) == '.DS_Store': remove(filepathname) elif not path.basename(filepathname) == '.DS_Store': counter += 1 rownum = str(counter) statinfo = stat(filepathname) filesize = statinfo[6] csize = self.convert_size(filesize) filemime = str( mimetypes.guess_type(filepathname)[0]) filectime = time.strftime( "%Y.%m.%d %H:%M:%S", time.localtime(statinfo.st_ctime)) # note: on a Windows system, ctime is "date created" but on Unix it is # "change time", i.e. the last time the metadata was changed. modifdate = time.strftime( "%Y.%m.%d %H:%M:%S", time.localtime(statinfo.st_mtime)) accessdate = time.strftime( "%Y.%m.%d %H:%M:%S", time.localtime(statinfo.st_atime)) md5sum = self.md5(filepathname) sha3sum = self.sha3hash(filepathname) runtime = time.strftime("%Y.%m.%d %H:%M:%S") filemode = str(statinfo.st_mode) fileino = str(statinfo.st_ino) filedevice = str(statinfo.st_dev) filenlink = str(statinfo.st_nlink) fileuser = str(statinfo.st_uid) filegroup = str(statinfo.st_gid) # Displays a shortened Path for each file, excluding the directories # that precede the working directory that contains the objects. showpath = path.relpath(filepathname, workdir) tempmani.write("%s," % rownum + "\"%s\"," % name + "%s," % csize + "\"%s\"," % filemime + "%s," % filectime + "%s," % modifdate + "%s," % accessdate + "%s," % md5sum + "%s," % sha3sum + "%s," % runtime + "\"%s\"," % showpath) tempmani.write(" ,%s," % filemode + "%s," % fileino + "%s," % filedevice + "%s," % filenlink + "%s," % fileuser + "%s\n" % filegroup) tempmani.write("Comments, \n") tempmani.close() tomove = path.join(path.dirname(objpath), 'temp_manifest.csv') moveto = path.join(objpath, 'manifest.csv') shutil.move(tomove, moveto) if not moreopts3 == 0: if self.prompting == 0: runnext3 = True else: runnext3 = messagebox.askyesno( message= "Created %d \'manifest.csv\' files.\n\nProceed with the next action?" % manifiles) else: runnext3 = False messagebox.showwarning( message="Created %d \'manifest.csv\' files." % manifiles) return runnext3 def run_bagit(self, bagsdir, moreopts4): """ Bags all objects in a single directory """ validbags = 0 totalbags = 0 for f in listdir(bagsdir): inpath = path.join(bagsdir, f) cont = True if path.isdir(inpath): if path.exists(path.join(inpath, 'data')): cont = messagebox.askyesno( message= "It appears that \'%s\' is already a bag.\nBag it anyway?" % f) if cont == True: newbag = bagit.make_bag(inpath, checksums=['md5', 'sha512']) totalbags += 1 if newbag.is_valid(): validbags += 1 elif not newbag.is_valid(): messagebox.showwarning( message="Bag \'%s\' is not a valid bag." % f) # elif cont == False: # messagebox.showwarning(message="Skipped bagging of \'%s\'." %f) if not moreopts4 == 0: if self.prompting == 0: runnext4 = True else: runnext4 = messagebox.askyesno( message= "Created %d total bags,\nof which %d are valid.\n\nProceed with the next action?" % (totalbags, validbags)) else: runnext4 = False messagebox.showwarning( message="Created %d total bags,\nof which %d are valid." % (totalbags, validbags)) return runnext4 def run_tar(self, tarfolder, moreopts5): """ Tars all objects in a single directory """ tarfiles = 0 alreadytar = 0 notfolder = 0 outfolder = path.splitext(tarfolder)[0] + '-tarred' if not path.exists(outfolder): mkdir(outfolder) for i in listdir(tarfolder): infile = path.join(tarfolder, i) if path.isdir(infile): outfile = path.join(outfolder, path.splitext(i)[0] + '.tar') if path.exists(outfile): messagebox.showwarning( message= "The TAR file: \n\'%s\'\nalready exists!\nTar archive not created." % outfile) alreadytar += 1 elif not path.exists(outfile): # with tarfile.open(outfile, 'w:gz') as newtar: with tarfile.open(outfile, 'w') as newtar: tarname = path.relpath(infile, tarfolder) newtar.add(infile, arcname='%s' % tarname) tarfiles += 1 else: notfolder += 1 if not alreadytar == 0: messagebox.showwarning( message= "The folder \'%s\' already contained %d tar files which were skipped." % (outfolder, alreadytar)) # if not notfolder == 0: # messagebox.showwarning(message="The target folder contained %d files, which were ignored." %notfolder) if not moreopts5 == 0: if self.prompting == 0: runnext5 = True else: runnext5 = messagebox.askyesno( message= "Created %d tar archives.\n\nProceed with the next action?" % tarfiles) else: runnext5 = False messagebox.showwarning(message="Created %d tar archives." % tarfiles) return runnext5 def trans_manifest(self, indirectory): """ Generates a manifest of filenames and checksums for a directory of Bagged and Tarred objects """ askingdir = path.join(path.basename(path.dirname(indirectory)), path.basename(indirectory)) indir = "" tardest = messagebox.askyesno( message="Create manifest of \'%s-tarred\'?" % askingdir, default='yes') if tardest: indir = indirectory + "-tarred" elif not tardest: indir = askdirectory( initialdir=path.dirname(indirectory), title="In which folder are the objects to be transferred?") if not path.exists(indir): messagebox.showwarning( message= "The directory: \n\'%s\'\n does not exist.\n\nCancelling action." % indir) return outdir = path.dirname(indir) # messagebox.showwarning(message="The transfer manifest will be saved in: \n\'%s\'" %outdir) compfile = open(path.join( outdir, "Transfer_%s_%s.csv" % (path.basename(indir), time.strftime("%m%d_%H%M%S"))), 'w', encoding='utf-8') for base, dirs, files in walk(indir): for name in files: pathname = path.join(base, name) if path.basename(pathname) == '.DS_Store': remove(pathname) elif not path.basename(pathname) == '.DS_Store': sha3sum = self.sha3hash(pathname) compfile.write("%s, " % name + "%s\n" % sha3sum) compfile.close() messagebox.showwarning(message="Transfer Manifest Created.") return def pre_pack(self, packdir): """ Preserves departmental folder structure during Bagging by moving object contents into a subdirectory named with the local object ID """ for item in listdir(packdir): olditempath = path.join(packdir, item) if path.isdir(olditempath): newdirpath = path.join(olditempath, path.basename(olditempath)) temppath = path.join(olditempath, 'temptemptemp') shutil.copytree(olditempath, temppath) for thing in listdir(olditempath): thingpath = path.join(olditempath, thing) if not thing == 'temptemptemp': if path.isdir(thingpath): shutil.rmtree(thingpath) elif not 'meta' in thing: remove(thingpath) rename(temppath, newdirpath) return packdir def run_procs(self, root, frame2): runnext = True olditemsdir = self.e1.get() meta = frame2.metavar.get() regstr = frame2.regisvar.get() inv = frame2.invenvar.get() bagit = frame2.bagitvar.get() tar = frame2.tarvar.get() trans = frame2.transvar.get() self.prompting = frame2.prompt.get() nselect = 0 for d in [meta, regstr, inv, bagit, tar, trans]: if d == 1: nselect += 1 if olditemsdir == "": messagebox.showwarning(message="You must first select a folder.") return if not path.exists(olditemsdir): messagebox.showwarning( message="Items folder:\n\'%s\'\nnot found." % olditemsdir) return if nselect == 0: messagebox.showwarning( message="You have not selected any \'Options\'.") return # PrePack items prepack = messagebox.askyesno( title="Pre-Packaging", message= "Is this the first time running UDOF on THESE items?\n(Clicking \'yes\' will \'pre-package\' them.)", default='no') if prepack == False: itemsdir = olditemsdir else: itemsdir = self.pre_pack(olditemsdir) # Run CSV meta if meta == 1: nselect -= 1 metainput = self.e2.get() idcolumn = self.e3.get() if metainput == "": messagebox.showwarning( message="You must choose a CSV master metadata file.") return if not path.exists(metainput): messagebox.showwarning( message="CSV file:\n\'%s\'\nnot found. Stopping action." % metainput) return if path.splitext(metainput)[1] == '.csv' and idcolumn == "": messagebox.showwarning( message="You must choose the column of ID's in the CSV.") return runnext = self.create_meta(root, itemsdir, metainput, idcolumn, nselect) if runnext == False: return # Assign UUID's and Register Objects if regstr == 1: nselect -= 1 runnext = self.register_obj(itemsdir, nselect) if runnext == False: return # Run Inventory if inv == 1: nselect -= 1 runnext = self.run_inventory(itemsdir, nselect) if runnext == False: return # Run BagIt if bagit == 1: nselect -= 1 self.run_bagit(itemsdir, nselect) if runnext == False: return # Run Tar if tar == 1: nselect -= 1 runnext = self.run_tar(itemsdir, nselect) if runnext == False: return # Make Transfer Manifest if trans == 1: self.trans_manifest(itemsdir) return
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller KOPTIONS = ["1024 bits", "2048 bits", "4096 bits"] self.columnconfigure(0) self.columnconfigure(1, weight=1) self.rowconfigure(0, pad=5) self.rowconfigure(1, pad=5) self.rowconfigure(2, weight=1, pad=5) self.rowconfigure(3, pad=5) self.rowconfigure(4, pad=5) self.rowconfigure(5, pad=5) self.rowconfigure(6, pad=5) self.rowconfigure(7, pad=5) # Title bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage")) bbutton.grid(row=0, column=0, padx=10, sticky=W) title = Label(self, text="RSA Key Generator") title.grid(row=0, columnspan=2, padx=10) # Key length kframe = Frame(self) klength_label = Label(kframe, text="Key Length") klength_label.pack(side=LEFT) kselect = StringVar(self) kselect.set(KOPTIONS[0]) # default value koption = OptionMenu(kframe, kselect, *KOPTIONS) koption.pack(side=LEFT, padx=10) koption.configure(width=40) gbutton = Button(kframe, text="Generate", width=15) gbutton.pack(side=LEFT, padx=10) gbutton.configure(command=lambda: self.generate(kselect.get())) kframe.grid(row=1, columnspan=2, padx=10, pady=5, sticky=E + W + N) # Result key frame keyframe = Frame(self) keyframe.columnconfigure(0, weight=1, pad=5) keyframe.columnconfigure(1, pad=5) keyframe.columnconfigure(2, weight=1, pad=5) keyframe.rowconfigure(0, pad=5) keyframe.rowconfigure(1, weight=1, pad=5) # Box labels pub_label = Label(keyframe, text="Public Key") pub_label.grid(row=0, column=0, padx=10, sticky=W) priv_label = Label(keyframe, text="Private Key") priv_label.grid(row=0, column=2, sticky=W) # Public key box self.pub_output = Text(keyframe, wrap=WORD) self.pub_output.grid(row=1, column=0, padx=10, pady=10, sticky=N + E + S + W) self.pub_output.bind("<1>", lambda event: self.pub_output.focus_set()) scrolli = Scrollbar(keyframe, command=self.pub_output.yview) self.pub_output.configure(yscrollcommand=scrolli.set) scrolli.grid(row=1, column=0, pady=10, sticky=N + S + E) self.pub_output.configure(state="disabled") self.pub_output.bind("<Control-Key-a>", select_all) # select-all Windows/Linux self.pub_output.bind("<Command-Key-a>", select_all) # select-all Mac # Private key box self.priv_output = Text(keyframe, wrap=WORD) self.priv_output.grid(row=1, column=2, padx=10, pady=10, sticky=N + E + S + W) self.priv_output.bind("<1>", lambda event: self.priv_output.focus_set()) scrolli = Scrollbar(keyframe, command=self.priv_output.yview) self.priv_output.configure(yscrollcommand=scrolli.set) scrolli.grid(row=1, column=2, pady=10, sticky=N + S + E) self.priv_output.configure(state="disabled") self.priv_output.bind("<Control-Key-a>", select_all) # select-all Windows/Linux self.priv_output.bind("<Command-Key-a>", select_all) # select-all Mac keyframe.grid(row=2, columnspan=2, pady=5, sticky=E + W + N + S) plabel = Label(self, text="p") plabel.grid(row=3, column=0, padx=3, pady=3) self.p = Entry(self) self.p.grid(row=3, column=1, padx=10, pady=3, sticky=E + W) self.p.bind("<Control-Key-a>", select_all_entry) # select-all Windows/Linux self.p.bind("<Command-Key-a>", select_all_entry) # select-all Mac # q qlabel = Label(self, text="q") qlabel.grid(row=4, column=0, padx=3, pady=3) self.q = Entry(self) self.q.grid(row=4, column=1, padx=10, pady=3, sticky=E + W) self.q.bind("<Control-Key-a>", select_all_entry) # select-all Windows/Linux self.q.bind("<Command-Key-a>", select_all_entry) # select-all Mac # N Nlabel = Label(self, text="N") Nlabel.grid(row=5, column=0, padx=3, pady=3) self.N = Entry(self) self.N.grid(row=5, column=1, padx=10, pady=3, sticky=E + W) self.N.bind("<Control-Key-a>", select_all_entry) # select-all Windows/Linux self.N.bind("<Command-Key-a>", select_all_entry) # select-all Mac # e elabel = Label(self, text="e") elabel.grid(row=6, column=0, padx=3, pady=3) self.e = Entry(self) self.e.grid(row=6, column=1, padx=10, pady=3, sticky=E + W) self.e.bind("<Control-Key-a>", select_all_entry) # select-all Windows/Linux self.e.bind("<Command-Key-a>", select_all_entry) # select-all Mac # d dlabel = Label(self, text="d") dlabel.grid(row=7, column=0, padx=3, pady=3) self.d = Entry(self) self.d.grid(row=7, column=1, padx=10, pady=3, sticky=E + W) self.d.bind("<Control-Key-a>", select_all_entry) # select-all Windows/Linux self.d.bind("<Command-Key-a>", select_all_entry) # select-all Mac
class MainView(Tk): class Constants: title = "Cambio de Moneda" heigth = 100 width = 550 input_width = 250 separator_width = 50 center = N + S + E + W left = W right = E event = "<Button-1>" convert_text = "Convertir" separator_text = "▶" convertion_base = "USD" convertion_final = "To" convertion_initial = "From" bleeding = 10 def __init__(self, convert_handler=None): super().__init__() self.__convert_handler = convert_handler self.title(self.Constants.title) self.maxsize(width=self.Constants.width, height=self.Constants.heigth) self.minsize(width=self.Constants.width, height=self.Constants.heigth) self.__configure_grid() self.__configure_UI() def __configure_grid(self): self.grid_rowconfigure(0, weight=True) self.grid_rowconfigure(1, weight=True) self.grid_rowconfigure(2, weight=True) self.grid_columnconfigure(0, minsize=self.Constants.input_width) self.grid_columnconfigure(2, minsize=self.Constants.input_width) self.grid_columnconfigure(1, minsize=self.Constants.separator_width) def __configure_UI(self): self.option_final = StringVar(self) self.option_final.set(self.Constants.convertion_final) self.list_of_convertions = self.convert_data_to_list() self.menu = OptionMenu(self, self.option_final, *self.list_of_convertions) self.menu.grid(row=2, column=2, sticky=self.Constants.right) self.menu.configure(bg="light sea green", fg="black", width=30, font=("Arial black", 8)) self.option_initial = StringVar(self) self.option_initial.set(self.Constants.convertion_initial) self.list_of_inital_conversion = self.convert_initial_data_list() self.initial_menu = OptionMenu(self, self.option_initial, *self.list_of_inital_conversion) self.initial_menu.grid(row=2, column=0, sticky=self.Constants.left) self.initial_menu.configure(bg="light sea green", fg="black", width=30, font=("Arial black", 8)) currency_name_label = Label(self) currency_name_label.configure(textvariable=self.option_initial) currency_name_label.grid(row=0, column=0, sticky=self.Constants.left) result_name_label = Label(self) result_name_label.configure(textvariable=self.option_final) result_name_label.grid(row=0, column=2, sticky=self.Constants.left) separator_label = Label(self) separator_label.configure(text=self.Constants.separator_text) separator_label.grid(row=1, column=1, sticky=self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text="0") self.__result_label.grid(row=1, column=2, sticky=self.Constants.left) self.__convert_button = Button(self) self.__convert_button.configure(text=self.Constants.convert_text) self.__convert_button.configure(bg="lawn green", fg="black", font=("Arial black", self.Constants.bleeding)) self.__convert_button.grid(row=2, column=1, sticky=self.Constants.center, padx=self.Constants.bleeding, pady=self.Constants.bleeding) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate="key", validatecommand=vcmd) self.__currency_input.grid(row=1, column=0, sticky=self.Constants.center) def __did_tap_convert(self, event): if self.__convert_handler is None: return try: ammount_to_convert = float(self.__currency_input.get()) except ValueError: return else: self.__convert_handler(self.finding_initial_equivalence(), self.finding_equivalence_of_name(), ammount_to_convert) def update_result(self, text): self.__result_label.configure(text=text) def __checkNumberOnly(self, action, value_if_allowed): if action != '1': return True try: float(value_if_allowed) except ValueError: return False else: return True def convert_data_to_list(self): self.messy_list = CurrencyManager.get_crude_dates(self) return self.messy_list def finding_equivalence_of_name(self): self.sign_convertion = self.option_final.get() self.equivalence = CurrencyManager.finding_equivalence( self, self.sign_convertion) return self.equivalence def convert_initial_data_list(self): self.initial_options_list = CurrencyManager.get_initial_currency(self) return self.initial_options_list def finding_initial_equivalence(self): self.initial_sign_convertion = self.option_initial.get() self.initial_equivalence = CurrencyManager.finding_initial_equivalence( self, self.initial_sign_convertion) return self.initial_equivalence
class MyApp(Frame): def __init__(self): self.root = Tk() Frame.__init__(self, self.root) # high level GUI configuration self.root.geometry('800x600') self.root.resizable(width=1, height=1) self.root.option_add('*tearOff', False) # keeps file menus from looking weird # members related to the background thread and operator instance self.long_thread = None self.background_operator = None # tk variables we can access later self.label_string = StringVar() self.build_dir_1_var = StringVar() self.build_dir_2_var = StringVar() self.run_period_option = StringVar() self.run_period_option.set(RunOptions.DONT_FORCE) self.reporting_frequency = StringVar() self.reporting_frequency.set(ReportingFrequency.HOURLY) # widgets that we might want to access later self.build_dir_1_button = None self.build_dir_2_button = None self.run_button = None self.stop_button = None self.build_dir_1_label = None self.build_dir_1_var.set('/eplus/repos/1eplus/builds') # "<Select build dir 1>") self.build_dir_2_label = None self.build_dir_2_var.set('/eplus/repos/1eplus/builds') # "<Select build dir 2>") self.progress = None self.log_message_listbox = None self.results_tree = None self.num_threads_spinner = None self.full_idf_listbox = None self.move_idf_to_active_button = None self.active_idf_listbox = None self.remove_idf_from_active_button = None self.idf_select_all_button = None self.idf_deselect_all_button = None self.idf_select_n_random_button = None self.run_period_option_menu = None self.reporting_frequency_option_menu = None # some data holders self.tree_folders = dict() self.valid_idfs_in_listing = False self.run_button_color = '#008000' # initialize the GUI self.init_window() # wire up the background thread pub.subscribe(self.status_handler, PubSubMessageTypes.STATUS) pub.subscribe(self.finished_handler, PubSubMessageTypes.FINISHED) pub.subscribe(self.cancelled_handler, PubSubMessageTypes.CANCELLED) def init_window(self): # changing the title of our master widget self.root.title("EnergyPlus Regression Tool 2") self.root.protocol("WM_DELETE_WINDOW", self.client_exit) # create the menu menu = Menu(self.root) self.root.config(menu=menu) file_menu = Menu(menu) file_menu.add_command(label="Exit", command=self.client_exit) menu.add_cascade(label="File", menu=file_menu) # main notebook holding everything main_notebook = ttk.Notebook(self.root) # run configuration pane_run = Frame(main_notebook) group_build_dir_1 = LabelFrame(pane_run, text="Build Directory 1") group_build_dir_1.pack(fill=X, padx=5) self.build_dir_1_button = Button(group_build_dir_1, text="Change...", command=self.client_build_dir_1) self.build_dir_1_button.grid(row=1, column=1, sticky=W) self.build_dir_1_label = Label(group_build_dir_1, textvariable=self.build_dir_1_var) self.build_dir_1_label.grid(row=1, column=2, sticky=E) group_build_dir_2 = LabelFrame(pane_run, text="Build Directory 2") group_build_dir_2.pack(fill=X, padx=5) self.build_dir_2_button = Button(group_build_dir_2, text="Change...", command=self.client_build_dir_2) self.build_dir_2_button.grid(row=1, column=1, sticky=W) self.build_dir_2_label = Label(group_build_dir_2, textvariable=self.build_dir_2_var) self.build_dir_2_label.grid(row=1, column=2, sticky=E) group_run_options = LabelFrame(pane_run, text="Run Options") group_run_options.pack(fill=X, padx=5) Label(group_run_options, text="Number of threads for suite: ").grid(row=1, column=1, sticky=E) self.num_threads_spinner = Spinbox(group_run_options, from_=1, to_=48) # validate later self.num_threads_spinner.grid(row=1, column=2, sticky=W) Label(group_run_options, text="Test suite run configuration: ").grid(row=2, column=1, sticky=E) self.run_period_option_menu = OptionMenu(group_run_options, self.run_period_option, *RunOptions.get_all()) self.run_period_option_menu.grid(row=2, column=2, sticky=W) Label(group_run_options, text="Minimum reporting frequency: ").grid(row=3, column=1, sticky=E) self.reporting_frequency_option_menu = OptionMenu( group_run_options, self.reporting_frequency, *ReportingFrequency.get_all() ) self.reporting_frequency_option_menu.grid(row=3, column=2, sticky=W) main_notebook.add(pane_run, text='Configuration') # now let's set up a list of checkboxes for selecting IDFs to run pane_idfs = Frame(main_notebook) group_idf_tools = LabelFrame(pane_idfs, text="IDF Selection Tools") group_idf_tools.pack(fill=X, padx=5) self.idf_select_all_button = Button( group_idf_tools, text="Refresh", command=self.client_idf_refresh ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_select_all_button = Button( group_idf_tools, text="Select All", command=self.idf_select_all ) self.idf_select_all_button.pack(side=LEFT, expand=1) self.idf_deselect_all_button = Button( group_idf_tools, text="Deselect All", command=self.idf_deselect_all ) self.idf_deselect_all_button.pack(side=LEFT, expand=1) self.idf_select_n_random_button = Button( group_idf_tools, text="Select N Random", command=self.idf_select_random ) self.idf_select_n_random_button.pack(side=LEFT, expand=1) group_full_idf_list = LabelFrame(pane_idfs, text="Full IDF List") group_full_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_full_idf_list) self.full_idf_listbox = Listbox(group_full_idf_list, yscrollcommand=scrollbar.set) self.full_idf_listbox.bind('<Double-1>', self.idf_move_to_active) self.full_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.full_idf_listbox.yview) self.move_idf_to_active_button = Button( pane_idfs, text="↓ Add to Active List ↓", command=self.idf_move_to_active ) self.move_idf_to_active_button.pack(side=TOP, fill=X, expand=True) self.remove_idf_from_active_button = Button( pane_idfs, text="↑ Remove from Active List ↑", command=self.idf_remove_from_active ) self.remove_idf_from_active_button.pack(side=TOP, fill=X, expand=True) group_active_idf_list = LabelFrame(pane_idfs, text="Active IDF List") group_active_idf_list.pack(fill=X, padx=5) scrollbar = Scrollbar(group_active_idf_list) self.active_idf_listbox = Listbox(group_active_idf_list, yscrollcommand=scrollbar.set) self.active_idf_listbox.bind('<Double-1>', self.idf_remove_from_active) self.active_idf_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.active_idf_listbox.yview) self.build_idf_listing(initialize=True) main_notebook.add(pane_idfs, text="IDF Selection") # set up a scrolled listbox for the log messages frame_log_messages = Frame(main_notebook) group_log_messages = LabelFrame(frame_log_messages, text="Log Message Tools") group_log_messages.pack(fill=X, padx=5) Button(group_log_messages, text="Clear Log Messages", command=self.clear_log).pack(side=LEFT, expand=1) Button(group_log_messages, text="Copy Log Messages", command=self.copy_log).pack(side=LEFT, expand=1) scrollbar = Scrollbar(frame_log_messages) self.log_message_listbox = Listbox(frame_log_messages, yscrollcommand=scrollbar.set) self.add_to_log("Program started!") self.log_message_listbox.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.log_message_listbox.yview) main_notebook.add(frame_log_messages, text="Log Messages") # set up a tree-view for the results frame_results = Frame(main_notebook) scrollbar = Scrollbar(frame_results) self.results_tree = ttk.Treeview(frame_results, columns=("Base File", "Mod File", "Diff File")) self.results_tree.heading("#0", text="Results") self.results_tree.column('#0', minwidth=200, width=200) self.results_tree.heading("Base File", text="Base File") self.results_tree.column("Base File", minwidth=100, width=100) self.results_tree.heading("Mod File", text="Mod File") self.results_tree.column("Mod File", minwidth=100, width=100) self.results_tree.heading("Diff File", text="Diff File") self.results_tree.column("Diff File", minwidth=100, width=100) self.build_results_tree() self.results_tree.pack(fill=BOTH, side=LEFT, expand=True) scrollbar.pack(fill=Y, side=LEFT) scrollbar.config(command=self.results_tree.yview) main_notebook.add(frame_results, text="Run Control and Results") # pack the main notebook on the window main_notebook.pack(fill=BOTH, expand=1) # status bar at the bottom frame_status = Frame(self.root) self.run_button = Button(frame_status, text="Run", bg=self.run_button_color, command=self.client_run) self.run_button.pack(side=LEFT, expand=0) self.stop_button = Button(frame_status, text="Stop", command=self.client_stop, state='disabled') self.stop_button.pack(side=LEFT, expand=0) self.progress = ttk.Progressbar(frame_status) self.progress.pack(side=LEFT, expand=0) label = Label(frame_status, textvariable=self.label_string) self.label_string.set("Initialized") label.pack(side=LEFT, anchor=W) frame_status.pack(fill=X) def run(self): self.root.mainloop() def build_idf_listing(self, initialize=False, desired_selected_idfs=None): # clear any existing ones self.active_idf_listbox.delete(0, END) self.full_idf_listbox.delete(0, END) # now rebuild them self.valid_idfs_in_listing = False path_1 = Path(self.build_dir_1_var.get()) path_2 = Path(self.build_dir_2_var.get()) if path_1.exists() and path_2.exists(): idf_dir_1 = dummy_get_idf_dir(path_1) idfs_dir_1 = dummy_get_idfs_in_dir(idf_dir_1) idf_dir_2 = dummy_get_idf_dir(path_2) idfs_dir_2 = dummy_get_idfs_in_dir(idf_dir_2) common_idfs = idfs_dir_1.intersection(idfs_dir_2) for idf in sorted(common_idfs): self.full_idf_listbox.insert(END, str(idf)) self.valid_idfs_in_listing = True elif initialize: self.full_idf_listbox.insert(END, "This will be the master list") self.full_idf_listbox.insert(END, "Select build folders to fill listing") elif path_1.exists(): self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Build folder path #2 is invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") elif path_2.exists(): self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Build folder path #1 is invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") else: self.full_idf_listbox.insert(END, "Cannot update master list master list") self.full_idf_listbox.insert(END, "Both build folders are invalid") self.full_idf_listbox.insert(END, "Select build folders to fill listing") if desired_selected_idfs is None: ... # add things to the listbox def build_results_tree(self, results=None): self.results_tree.delete(*self.results_tree.get_children()) for root in ResultsTreeRoots.get_all(): self.tree_folders[root] = self.results_tree.insert( parent="", index='end', text=root, values=("", "", "") ) if results: self.results_tree.insert( parent=self.tree_folders[root], index="end", text="Pretend", values=("These", "Are", "Real") ) else: self.results_tree.insert( parent=self.tree_folders[root], index="end", text="Run test for results", values=("", "", "") ) def add_to_log(self, message): self.log_message_listbox.insert(END, f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]: {message}") def clear_log(self): self.log_message_listbox.delete(0, END) def copy_log(self): messages = self.log_message_listbox.get(0, END) message_string = '\n'.join(messages) self.root.clipboard_append(message_string) def client_idf_refresh(self): self.build_idf_listing() def idf_move_to_active(self, _): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return current_selection = self.full_idf_listbox.curselection() if not current_selection: simpledialog.messagebox.showerror("IDF Selection Error", "No IDF Selected") return currently_selected_idf = self.full_idf_listbox.get(current_selection) try: self.active_idf_listbox.get(0, "end").index(currently_selected_idf) simpledialog.messagebox.showwarning("IDF Selection Warning", "IDF already exists in active list") return except ValueError: pass # the value error indicates it was _not_ found, so this is success self.active_idf_listbox.insert(END, currently_selected_idf) self.idf_refresh_count_status(currently_selected_idf, True) def idf_remove_from_active(self, event=None): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return current_selection = self.active_idf_listbox.curselection() if not current_selection: if event: return simpledialog.messagebox.showerror("IDF Selection Error", "No IDF Selected") return self.active_idf_listbox.delete(current_selection) self.idf_refresh_count_status(current_selection, False) def idf_select_all(self): self.idf_deselect_all() if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return all_idfs = self.full_idf_listbox.get(0, END) for idf in all_idfs: self.active_idf_listbox.insert(END, idf) self.idf_refresh_count_status() def idf_deselect_all(self): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return self.active_idf_listbox.delete(0, END) self.idf_refresh_count_status() def idf_select_random(self): if not self.valid_idfs_in_listing: simpledialog.messagebox.showerror("IDF Selection Error", "Invalid build folders or IDF list") return potential_number_to_select = simpledialog.askinteger("Input Amount", "How many would you like to select?") if not potential_number_to_select: return self.idf_deselect_all() number_to_select = int(potential_number_to_select) number_of_idf_files = self.full_idf_listbox.size() if number_of_idf_files <= number_to_select: # just take all of them self.idf_select_all() else: # down select randomly indices_to_take = random.sample(range(number_of_idf_files), number_to_select) idfs_to_take = list() for i in indices_to_take: idf_to_get = self.full_idf_listbox.get(i) idfs_to_take.append(idf_to_get) for idf_to_get in sorted(idfs_to_take): self.active_idf_listbox.insert(END, idf_to_get) self.idf_refresh_count_status() def idf_refresh_count_status(self, test_case=None, checked=False): if not self.valid_idfs_in_listing: return num_total = self.full_idf_listbox.size() num_active = self.active_idf_listbox.size() if test_case: chk_string = "Checked" if checked else "Unchecked" if checked: self.label_string.set(f"{chk_string} {test_case} ({num_active}/{num_total} selected)") else: self.label_string.set(f"{num_active}/{num_total} selected") def set_gui_status_for_run(self, is_running: bool): if is_running: run_button_state = 'disabled' stop_button_state = 'normal' else: run_button_state = 'normal' stop_button_state = 'disabled' self.build_dir_1_button.configure(state=run_button_state) self.build_dir_2_button.configure(state=run_button_state) self.run_button.configure(state=run_button_state) self.idf_select_all_button.configure(state=run_button_state) self.idf_deselect_all_button.configure(state=run_button_state) self.idf_select_n_random_button.configure(state=run_button_state) self.move_idf_to_active_button.configure(state=run_button_state) self.remove_idf_from_active_button.configure(state=run_button_state) self.run_period_option_menu.configure(state=run_button_state) self.reporting_frequency_option_menu.configure(state=run_button_state) self.num_threads_spinner.configure(state=run_button_state) self.stop_button.configure(state=stop_button_state) def client_build_dir_1(self): selected_dir = filedialog.askdirectory() if selected_dir: self.build_dir_1_var.set(selected_dir) self.build_idf_listing() def client_build_dir_2(self): selected_dir = filedialog.askdirectory() if selected_dir: self.build_dir_2_var.set(selected_dir) self.build_idf_listing() def client_run(self): if self.long_thread: messagebox.showerror("Cannot run another thread, wait for the current to finish -- how'd you get here?!?") return potential_num_threads = self.num_threads_spinner.get() try: num_threads = int(potential_num_threads) except ValueError: messagebox.showerror("Invalid Configuration", "Number of threads must be an integer") return idfs_to_run = list() for i in self.active_idf_listbox.get(0, END): idfs_to_run.append(i) self.background_operator = BackgroundOperation(num_threads, idfs_to_run) self.background_operator.get_ready_to_go( MyApp.status_listener, MyApp.finished_listener, MyApp.cancelled_listener ) self.set_gui_status_for_run(True) self.long_thread = Thread(target=self.background_operator.run) self.add_to_log("Starting a new set of tests") self.long_thread.start() def client_stop(self): self.add_to_log("Attempting to cancel") self.label_string.set("Attempting to cancel...") self.background_operator.please_stop() def client_exit(self): if self.long_thread: messagebox.showerror("Uh oh!", "Cannot exit program while operations are running; abort them then exit") return exit() def client_done(self): self.set_gui_status_for_run(False) self.long_thread = None # -- Callbacks from the background thread coming via PyPubSub @staticmethod def status_listener(status, object_completed, percent_complete): """Operates on background thread, just issues a pubsub message""" pub.sendMessage( PubSubMessageTypes.STATUS, status=status, object_completed=object_completed, percent_complete=percent_complete) def status_handler(self, status, object_completed, percent_complete): self.add_to_log(object_completed) self.progress['value'] = percent_complete self.label_string.set(f"Hey, status update: {str(status)}") @staticmethod def finished_listener(results_dict): """Operates on background thread, just issues a pubsub message""" pub.sendMessage(PubSubMessageTypes.FINISHED, results=results_dict) def finished_handler(self, results): self.add_to_log("All done, finished") self.label_string.set("Hey, all done!") self.build_results_tree(results) self.client_done() @staticmethod def cancelled_listener(): """Operates on background thread, just issues a pubsub message""" pub.sendMessage(PubSubMessageTypes.CANCELLED) def cancelled_handler(self): self.add_to_log("Cancelled!") self.label_string.set("Properly cancelled!") self.client_done()
size_out_label = Label(out_img_frame, text='Specify size') size_out_label.grid(row=1, column=0, sticky='W', padx=20) format_out_label = Label(out_img_frame, text='Specify format') format_out_label.grid(row=2, column=0, sticky='W', padx=20, pady=5) size_h_txt = Entry(out_img_frame, state=DISABLED, width=5) size_h_txt.grid(row=1, column=1, sticky='W', pady=10) size_w_txt = Entry(out_img_frame, state=DISABLED, width=5) size_w_txt.grid(row=1, column=1, sticky='E', pady=10) click = StringVar() format_out_txt = OptionMenu(out_img_frame, click, 'JPG', 'PNG', 'BMP') format_out_txt.configure(width=6, state=DISABLED) format_out_txt.grid(row=2, column=1, sticky='W') btn_in_frame = Frame(root) btn_in_frame.grid(row=5, column=0, pady=20) open_btn = Button(btn_in_frame, text='Open', command=open_file) open_btn.grid(row=0, column=0) reset_btn = Button(btn_in_frame, text='Reset', state=DISABLED, command=reset) reset_btn.grid(row=0, column=1) btn_out_frame = Frame(root) btn_out_frame.grid(row=5, column=1, pady=20) convert_btn = Button(btn_out_frame,
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.columnconfigure(0, weight=1, pad=5) self.rowconfigure(0, pad=5) self.rowconfigure(1, pad=5) self.rowconfigure(2, pad=5) self.rowconfigure(3, pad=5) self.rowconfigure(4, pad=5) self.rowconfigure(5, pad=5) self.rowconfigure(6, weight=1, pad=5) # Title bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage")) bbutton.grid(row=0, padx=10, sticky=W) title = Label(self, text="Number Arithmetic") title.grid(row=0) # Type options TOPTIONS = [ "Unsigned Binary", "Sign and Magnitude", "One's Complement", "Two's Complement", "Hexadecimal" ] self.tselect = StringVar(self) toption = OptionMenu(self, self.tselect, *TOPTIONS) toption.grid(row=1, padx=8, sticky=W + E) # Operand 1 op1 = Entry(self) op1.grid(row=2, padx=10, pady=10, sticky=E + W) op1.insert(0, "Operand 1") # Operator option OOPTIONS = ["+", "-", "*", "/ (will round)"] operator = StringVar(self) operator.set(OOPTIONS[0]) # default value ooption = OptionMenu(self, operator, *OOPTIONS) ooption.grid(row=3, padx=8, sticky=W) ooption.configure(width=8) # Operand 2 op2 = Entry(self) op2.grid(row=4, padx=10, pady=10, sticky=E + W) op2.insert(0, "Operand 2") # Evaluate button ebutton = Button(self, text="=", width=10) ebutton.grid(row=5) ebutton.configure(command=lambda: self.calc_prep( op1.get(), op2.get(), operator.get(), self.tselect.get())) # Output box self.output = Text(self, wrap=WORD) self.output.grid(row=6, padx=11, pady=10, sticky=N + E + S + W) self.output.bind("<1>", lambda event: self.output.focus_set()) scrollo = Scrollbar(self, command=self.output.yview) scrollo.grid(row=6, pady=10, sticky=N + S + E) self.output.configure(yscrollcommand=scrollo.set) self.output.insert(1.0, "Output") self.output.configure(state="disabled") self.output.bind("<Control-Key-a>", select_all) # select-all Windows/Linux self.output.bind("<Command-Key-a>", select_all) # select-all Mac
def show(self, tab): self.tab = tab self.tab.freeze( ) # You have to finish dealing with this before, say, opening another analysis box. buttons = { "reset": { self.select_tab: [], self.tab.reset: [], self.uncheck_exclude_artifacts: [], self.disable_plot: [], # utils.thread_lift_widget: [], }, "close": {}, } self.analysis_dialog = VerticalScrolledDialog(self.controller, "Analyze Data", "", buttons=buttons, button_width=13) self.analysis_dialog.top.attributes("-topmost", True) outer_normalize_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_normalize_frame.pack(expand=True, fill=BOTH) slope_title_label = Label(outer_normalize_frame, text="Normalize:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack() normalize_frame = Frame(outer_normalize_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) normalize_frame.pack() normalize_label = Label(normalize_frame, text="Wavelength (nm):", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.normalize_entry = Entry( normalize_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) normalize_button = Button( normalize_frame, text="Apply", command=self.normalize, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) normalize_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) normalize_button.pack(side=RIGHT, padx=(10, 10)) self.normalize_entry.pack(side=RIGHT, padx=self.tk_format.padx) normalize_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_offset_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_offset_frame.pack(expand=True, fill=BOTH) slope_title_label = Label(outer_offset_frame, text="Add offset to sample:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack(pady=(0, 15)) offset_sample_frame = Frame(outer_offset_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=self.tk_format.pady) offset_sample_frame.pack() offset_sample_label = Label(offset_sample_frame, text="Sample: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) offset_sample_label.pack(side=LEFT) self.offset_sample_var = StringVar() sample_names = [] repeats = False max_len = 0 for sample in self.tab.samples: if sample.name in sample_names: repeats = True else: sample_names.append(sample.name) max_len = np.max([max_len, len(sample.name)]) if repeats: sample_names = [] for sample in self.tab.samples: sample_names.append(sample.title + ": " + sample.name) max_len = np.max([max_len, len(sample_names[-1])]) self.offset_sample_var.set(sample_names[0]) # pylint: disable = no-value-for-parameter offset_menu = OptionMenu(offset_sample_frame, self.offset_sample_var, *sample_names) offset_menu.configure( width=max_len, highlightbackground=self.tk_format.highlightbackgroundcolor) offset_menu.pack(side=LEFT) offset_frame = Frame(outer_offset_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) offset_frame.pack() offset_label = Label(offset_frame, text="Offset:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.offset_entry = Entry( offset_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) offset_button = Button( offset_frame, text="Apply", command=self.offset, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) offset_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) offset_button.pack(side=RIGHT, padx=(10, 10)) self.offset_entry.pack(side=RIGHT, padx=self.tk_format.padx) offset_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_outer_zoom_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_outer_zoom_frame.pack(expand=True, fill=BOTH) zoom_title_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg) zoom_title_frame.pack(pady=(5, 10)) zoom_title_label = Label(zoom_title_frame, text="Adjust plot x and y limits:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) zoom_title_label.pack(side=LEFT, pady=(0, 4)) outer_zoom_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame = Frame(outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame.pack() zoom_label = Label(zoom_frame, text="x1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label2 = Label(zoom_frame, text="x2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button = Button( zoom_frame, text="Apply", command=self.apply_x, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_zoom_frame2 = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame2.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame2 = Frame(outer_zoom_frame2, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame2.pack() zoom_label3 = Label(zoom_frame2, text="y1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry2 = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label4 = Label(zoom_frame2, text="y2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry2 = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button2 = Button( zoom_frame2, text="Apply", command=self.apply_y, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button2.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button2.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label4.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label3.pack(side=RIGHT, padx=self.tk_format.padx) outer_outer_slope_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_outer_slope_frame.pack(expand=True, fill=BOTH) self.outer_slope_frame = Frame(outer_outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) self.outer_slope_frame.pack(expand=True, fill=BOTH, pady=(0, 10)) slope_title_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg) slope_title_frame.pack(pady=(5, 5)) slope_title_label = Label(slope_title_frame, text="Analyze ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack(side=LEFT, pady=(0, 4)) self.analyze_var = StringVar() self.analyze_var.set("slope") analyze_menu = OptionMenu( slope_title_frame, self.analyze_var, "slope", "band depth", "band center", "reflectance", # "reciprocity", "difference", command=self.disable_plot, ) analyze_menu.configure( width=10, highlightbackground=self.tk_format.highlightbackgroundcolor) analyze_menu.pack(side=LEFT) # We'll put checkboxes for additional options into this frame at the time the user selects a given option (e.g. # select 'difference' from menu, add option to calculate differences based on absolute value self.extra_analysis_check_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) self.extra_analysis_check_frame.pack() # Note that we are not packing this checkbutton yet. self.abs_val_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text=" Use absolute values for average differences", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.abs_val, ) self.use_max_for_centers_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " If band max is more prominent than\nband min, use to find center.", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.use_max_for_centers, ) self.use_max_for_centers_check.select() self.use_delta_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text=" Center at max \u0394" + "R from continuum \nrather than spectral min/max. ", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.use_delta, ) self.use_delta_check.select() self.neg_depth_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " If band max is more prominent than \nband min, report negative depth.", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.neg_depth, ) self.neg_depth_check.select() slope_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, highlightthickness=0) slope_frame.pack(pady=(15, 0)) slope_label = Label(slope_frame, text="x1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_slope_entry = Entry( slope_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) slope_label_2 = Label(slope_frame, text="x2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_slope_entry = Entry( slope_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) slope_button = Button( slope_frame, text="Calculate", command=self.calculate, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) slope_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) slope_button.pack(side=RIGHT, padx=(10, 10)) self.right_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx) slope_label_2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx) slope_label.pack(side=RIGHT, padx=self.tk_format.padx) self.slope_results_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg) self.slope_results_frame.pack( fill=BOTH, expand=True ) # We'll put a listbox with slope info in here later after calculating. outer_plot_slope_frame = Frame(outer_outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=10) outer_plot_slope_frame.pack(expand=True, fill=BOTH) plot_slope_frame = Frame(outer_plot_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) plot_slope_frame.pack(side=RIGHT) plot_slope_label = Label(plot_slope_frame, text="Plot as a function of", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.plot_slope_var = StringVar() self.plot_slope_var.set("e") self.plot_slope_menu = OptionMenu(plot_slope_frame, self.plot_slope_var, "e", "i", "g", "e,i", "theta", "az, e") self.plot_slope_menu.configure( width=2, highlightbackground=self.tk_format.highlightbackgroundcolor) self.plot_slope_button = Button( plot_slope_frame, text="Plot", command=self.plot, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) self.plot_slope_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, state=DISABLED, ) self.plot_slope_button.pack(side=RIGHT, padx=(10, 10)) self.plot_slope_menu.pack(side=RIGHT, padx=self.tk_format.padx) plot_slope_label.pack(side=RIGHT, padx=self.tk_format.padx) exclude_artifacts_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) exclude_artifacts_frame.pack(fill=BOTH, expand=True) self.exclude_artifacts_check = Checkbutton( exclude_artifacts_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " Exclude data susceptible to artifacts\n (high g, 1000-1400 nm) ", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.exclude_artifacts, # TODO: check if the comma is meant to be there in the lambda definition command=lambda x="foo", : self.tab.set_exclude_artifacts( self.exclude_artifacts.get()), ) self.exclude_artifacts_check.pack() if self.tab.exclude_artifacts: self.exclude_artifacts_check.select() self.analysis_dialog.interior.configure(highlightthickness=1, highlightcolor="white")
class MainView(Tk): class Constants: title = "Cambio de Moneda" heigth = 100 width = 550 input_width = 250 separator_width = 50 center = N + S + E + W left = W event = "<Button-1>" convert_text = "Convertir" separator_text = "▶" currency_options = [ "AUD", "BGN", "BRL", "CAD", "CHF", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HRK", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PLN", "RON", "RUB", "SEK", "SGD", "THB", "TRY", "USD", "ZAR" ] currency_1 = True currency_2 = True def __init__(self, convert_handler=None): super().__init__() self.__convert_handler = convert_handler self.title(self.Constants.title) self.maxsize(width=self.Constants.width, height=self.Constants.heigth) self.minsize(width=self.Constants.width, height=self.Constants.heigth) self.__configure_grid() self.__configure_UI() def __configure_grid(self): self.grid_rowconfigure(0, weight=True) self.grid_rowconfigure(1, weight=True) self.grid_rowconfigure(2, weight=True) self.grid_columnconfigure(0, minsize=self.Constants.input_width) self.grid_columnconfigure(2, minsize=self.Constants.input_width) self.grid_columnconfigure(1, minsize=self.Constants.separator_width) def __configure_UI(self): self.Constants.currency_1 = StringVar(self) self.Constants.currency_1.set("Currency 1") self.__currency_name_menu = OptionMenu( self, self.Constants.currency_1, *self.Constants.currency_options) self.__currency_name_menu.configure(bg="steelblue") self.__currency_name_menu.grid(row=0, column=0, sticky=self.Constants.left) self.Constants.currency_2 = StringVar(self) self.Constants.currency_2.set("Currency 2") self.__result_name_menu = OptionMenu(self, self.Constants.currency_2, *self.Constants.currency_options) self.__result_name_menu.configure(bg="steelblue") self.__result_name_menu.grid(row=0, column=2, sticky=self.Constants.left) separator_label = Label(self) separator_label.configure(text=self.Constants.separator_text) separator_label.grid(row=1, column=1, sticky=self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text="0") self.__result_label.grid(row=1, column=2, sticky=self.Constants.left) self.__convert_button = Button(self) self.__convert_button.configure(bg="lightslategray", text=self.Constants.convert_text) self.__convert_button.grid(row=2, column=0, columnspan=3, sticky=self.Constants.center) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate="key", validatecommand=vcmd) self.__currency_input.grid(row=1, column=0, sticky=self.Constants.center) def __did_tap_convert(self, event): if self.__convert_handler is None: return try: ammount_to_convert = float(self.__currency_input.get()) except ValueError: return else: if self.Constants.currency_1.get() == "Currency 1": self.update_result("Without kind of currency 1") elif self.Constants.currency_2.get() == "Currency 2": self.update_result("Without kind of currency 2") elif self.Constants.currency_1.get( ) == self.Constants.currency_2.get(): self.update_result(str(ammount_to_convert)) else: self.__convert_handler(self.Constants.currency_1.get(), self.Constants.currency_2.get(), ammount_to_convert) def update_result(self, text): self.__result_label.configure(text=text) def __checkNumberOnly(self, action, value_if_allowed): if action != '1': return True try: float(value_if_allowed) except ValueError: return False else: return True
class View(tk.Frame): def __init__(self): self.root = tk.Tk() super().__init__(self.root) self.root.configure(background='#1C1B18') self.__controller = None self.__canvas = None self.__canvas_frame = None self.__player_label = None self.__label_info = StringVar() self.__option_menu = None self.__canvas_logo = None self.__canvas_frame_logo = None self.__button_color = '#921414' self.__player_color = '#921414' self.__button1 = tk.Button(self, command=lambda: self.__controller.click_button(1)) self.__button2 = tk.Button(self, command=lambda: self.__controller.click_button(2)) self.__button3 = tk.Button(self, command=lambda: self.__controller.click_button(3)) self.__button4 = tk.Button(self, command=lambda: self.__controller.click_button(4)) self.__button5 = tk.Button(self, command=lambda: self.__controller.click_button(5)) self.__button6 = tk.Button(self, command=lambda: self.__controller.click_button(6)) self.__button7 = tk.Button(self, command=lambda: self.__controller.click_button(7)) self.__reset_button = tk.Button(self, command=lambda: self.__controller.reset()) self.set_buttons() self.set_elements() def create_gameboard(self, color_board): self.grid(row=1, columnspan=14, sticky='N', padx=90, pady=10) self.configure(background='#1C1B18') self.master.title("Connect Four") self.create_canvas() self.__create_ovals(color_board) def update_gameboard(self, color_board): self.__create_ovals(color_board) def start_loop(self): self.mainloop() def create_canvas(self): self.__canvas_frame = tk.Frame(self, bd=2, relief=tk.RAISED) self.__canvas = tk.Canvas(self.__canvas_frame, bg='#1C1B18', width=720, height=620) self.__canvas.pack() self.__canvas_frame.grid(row=1, columnspan=8, rowspan=6, pady=5) def set_buttons(self): self.__button1.grid(row=0, column=0, sticky='E', padx=10, pady=2) self.__button1.config(height=2, width=5) self.__button1["text"] = "\n1.\n" self.__button1.config(background='#0E0E0E',fg='white') self.__button1.config(activebackground='#1C1B18') self.__button2.grid(row=0, column=1, sticky='E', padx=10, pady=2) self.__button2.config(height=2, width=5) self.__button2["text"] = "\n2.\n" self.__button2.config(background='#0E0E0E',fg='white') self.__button2.config(activebackground='#1C1B18') self.__button3.grid(row=0, column=2, sticky='E', padx=10, pady=2) self.__button3.config(height=2, width=5) self.__button3["text"] = "\n3.\n" self.__button3.config(background='#0E0E0E',fg='white') self.__button3.config(activebackground='#1C1B18') self.__button4.grid(row=0, column=3, sticky='E', padx=10, pady=2) self.__button4.config(height=2, width=5) self.__button4["text"] = "\n4.\n" self.__button4.config(background='#0E0E0E',fg='white') self.__button4.config(activebackground='#1C1B18') self.__button5.grid(row=0, column=4, sticky='E', padx=10, pady=2) self.__button5.config(height=2, width=5) self.__button5["text"] = "\n5.\n" self.__button5.config(background='#0E0E0E',fg='white') self.__button5.config(activebackground='#1C1B18') self.__button6.grid(row=0, column=5, sticky='E', padx=10, pady=2) self.__button6.config(height=2, width=5) self.__button6["text"] = "\n6.\n" self.__button6.config(background='#0E0E0E',fg='white') self.__button6.config(activebackground='#1C1B18') self.__button7.grid(row=0, column=6, sticky='E', padx=5) self.__button7.config(height=2, width=5) self.__button7["text"] = "\n7.\n" self.__button7.config(background='#0E0E0E', fg='white') self.__button7.config(activebackground='#1C1B18') self.__reset_button["text"] = "RESET GAME\n" self.__reset_button.config(background='#0E0E0E',fg='white') self.__reset_button.config(activebackground='#1C1B18') self.__reset_button.grid(row=1, column=10, sticky='N', padx=20, pady=200) def set_elements(self): self.__label_info.set("PLAYER 1") self.__player_label = tk.Label(self, textvariable=self.__label_info, width=20, height=5, bg='#1C1B18', fg='white', bd=0, highlightthickness=0, font=('Helvetica', 18)) self.__player_label.grid(row=1, column=10, sticky='N', pady=5, padx=1) self.__canvas_frame_logo = tk.Frame(self, bd=0, relief=tk.RAISED) self.__canvas_logo = tk.Canvas(self.__canvas_frame_logo, bg=self.__player_color, width=80, height=80) self.__canvas_logo.pack() self.__canvas_frame_logo.grid(row=1, column=11, sticky='N', pady=20) variable = StringVar(self.root) variable.set("Klasyczna") def option_menu_command(value): self.__controller.add_model(value) self.__option_menu = OptionMenu(self, variable, "Klasyczna", "Tylko w poziomie", "Tylko w pionie", "Tylko uskośne", command=option_menu_command) self.__option_menu.configure(width=15) self.__option_menu.grid(row=1, column=11, sticky='N', pady=200, padx=20) def add_controller(self, controller): self.__controller = controller def update_information(self): if self.__label_info.get() == "PLAYER 1": self.__label_info.set("PLAYER 2") self.__player_color = '#EEC111' self.__canvas_logo.configure(bg=self.__player_color) else: self.__label_info.set("PLAYER 1") self.__player_color = '#921414' self.__canvas_logo.configure(bg=self.__player_color) def reset_view(self): self.__label_info.set("PLAYER 1") self.__player_color = '#921414' self.__canvas_logo.configure(bg=self.__player_color) @staticmethod def show_warning_window(message): messagebox.showwarning("Warning", message) @staticmethod def show_message_window(message): messagebox.showinfo("Info", message) def __create_ovals(self, color_board): for i in range(0, 6): for j in range(0, 7): self.__canvas.create_oval(j*100+20, i*100+20, j*100+110, i*100+110, fill=color_board[i][j] if color_board[i][j] is not None else '#C1C1B5')
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller opFrame = Frame(self) opFrame.columnconfigure(0, pad=5) opFrame.columnconfigure(1, pad=5) opFrame.columnconfigure(2, pad=5) opFrame.rowconfigure(0, pad=5) opFrame.rowconfigure(1, pad=5) opFrame.rowconfigure(2, pad=5) opFrame.rowconfigure(3, pad=5) opFrame.rowconfigure(4, pad=5) opFrame.rowconfigure(5, pad=5) title = Label(opFrame, text="CipherBox") title.grid(row=0, columnspan=3) # Cryptography options cylabel = Label(opFrame, text="Crypto") cylabel.grid(row=1, column=0, padx=5, pady=20) CYOPTIONS = [ "Caesar", "Vigenere", "One-time pad", "MD5 Hash", "RSA", "RSA Key Generator" ] cyselect = StringVar(opFrame) cyselect.set(CYOPTIONS[0]) # default value cyoption = OptionMenu(opFrame, cyselect, *CYOPTIONS) cyoption.grid(row=1, column=1, padx=5, pady=5) cyoption.configure(width=30) cybutton = Button( opFrame, text="Go", command=lambda: controller.show_frame(cyselect.get())) cybutton.grid(row=1, column=2) cybutton.configure(width=3, height=2) # String options slabel = Label(opFrame, text="Strings") slabel.grid(row=2, column=0, padx=5, pady=5) SOPTIONS = [ "ASCII chart", "Base64 encode", "URL encode", "UTF-8 encode" ] sselect = StringVar(opFrame) sselect.set(SOPTIONS[0]) # default value soption = OptionMenu(opFrame, sselect, *SOPTIONS) soption.grid(row=2, column=1, padx=5, pady=5) soption.configure(width=30) sbutton = Button(opFrame, text="Go", command=lambda: controller.show_frame(sselect.get())) sbutton.grid(row=2, column=2, padx=5, pady=5) sbutton.configure(width=3, height=2) # Arithmetic options alabel = Label(opFrame, text="Arithmetic") alabel.grid(row=3, column=0) AOPTIONS = [ "Unsigned Binary", "Sign and Magnitude", "One's Complement", "Two's Complement", "Hexadecimal", "Modulus Calculator", "Prime Number Checker" ] aselect = StringVar(opFrame) aselect.set(AOPTIONS[0]) # default value aoption = OptionMenu(opFrame, aselect, *AOPTIONS) aoption.grid(row=3, column=1, padx=5, pady=5) aoption.configure(width=30) abutton = Button(opFrame, text="Go", command=lambda: controller.show_frame(aselect.get())) abutton.grid(row=3, column=2, padx=5, pady=5) abutton.configure(width=3, height=2) # Converter options clabel = Label(opFrame, text="Converter") clabel.grid(row=4, column=0) COPTIONS = [ "All Numbers", "All Numbers (alternate)", "Binary Representation", "Data Storage Units", 'String to Binary' ] cselect = StringVar(opFrame) cselect.set(COPTIONS[0]) # default value coption = OptionMenu(opFrame, cselect, *COPTIONS) coption.grid(row=4, column=1, padx=5, pady=5) coption.configure(width=30) cbutton = Button(opFrame, text="Go", command=lambda: controller.show_frame(cselect.get())) cbutton.grid(row=4, column=2, padx=5, pady=5) cbutton.configure(width=3, height=2) # Other options olabel = Label(opFrame, text="Other") olabel.grid(row=5, column=0) OOPTIONS = ["Hexdump"] oselect = StringVar(opFrame) oselect.set(OOPTIONS[0]) # default value ooption = OptionMenu(opFrame, oselect, *OOPTIONS) ooption.grid(row=5, column=1, padx=5, pady=5) ooption.configure(width=30) obutton = Button(opFrame, text="Go", command=lambda: controller.show_frame(oselect.get())) obutton.grid(row=5, column=2, padx=5, pady=5) obutton.configure(width=3, height=2) opFrame.pack(pady=50)
class Interface(Frame): def __init__(self, master=None, data={}): Frame.__init__(self, master) self.version = "1.2.0" self.master.title(data["window_name"]) self.data = data self._main = Main(self.data["directory_name"]) self.default = StringVar() self.default.set(self._main.language) self.load_config() self.init_elements() self.fill_from_config() menu_options = (("Open Window", None, self.back), ("Start", None, self.start_service), ("Stop", None, self.stop_service)) self.systray = SysTrayIcon("./{0}/icon.ico".format( self.data["directory_name"]), "SIVA", menu_options, on_quit=self.quit_service) self.systray.start() self.master.protocol("WM_DELETE_WINDOW", self.vanish) def quit_service(self, e=None): exit(0) def vanish(self): self.master.withdraw() def back(self, e=None): self.master.update() self.master.deiconify() def load_config(self): if path.isfile("./{0}/config.json".format( self.data["directory_name"])): with open("./{0}/config.json".format(self.data["directory_name"]), "r") as out: self.config = json.load(out) else: with open("./{0}/config.json".format(self.data["directory_name"]), "w+") as out: self.config = { "api_token": "", "platform": "Playstation", "username": "", "language": "en", "autostart": False, "id_search": False } json.dump(self.config, out, indent=4) def fill_from_config(self): self.token_box.delete(0, END) self.token_box.insert(0, self.config["api_token"]) self.option_menu_default.set(self.config["platform"]) self.username_box.delete(0, END) self.username_box.insert(0, self.config["username"]) if self.config.get("autostart", None) == None: self.config["autostart"] = False if self.config.get("autostart", None) == True: self.start_service() if self.config.get("id_search", None) == None: self.config["id_search"] = False self.search_with_id.set(self.config["id_search"]) def init_elements(self): self.menubar = Menu(self.master) self.master.config(menu=self.menubar) self.menu_dropdown_siva = Menu(self.menubar) self.menu_dropdown_themes = Menu(self.menubar) self.menu_dropdown_links = Menu(self.menubar) self.menu_dropdown_help = Menu(self.menubar) self.menu_dropdown_language = Menu(self.menubar) self.menu_dropdown_siva.add_command( label="Start", command=lambda: self.start_service()) self.menu_dropdown_siva.add_command( label="Stop", command=lambda: self.stop_service()) self.auto_start = BooleanVar() self.auto_start.set(self.config.get("autostart", False)) self.menu_dropdown_siva.add_checkbutton( label="Autostart", onvalue=True, offvalue=False, variable=self.auto_start, command=lambda: self.start_service()) self.search_with_id = BooleanVar() self.search_with_id.set(self.config.get("id_search", False)) self.menu_dropdown_siva.add_checkbutton(label="Login With ID", onvalue=True, offvalue=False, variable=self.search_with_id) self.menu_dropdown_themes.add_command( label="Light Theme", command=lambda: self.light_mode()) self.menu_dropdown_themes.add_command(label="Dark Theme", command=lambda: self.dark_mode()) self.menu_dropdown_links.add_command( label="Get A Token", command=lambda: open_new_tab( "https://www.bungie.net/en/Application")) self.menu_dropdown_links.add_command( label="Message Me On Reddit", command=lambda: open_new_tab( "https://www.reddit.com/message/compose?to=TheTimebike&subject=SIVA" )) self.menu_dropdown_links.add_command( label="Github", command=lambda: open_new_tab("https://github.com/TheTimebike/SIVA" )) self.menu_dropdown_links.add_command( label="Report An Issue", command=lambda: open_new_tab( "https://github.com/TheTimebike/SIVA/issues")) self.menu_dropdown_help.add_command( label="About", command=lambda: messagebox.showinfo( "SIVA", "SIVA:\nVersion: {0}\nCreator: u/TheTimebike".format( self.version))) language_conversion_table = self.get_conversion_table("language") for lang, key in language_conversion_table.items(): self.add_language(lang, key) self.menubar.add_cascade(label="SIVA", menu=self.menu_dropdown_siva) self.menubar.add_cascade(label="Themes", menu=self.menu_dropdown_themes) self.menubar.add_cascade(label="Links", menu=self.menu_dropdown_links) self.menubar.add_cascade(label="Help", menu=self.menu_dropdown_help) self.menubar.add_cascade(label="Languages", menu=self.menu_dropdown_language) if self.data["version"] != self.version: self.menubar.add_command(label="Update", command=lambda: update(self)) self.label_1 = Label(self.master, text="API Token") self.label_1.place(x=315, y=10) self.token_box = Entry(self.master, width=50) self.token_box.place(x=10, y=10) self.token_button = Button( self.master, width=20, height=1, text="How Do I Find This?", command=lambda: open_new_tab( "https://www.bungie.net/en/Application")) self.token_button.place(x=375, y=9) self.start_button = Button(self.master, width=72, height=5, text="Start!", command=lambda: self.start_service()) self.start_button.place(x=10, y=70) self.option_menu_default = StringVar() self.option_menu_default.set("Playstation") self.option_menu = OptionMenu(self.master, self.option_menu_default, "Playstation", "Xbox", "Steam", "Stadia") self.option_menu.configure(highlightthickness=0) self.option_menu.place(x=8, y=35) self.label_2 = Label(self.master, text="Select Platform") self.label_2.place(x=110, y=40) self.username_box = Entry(self.master, width=40) self.username_box.place(x=220, y=40) self.label_3 = Label(self.master, text="Username") self.label_3.place(x=460, y=40) self.elements = { "labels": [self.label_1, self.label_2, self.label_3], "entrys": [self.username_box, self.token_box], "optionmenus": [self.option_menu], "buttons": [self.start_button, self.token_button] } def add_language(self, lang, key): self.menu_dropdown_language.add_radiobutton( label=lang, value=key, variable=self.default, command=lambda: self.change_language(key)) def change_language(self, key): self._main.language = key self._main.configurator.save({ "api_token": self.token_box.get(), "platform": self.option_menu_default.get(), "username": self.username_box.get(), "language": self._main.language, "autostart": self.auto_start.get() }) def light_mode(self): text_colour = "black" box_colour = "white" background_colour = "#f0f0f0" self.master.configure(background=background_colour) for element in self.elements["labels"]: element.configure(background=background_colour, foreground=text_colour) for element in self.elements["buttons"]: element.configure(background=background_colour, foreground=text_colour) for element in self.elements["entrys"]: element.configure(background=box_colour, foreground=text_colour) for element in self.elements["optionmenus"]: element.configure(highlightthickness=0, background=background_colour, foreground=text_colour, activebackground=background_colour, activeforeground=text_colour) def dark_mode(self): text_colour = "white" box_colour = "#484b52" background_colour = "#36393f" self.master.configure(background=background_colour) for element in self.elements["labels"]: element.configure(background=background_colour, foreground=text_colour) for element in self.elements["buttons"]: element.configure(background=background_colour, foreground=text_colour) for element in self.elements["entrys"]: element.configure(background=box_colour, foreground=text_colour) for element in self.elements["optionmenus"]: element.configure(highlightthickness=0, background=background_colour, foreground=text_colour, activebackground=background_colour, activeforeground=text_colour) def start_service(self, e=None): self._main.configurator.save({ "api_token": self.token_box.get(), "platform": self.option_menu_default.get(), "username": self.username_box.get(), "language": self._main.language, "autostart": self.auto_start.get(), "id_search": self.search_with_id.get() }) self.thread = Thread(target=self._main.start_siva, args=(self, )) self.thread.daemon = True self.thread.start() self.start_button.config(text="Stop!", command=lambda: self.stop_service()) def stop_service(self, e=None): self._main.run = False self.start_button.config(text="Start!", command=lambda: self.start_service()) def get_conversion_table(self, table): _index = get( "https://raw.githubusercontent.com/TheTimebike/SIVA/master/conversion_tables/index.json" ) _data_url = _index.json()[table] _data = get(_data_url) return _data.json() def error(self, error_enum): self.stop_service() error_conversion_table = self.get_conversion_table("error") messagebox.showinfo(error_conversion_table["error_window_name"], error_conversion_table["errors"][error_enum]) return None def create_pick_account_interface(self, acc_list): self.select_acc_window = SubWindow(self.master, acc_list, self._main) self.select_acc_window.master.iconbitmap("./{0}/icon.ico".format( self.data["directory_name"]))
class Application(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack(padx=20, pady=20) self.config(background='white') self.Note = Note() self.noteFiles = self.Note.browse() self.browserNav = {} self.create_widgets() self.encFile = "" self.encFileLoc = "" self.Key = None def noteReader(self, title): nt = Note() def nt2(): if nt.fileExist(title): content = nt.read(title) self.noteEd(title, content) else: self.noteEd(title + ": File not Found", "Error :(\nPlease check if file has been deleted") return self.browserNav[title] = nt2 return def clearFrame(self, frame): for widget in frame.winfo_children(): widget.destroy() def create_widgets(self): self.a = Frame(self, bd=2) self.a.pack(side="top") self.a.configure(background="white") self.menubuttons() self.b = Frame(self) self.b.pack(side="top") self.b.configure(background="white") self.left = Frame(self.b, padx=20, pady=10) self.left.configure(background="white") self.left.pack(side="left", anchor="n") self.right = Frame(self.b, padx=20, pady=10) self.right.pack(side="right") self.right.configure(background="white") self.encBtn() def menubuttons(self): self.note = Button(self.a, text="Notes", command=self.noteFrames, activebackground="green", activeforeground="white", bg="white", font=("Helvetica", 18, "bold"), bd=0, height=3, width=15, padx=2, pady=2, fg="green") self.note.grid(row=2, column=1) self.enc = Button(self.a, text="Encrypt", command=self.encBtn, activebackground="green", activeforeground="white", bg="white", font=("Helvetica", 18, "bold"), bd=0, height=3, width=15, padx=2, pady=2, fg="gray") self.enc.grid(row=2, column=3) self.dec = Button(self.a, text="Decrypt", command=self.decBtn, activebackground="green", activeforeground="white", bg="white", font=("Helvetica", 18, "bold"), bd=0, height=3, width=15, padx=2, pady=2, fg="gray") self.dec.grid(row=2, column=5) def delEd(self): title = self.notetitle.get("1.0", "end") self.Note.remove(title.rstrip()) self.noteEd("Untitled", "Deleted from notes: " + title) return def noteFrames(self): self.enc['fg'] = "gray" self.note['fg'] = "green" self.dec['fg'] = "gray" self.clearFrame(self.left) self.clearFrame(self.right) self.browse = Button(self.left, text="Browse", command=self.browseBtn, activebackground="green", activeforeground="white", bg="white", font=("Helvetica", 12), bd=0, height=2, width=10, padx=2, pady=2, fg="gray", relief="solid") self.browse.pack(side="top") self.create = Button(self.left, text="Create", command=self.createBtn, highlightbackground="green", activebackground="green", activeforeground="white", bg="white", font=("Helvetica", 12), bd=0, height=2, width=10, padx=2, pady=2, fg="gray", relief="solid") self.create.pack(side="top") self.browseBtn() def clearEdBtn(self): self.newnote.delete("1.0", "end") def saveEdBtn(self): title = self.notetitle.get("1.0", "end") print(title) content = self.newnote.get("1.0", "end") print(content) self.Note.save(title.rstrip(), content) print("saved") def noteEd(self, title, content): self.clearFrame(self.right) self.notetitle = Text(self.right, width=75, height=1, bd=1, relief="solid", pady=5, padx=3, font=("Helvetica", 12, "bold")) self.notetitle.insert("1.0", title) self.notetitle.pack(side="top") self.newnote = Text(self.right, width=75, height=20, bd=1, relief="solid", pady=5, padx=3, spacing2=3, font=("Helvetica", 12)) self.newnote.insert("1.0", content) self.newnote.pack(side="top") self.addnote = Button(self.right, text="Save", command=self.saveEdBtn, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.addnote.pack(side="left", anchor="w") self.clear = Button(self.right, text="Clear", command=self.clearEdBtn, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.clear.pack(side="left", anchor="w") self.delete = Button(self.right, text="Delete", command=self.delEd, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.delete.pack(side="right", anchor="w") self.back = Button(self.right, text="Back", command=self.browseBtn, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.back.pack(side="right", anchor="w") def createBtn(self): self.clearFrame(self.right) self.notetitle = Text(self.right, width=75, height=1, bd=1, relief="solid", pady=5, padx=3, font=("Helvetica", 12, "bold")) self.notetitle.insert("1.0", "Untitled") self.notetitle.pack(side="top") self.newnote = Text(self.right, width=75, height=20, bd=1, relief="solid", pady=5, padx=3, spacing2=3, font=("Helvetica", 12)) self.newnote.pack(side="top") self.addnote = Button(self.right, text="Save", command=self.saveEdBtn, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.addnote.pack(side="left", anchor="w") self.clear = Button(self.right, text="Clear", command=self.clearEdBtn, activebackground="green", activeforeground="white", bg="#f8cd0c", relief="flat", font=("Helvetica", 12), bd=1, height=2, width=10, padx=2, pady=2, fg="white") self.clear.pack(side="left", anchor="w") self.create['fg'] = 'black' self.create['bd'] = 2 self.browse['fg'] = 'gray' self.browse['bd'] = 0 return def browseBtn(self): self.clearFrame(self.right) canvas = Canvas(self.right, width=700, height=500, bg="white") scroll_y = Scrollbar(self.right, orient="vertical", command=canvas.yview) frame = Frame(canvas, width=700, height=500, bg="white") self.noteFiles = self.Note.browse() for x in self.noteFiles: self.noteReader(x) temp = Button(frame, text=x, command=self.browserNav[x], activebackground="#5c8066", activeforeground="white", anchor="w", relief="flat", font=("Helvetica", 12), padx=5, pady=5, height=2, width=700, bg="#95a69a", fg="white") temp.pack(side="top") temp2 = Label(frame, bg="white") temp2.pack(side="top") canvas.create_window(0, 0, anchor='nw', window=frame) canvas.update_idletasks() canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scroll_y.set) canvas.pack(fill='both', expand=True, side='left') scroll_y.pack(fill='y', side='right') self.browse['fg'] = 'black' self.browse['bd'] = 2 self.create['fg'] = 'gray' self.create['bd'] = 0 return def encBtn(self): self.enc['fg'] = "green" self.note['fg'] = "gray" self.dec['fg'] = "gray" self.clearFrame(self.left) self.clearFrame(self.right) self.right2 = Frame(self.right) self.right2.pack(side="top") self.keyChoice = StringVar(self.right2) self.keyChoice.set("Choose Key") self.option = OptionMenu(self.left, self.keyChoice, "Generate Key", "Upload Key", "Type Key", command=self.chooseKey) self.option['menu'].config(bg="white", selectcolor="blue", relief="solid", font=("Helvetica", 12)) self.option.configure(bg="white", width=12, bd=2, activebackground="white", relief="solid", font=("Helvetica", 12)) self.option.pack(side="top") self.keyText = Text(self.right2, width="70", height=1, relief="solid", font=("Helvetica", 14), pady=5) self.keyText.pack(side="left") self.b1 = Button(self.right, text="Select file to be encrypted", activebackground="gray", activeforeground="white", bg="#f28100", font=("Helvetica", 12), bd=2, relief='flat', height=3, width=85, padx=2, pady=2, fg="white", command=self.askFileLocation) self.b2 = Button( self.right, text="Select location where encrypted file is to be stored", activebackground="gray", activeforeground="white", bg="#f28100", font=("Helvetica", 12), bd=2, relief='flat', height=3, width=85, padx=2, pady=2, fg="white", command=self.askFolderStore) self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.b1.pack(side="top") self.t1 = Text(self.right, relief="flat", width="110", height=1, font=("Helvetica", 10), pady=10) self.t1.pack(side="top") self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.t2 = Text(self.right, relief="flat", pady=10, width="110", height=1, font=("Helvetica", 10)) self.b2.pack(side="top") self.t2.pack(side="top") self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.b3 = Button(self.right, text="Start", activebackground="gray", activeforeground="white", bg="#3f6621", font=("Helvetica", 14), bd=2, relief='flat', height=2, width=10, padx=2, pady=2, fg="white", command=self.startBtn) self.b3.pack(side="right") return def askFileLocation(self): x = filedialog.askopenfile(mode="r") self.t1.delete('1.0', 'end') self.t1.insert('1.0', x.name) self.t1['relief'] = 'solid' self.encFile = x.name def askFolderStore(self): x = filedialog.askdirectory() self.t2.delete('1.0', 'end') self.t2.insert('1.0', x) self.t2['relief'] = 'solid' self.encFileLoc = x def startBtn(self): if not path.isfile(self.encFile): messagebox.showerror( title="File Path Wrong", message= "Please enter correct file path. Click on orange button.") if not path.exists(self.encFileLoc): messagebox.showerror( title="Invalid Folder Location", message= "Please enter correct folder path. Click on orange button.") if len(self.keyText.get("1.0", "end").rstrip()) != 44: messagebox.showerror( title="Key Error", message= "Please enter a key (length: 44) to encrypt. You can generate one from the options. Remember to save it." ) if not self.Key: self.Key = self.keyText.get("1.0", "end").rstrip() print(self.encFile) print(self.encFileLoc) f = FileOps() f.encryptFile(self.Key, self.encFile, self.encFileLoc) messagebox.showinfo('Encryption Done', message='Your file is now secure.') return def rem(self): try: self.saveKeyBtn.destroy() except: pass def chooseKey(self, val=""): self.keyText.delete("1.0", "end") self.rem() if val == "Generate Key": k = self.Note.e.generateKey() self.Key = k self.keyText.insert("1.0", k) self.saveKeyBtn = Button(self.right2, text="Save Key", bg="#f8cd0c", fg="white", relief="flat", command=self.saveGeneratedKey, font=("Helvetica", 12, "bold")) self.saveKeyBtn.pack(side="right") elif val == "Upload Key": self.select = filedialog.askopenfilename(filetypes=(("KEY File", "*.key"), ("All files", "*.*"))) print(self.select) f = open(self.select, 'rb') k = f.read() self.Key = k f.close() print(k) self.keyText.insert("1.0", k) def saveGeneratedKey(self): a = self.keyText.get("1.0", "end") file = filedialog.asksaveasfile(defaultextension=".key") file.write(a.rstrip()) def decStartBtn(self): if not path.isfile(self.encFile): messagebox.showerror( title="File Path Wrong", message= "Please enter correct file path. Click on orange button.") if not path.exists(self.encFileLoc): messagebox.showerror( title="Invalid Folder Location", message= "Please enter correct folder path. Click on orange button.") if len(self.keyText.get("1.0", "end").rstrip()) != 44: messagebox.showerror( title="Key Error", message= "Please enter a key (length: 44) to encrypt. You can generate one from the options. Remember to save it." ) if not self.Key: self.Key = self.keyText.get("1.0", "end").rstrip() print(self.encFile) print(self.encFileLoc) f = FileOps() f.decryptFile(self.Key, self.encFile, self.encFileLoc) messagebox.showinfo('Decryption Done', message='Your file is now readable.') return def decBtn(self): self.enc['fg'] = "gray" self.note['fg'] = "gray" self.dec['fg'] = "green" self.clearFrame(self.left) self.clearFrame(self.right) self.right2 = Frame(self.right) self.right2.pack(side="top") self.keyChoice = StringVar(self.right2) self.keyChoice.set("Choose Key") self.option = OptionMenu(self.left, self.keyChoice, "Generate Key", "Upload Key", "Type Key", command=self.chooseKey) self.option['menu'].config(bg="white", selectcolor="blue", relief="solid", font=("Helvetica", 12)) self.option.configure(bg="white", width=12, bd=2, activebackground="white", relief="solid", font=("Helvetica", 12)) self.option.pack(side="top") self.keyText = Text(self.right2, width="70", height=1, relief="solid", font=("Helvetica", 14), pady=5) self.keyText.pack(side="left") self.b1 = Button(self.right, text="Select file to be decrypted", activebackground="gray", activeforeground="white", bg="#f28100", font=("Helvetica", 12), bd=2, relief='flat', height=3, width=85, padx=2, pady=2, fg="white", command=self.askFileLocation) self.b2 = Button( self.right, text="Select location where decrypted file is to be stored", activebackground="gray", activeforeground="white", bg="#f28100", font=("Helvetica", 12), bd=2, relief='flat', height=3, width=85, padx=2, pady=2, fg="white", command=self.askFolderStore) self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.b1.pack(side="top") self.t1 = Text(self.right, relief="flat", width="110", height=1, font=("Helvetica", 10), pady=10) self.t1.pack(side="top") self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.t2 = Text(self.right, relief="flat", pady=10, width="110", height=1, font=("Helvetica", 10)) self.b2.pack(side="top") self.t2.pack(side="top") self.lab = Label(self.right, bg="white") self.lab.pack(side="top") self.b3 = Button(self.right, text="Start", activebackground="gray", activeforeground="white", bg="#3f6621", font=("Helvetica", 14), bd=2, relief='flat', height=2, width=10, padx=2, pady=2, fg="white", command=self.decStartBtn) self.b3.pack(side="right") return
class AnalysisToolsManager: def __init__(self, controller): self.tab = None self.controller = controller self.tk_format = utils.TkFormat(self.controller.config_info) self.analysis_dialog = None self.exclude_artifacts = IntVar() self.abs_val = IntVar() self.use_max_for_centers = IntVar() self.use_delta = IntVar() self.neg_depth = IntVar() self.normalize_entry = None self.right_zoom_entry = None self.right_zoom_entry2 = None self.left_zoom_entry = None self.left_zoom_entry2 = None self.left_slope_entry = None self.right_slope_entry = None self.slopes_listbox = None self.abs_val_check = None self.use_max_for_centers_check = None self.use_delta_check = None self.neg_depth_check = None self.exclude_artifacts_check = None self.extra_analysis_check_frame = None self.plot_slope_var = None self.offset_entry = None self.offset_sample_var = None self.plot_slope_menu = None self.plot_slope_button = None self.analyze_var = None self.outer_slope_frame = None self.slope_results_frame = None def show(self, tab): self.tab = tab self.tab.freeze( ) # You have to finish dealing with this before, say, opening another analysis box. buttons = { "reset": { self.select_tab: [], self.tab.reset: [], self.uncheck_exclude_artifacts: [], self.disable_plot: [], # utils.thread_lift_widget: [], }, "close": {}, } self.analysis_dialog = VerticalScrolledDialog(self.controller, "Analyze Data", "", buttons=buttons, button_width=13) self.analysis_dialog.top.attributes("-topmost", True) outer_normalize_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_normalize_frame.pack(expand=True, fill=BOTH) slope_title_label = Label(outer_normalize_frame, text="Normalize:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack() normalize_frame = Frame(outer_normalize_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) normalize_frame.pack() normalize_label = Label(normalize_frame, text="Wavelength (nm):", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.normalize_entry = Entry( normalize_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) normalize_button = Button( normalize_frame, text="Apply", command=self.normalize, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) normalize_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) normalize_button.pack(side=RIGHT, padx=(10, 10)) self.normalize_entry.pack(side=RIGHT, padx=self.tk_format.padx) normalize_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_offset_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_offset_frame.pack(expand=True, fill=BOTH) slope_title_label = Label(outer_offset_frame, text="Add offset to sample:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack(pady=(0, 15)) offset_sample_frame = Frame(outer_offset_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=self.tk_format.pady) offset_sample_frame.pack() offset_sample_label = Label(offset_sample_frame, text="Sample: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) offset_sample_label.pack(side=LEFT) self.offset_sample_var = StringVar() sample_names = [] repeats = False max_len = 0 for sample in self.tab.samples: if sample.name in sample_names: repeats = True else: sample_names.append(sample.name) max_len = np.max([max_len, len(sample.name)]) if repeats: sample_names = [] for sample in self.tab.samples: sample_names.append(sample.title + ": " + sample.name) max_len = np.max([max_len, len(sample_names[-1])]) self.offset_sample_var.set(sample_names[0]) # pylint: disable = no-value-for-parameter offset_menu = OptionMenu(offset_sample_frame, self.offset_sample_var, *sample_names) offset_menu.configure( width=max_len, highlightbackground=self.tk_format.highlightbackgroundcolor) offset_menu.pack(side=LEFT) offset_frame = Frame(outer_offset_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) offset_frame.pack() offset_label = Label(offset_frame, text="Offset:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.offset_entry = Entry( offset_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) offset_button = Button( offset_frame, text="Apply", command=self.offset, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) offset_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) offset_button.pack(side=RIGHT, padx=(10, 10)) self.offset_entry.pack(side=RIGHT, padx=self.tk_format.padx) offset_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_outer_zoom_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_outer_zoom_frame.pack(expand=True, fill=BOTH) zoom_title_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg) zoom_title_frame.pack(pady=(5, 10)) zoom_title_label = Label(zoom_title_frame, text="Adjust plot x and y limits:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) zoom_title_label.pack(side=LEFT, pady=(0, 4)) outer_zoom_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame = Frame(outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame.pack() zoom_label = Label(zoom_frame, text="x1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label2 = Label(zoom_frame, text="x2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button = Button( zoom_frame, text="Apply", command=self.apply_x, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_zoom_frame2 = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame2.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame2 = Frame(outer_zoom_frame2, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame2.pack() zoom_label3 = Label(zoom_frame2, text="y1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry2 = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label4 = Label(zoom_frame2, text="y2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry2 = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button2 = Button( zoom_frame2, text="Apply", command=self.apply_y, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button2.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button2.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label4.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry2.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label3.pack(side=RIGHT, padx=self.tk_format.padx) outer_outer_slope_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) outer_outer_slope_frame.pack(expand=True, fill=BOTH) self.outer_slope_frame = Frame(outer_outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) self.outer_slope_frame.pack(expand=True, fill=BOTH, pady=(0, 10)) slope_title_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg) slope_title_frame.pack(pady=(5, 5)) slope_title_label = Label(slope_title_frame, text="Analyze ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) slope_title_label.pack(side=LEFT, pady=(0, 4)) self.analyze_var = StringVar() self.analyze_var.set("slope") analyze_menu = OptionMenu( slope_title_frame, self.analyze_var, "slope", "band depth", "band center", "reflectance", # "reciprocity", "difference", command=self.disable_plot, ) analyze_menu.configure( width=10, highlightbackground=self.tk_format.highlightbackgroundcolor) analyze_menu.pack(side=LEFT) # We'll put checkboxes for additional options into this frame at the time the user selects a given option (e.g. # select 'difference' from menu, add option to calculate differences based on absolute value self.extra_analysis_check_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) self.extra_analysis_check_frame.pack() # Note that we are not packing this checkbutton yet. self.abs_val_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text=" Use absolute values for average differences", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.abs_val, ) self.use_max_for_centers_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " If band max is more prominent than\nband min, use to find center.", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.use_max_for_centers, ) self.use_max_for_centers_check.select() self.use_delta_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text=" Center at max \u0394" + "R from continuum \nrather than spectral min/max. ", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.use_delta, ) self.use_delta_check.select() self.neg_depth_check = Checkbutton( self.extra_analysis_check_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " If band max is more prominent than \nband min, report negative depth.", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.neg_depth, ) self.neg_depth_check.select() slope_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, highlightthickness=0) slope_frame.pack(pady=(15, 0)) slope_label = Label(slope_frame, text="x1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_slope_entry = Entry( slope_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) slope_label_2 = Label(slope_frame, text="x2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_slope_entry = Entry( slope_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) slope_button = Button( slope_frame, text="Calculate", command=self.calculate, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) slope_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) slope_button.pack(side=RIGHT, padx=(10, 10)) self.right_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx) slope_label_2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_slope_entry.pack(side=RIGHT, padx=self.tk_format.padx) slope_label.pack(side=RIGHT, padx=self.tk_format.padx) self.slope_results_frame = Frame(self.outer_slope_frame, bg=self.tk_format.bg) self.slope_results_frame.pack( fill=BOTH, expand=True ) # We'll put a listbox with slope info in here later after calculating. outer_plot_slope_frame = Frame(outer_outer_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=10) outer_plot_slope_frame.pack(expand=True, fill=BOTH) plot_slope_frame = Frame(outer_plot_slope_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) plot_slope_frame.pack(side=RIGHT) plot_slope_label = Label(plot_slope_frame, text="Plot as a function of", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.plot_slope_var = StringVar() self.plot_slope_var.set("e") self.plot_slope_menu = OptionMenu(plot_slope_frame, self.plot_slope_var, "e", "i", "g", "e,i", "theta", "az, e") self.plot_slope_menu.configure( width=2, highlightbackground=self.tk_format.highlightbackgroundcolor) self.plot_slope_button = Button( plot_slope_frame, text="Plot", command=self.plot, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) self.plot_slope_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, state=DISABLED, ) self.plot_slope_button.pack(side=RIGHT, padx=(10, 10)) self.plot_slope_menu.pack(side=RIGHT, padx=self.tk_format.padx) plot_slope_label.pack(side=RIGHT, padx=self.tk_format.padx) exclude_artifacts_frame = Frame(self.analysis_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1) exclude_artifacts_frame.pack(fill=BOTH, expand=True) self.exclude_artifacts_check = Checkbutton( exclude_artifacts_frame, selectcolor=self.tk_format.check_bg, fg=self.tk_format.textcolor, text= " Exclude data susceptible to artifacts\n (high g, 1000-1400 nm) ", bg=self.tk_format.bg, pady=self.tk_format.pady, highlightthickness=0, variable=self.exclude_artifacts, # TODO: check if the comma is meant to be there in the lambda definition command=lambda x="foo", : self.tab.set_exclude_artifacts( self.exclude_artifacts.get()), ) self.exclude_artifacts_check.pack() if self.tab.exclude_artifacts: self.exclude_artifacts_check.select() self.analysis_dialog.interior.configure(highlightthickness=1, highlightcolor="white") def calculate(self): try: self.controller.view_notebook.select(self.tab.top) except TclError: print("Error selecting tab in analysis_tools_manager.calculate().") print(self.tab) pass artifact_warning = False if self.analyze_var.get() == "slope": left, right, slopes, artifact_warning = self.tab.calculate_slopes( self.left_slope_entry.get(), self.right_slope_entry.get()) self.update_entries(left, right) self.populate_listbox(slopes) self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"]) elif self.analyze_var.get() == "band depth": left, right, depths, artifact_warning = self.tab.calculate_band_depths( self.left_slope_entry.get(), self.right_slope_entry.get(), self.neg_depth.get(), self.use_delta.get(), ) self.update_entries(left, right) self.populate_listbox(depths) self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"]) elif self.analyze_var.get() == "band center": left, right, centers, artifact_warning = self.tab.calculate_band_centers( self.left_slope_entry.get(), self.right_slope_entry.get(), self.use_max_for_centers.get(), self.use_delta.get(), ) self.update_entries(left, right) self.populate_listbox(centers) self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"]) elif self.analyze_var.get() == "reflectance": left, right, reflectance, artifact_warning = self.tab.calculate_avg_reflectance( self.left_slope_entry.get(), self.right_slope_entry.get()) self.update_entries(left, right) self.populate_listbox(reflectance) self.update_plot_menu(["e", "i", "g", "e,i", "theta", "az, e"]) elif self.analyze_var.get() == "reciprocity": left, right, reciprocity, artifact_warning = self.tab.calculate_reciprocity( self.left_slope_entry.get(), self.right_slope_entry.get()) self.update_entries(left, right) self.populate_listbox(reciprocity) self.update_plot_menu(["e", "i", "g", "e,i"]) elif self.analyze_var.get() == "difference": left, right, error, artifact_warning = self.tab.calculate_error( self.left_slope_entry.get(), self.right_slope_entry.get(), self.abs_val.get()) # Tab validates left and right values. If they are no good, put in min and max wavelengths available. self.update_entries(left, right) self.populate_listbox(error) self.update_plot_menu(["\u03bb", "e,i"]) if artifact_warning: ErrorDialog( self, "Warning", "Warning: Excluding data potentially\ninfluenced by artifacts from 1000-1400 nm." ) self.analysis_dialog.min_height = 1000 self.analysis_dialog.update() def update_plot_menu(self, plot_options): self.plot_slope_var.set(plot_options[0]) self.plot_slope_menu["menu"].delete(0, "end") # Insert list of new options (tk._setit hooks them up to var) max_len = len(plot_options[0]) for option in plot_options: max_len = np.max([max_len, len(option)]) # pylint: disable = protected-access self.plot_slope_menu["menu"].add_command(label=option, command=tkinter._setit( self.plot_slope_var, option)) self.plot_slope_menu.configure(width=max_len) def update_entries(self, left, right): self.left_slope_entry.delete(0, "end") self.left_slope_entry.insert(0, str(left)) self.right_slope_entry.delete(0, "end") self.right_slope_entry.insert(0, str(right)) def populate_listbox(self, results): if len(results) > 0: self.slope_results_frame.pack(fill=BOTH, expand=True, pady=(10, 10)) try: self.slopes_listbox.delete(0, "end") except (AttributeError, TclError): self.slopes_listbox = utils.ScrollableListbox( self.slope_results_frame, self.tk_format.bg, self.tk_format.entry_background, self.tk_format.listboxhighlightcolor, selectmode=EXTENDED, ) self.slopes_listbox.configure(height=8) for result in results: self.slopes_listbox.insert("end", result) self.slopes_listbox.pack(fill=BOTH, expand=True) self.plot_slope_button.configure(state=NORMAL) def plot(self): if self.analyze_var.get() == "slope": self.tab.plot_slopes(self.plot_slope_var.get()) elif self.analyze_var.get() == "band depth": self.tab.plot_band_depths(self.plot_slope_var.get()) elif self.analyze_var.get() == "band center": self.tab.plot_band_centers(self.plot_slope_var.get()) elif self.analyze_var.get() == "reflectance": self.tab.plot_avg_reflectance(self.plot_slope_var.get()) elif self.analyze_var.get() == "reciprocity": self.tab.plot_reciprocity(self.plot_slope_var.get()) elif self.analyze_var.get() == "difference": new = self.tab.plot_error(self.plot_slope_var.get()) if self.plot_slope_var.get() == "\u03bb": x1 = float(self.left_slope_entry.get()) x2 = float(self.right_slope_entry.get()) new.adjust_x(x1, x2) # TODO: plots not always fully updating # (e.g. contour plot labels not showing up until you do a screen wiggle. # utils.thread_lift_widget(self.analysis_dialog.top) def normalize(self): self.select_tab() try: self.slopes_listbox.delete(0, "end") self.plot_slope_button.configure(state="disabled") except (AttributeError, TclError): pass self.tab.normalize(self.normalize_entry.get()) # thread = Thread(target=utils.lift_widget, args=(self.analysis_dialog.top,)) # thread.start() def offset(self): self.tab.offset(self.offset_sample_var.get(), self.offset_entry.get()) # This doesn't work - it hangs between thread.start() and thread.join(). Likely because of calls to canvas.draw() # thread = Thread(target=self.tab.offset, args=(self.offset_sample_var.get(), self.offset_entry.get())) # thread.start() # thread.join() # utils.lift_widget(self.analysis_dialog.top) def remove_topmost(self): print("removing!!") self.analysis_dialog.top.attributes("-topmost", False) def apply_x(self): self.controller.view_notebook.select(self.tab.top) try: x1 = float(self.left_zoom_entry.get()) x2 = float(self.right_zoom_entry.get()) self.tab.adjust_x(x1, x2) # utils.lift_widget(self.analysis_dialog.top) except ValueError: # utils.lift_widget(self.analysis_dialog.top) ErrorDialog( self, title="Invalid Zoom Range", label="Error! Invalid x limits: " + self.left_zoom_entry.get() + ", " + self.right_zoom_entry.get(), ) def apply_y(self): self.controller.view_notebook.select(self.tab.top) try: y1 = float(self.left_zoom_entry2.get()) y2 = float(self.right_zoom_entry2.get()) self.tab.adjust_y(y1, y2) # utils.lift_widget(self.analysis_dialog.top) except ValueError: # utils.lift_widget(self.analysis_dialog.top) ErrorDialog( self, title="Invalid Zoom Range", label="Error! Invalid y limits: " + self.left_zoom_entry2.get() + ", " + self.right_zoom_entry2.get(), ) def uncheck_exclude_artifacts(self): self.exclude_artifacts.set(0) self.exclude_artifacts_check.deselect() # utils.lift_widget(self.analysis_dialog.top) def disable_plot(self, analyze_var="None"): try: self.slopes_listbox.delete(0, "end") except (AttributeError, TclError): pass self.plot_slope_button.configure(state="disabled") if analyze_var == "difference": self.analysis_dialog.frame.min_height = 850 self.neg_depth_check.pack_forget() self.use_max_for_centers_check.pack_forget() self.use_delta_check.pack_forget() self.abs_val_check.pack() self.extra_analysis_check_frame.pack() elif analyze_var == "band center": self.analysis_dialog.frame.min_height = 1000 self.neg_depth_check.pack_forget() self.abs_val_check.pack_forget() self.use_delta_check.pack_forget() self.use_max_for_centers_check.pack() self.use_delta_check.pack() self.extra_analysis_check_frame.pack() elif analyze_var == "band depth": self.analysis_dialog.frame.min_height = 1000 self.abs_val_check.pack_forget() self.use_max_for_centers_check.pack_forget() self.use_delta_check.pack_forget() self.neg_depth_check.pack() self.use_delta_check.pack() self.extra_analysis_check_frame.pack() else: self.analysis_dialog.frame.min_height = 850 self.abs_val_check.pack_forget() self.neg_depth_check.pack_forget() self.use_max_for_centers_check.pack_forget() self.use_delta_check.pack_forget() self.extra_analysis_check_frame.grid_propagate(0) self.extra_analysis_check_frame.configure( height=1) # for some reason 0 doesn't work. self.extra_analysis_check_frame.pack() self.outer_slope_frame.pack() # utils.lift_widget(self.analysis_dialog.top) # def calculate_photometric_variability(self): # photo_var = self.tab.calculate_photometric_variability( # self.right_photo_var_entry.get(), self.left_photo_var_entry.get() # ) # try: # self.photo_var_listbox.delete(0, "end") # except: # self.photo_var_listbox = utils.ScrollableListbox( # self.photo_var_results_frame, # self.tk_format.bg, # self.tk_format.entry_background, # self.tk_format.listboxhighlightcolor, # selectmode=EXTENDED, # ) # for var in photo_var: # self.photo_var_listbox.insert("end", var) # self.photo_var_listbox.pack(fill=BOTH, expand=True) def select_tab(self): self.controller.view_notebook.select(self.tab.top)
class SerialGUI: def __init__(self, master): self.master = master master.title("DDR Pad Sensitivity") self.label = Label(master, text="DDRPad Sensitivity adjustment!") self.label.grid(row=0, sticky="nsew", columnspan=5) self.connection = None # port frame frame = tk.Frame(master) frame.grid(row=1, column=0, sticky="nsew", columnspan=5) self.setup_port_frame(frame) # sensitivity frame frame = tk.Frame(master) frame.grid(row=2, column=0, rowspan=5, columnspan=5, sticky="nsew") self.setup_sensitivity(frame) # debounce frame frame = tk.Frame(master) frame.grid(row=8, column=0, rowspan=5, columnspan=5, sticky="nsew") self.setup_debounce(frame) # bottom label label = Label( master, text= "Disclaimer: Pad slows down while debugging to 100hz~ ©2021 XeaL.", ) label.grid(row=13, column=0, columnspan=5, sticky="nsew") for row in range(14): self.master.grid_rowconfigure(row, weight=1) for col in range(5): self.master.grid_rowconfigure(col, weight=1) def setup_sensitivity(self, frame): Label(frame, text="🡄").grid(row=0, column=1, sticky="nsew") Label(frame, text="🡇").grid(row=0, column=2, sticky="nsew") Label(frame, text="🡅").grid(row=0, column=3, sticky="nsew") Label(frame, text="🡆").grid(row=0, column=4, sticky="nsew") # left side labels # sensitivity Label(frame, text="Pad's reported sensitivity (0-1000)").grid(row=1, column=0, sticky="nsew") Label(frame, text="Current pad sensor value (0-1000)").grid(row=2, column=0, sticky="nsew") Label(frame, text="Target pad sensor value (drag)").grid(row=3, column=0, sticky="nsew") Label(frame, text="Target pad sensor value (type)").grid(row=4, column=0, sticky="nsew") self.sens_bars = [] sens = serial_prog.get_sens() for i, sen in enumerate(sens): bar = ColoredBar(frame) bar.set_critical(sen) bar.grid(row=1, column=i + 1, sticky="nsew", rowspan=4) self.sens_bars.append(bar) self.write_sens_out = Button( frame, text="Write sensitivity to pad", command=self.on_write_sens_remote, ) self.write_sens_out.grid(row=6, column=1, columnspan=4, sticky="nsew") self.write_sens_out["state"] = "disabled" for row in range(7): frame.grid_columnconfigure(row, weight=1) for col in range(5): frame.grid_columnconfigure(col, weight=1) def setup_debounce(self, frame): Label(frame, text="Debounce in microseconds (5000µs = 5ms)").grid( row=0, columnspan=5, sticky="nsew") Label(frame, text="Firmware debounce").grid(row=1, column=0, sticky="nsew") Label(frame, text="Target debounce").grid(row=2, column=0, sticky="nsew") self.debounce_label = [] for i in range(4): label = Label(frame, text="(debounce in µs)") label.grid(row=1, column=i + 1, sticky="nsew") self.debounce_label.append(label) self.debounce_vars = [] debounce = serial_prog.get_debounce() for index, item in enumerate(debounce): trigger_var = IntVar() trigger_var.set(item) topEntry = Entry(frame, textvariable=trigger_var, justify="center") topEntry.bind("<FocusOut>", self.change_debounce) topEntry.grid(row=2, column=index + 1, sticky="nsew") self.debounce_vars.append(trigger_var) self.write_debounce_out = Button( frame, text="Write debounce time to pad", command=self.on_write_debounce_remote, ) self.write_debounce_out.grid(row=3, column=1, columnspan=4, sticky="nsew") self.write_debounce_out["state"] = "disabled" for row in range(4): frame.grid_columnconfigure(row, weight=1) for col in range(5): frame.grid_columnconfigure(col, weight=1) def setup_port_frame(self, frame): ports_avail = serial_prog.get_ports() if len(ports_avail) == 0: ports_avail = ["No ports available"] Label(frame, text="Choose a port:").grid(row=0, column=0, columnspan=2, sticky="nsew") self.port_var = StringVar() default_port = serial_prog.get_saved_port() if default_port in ports_avail: self.port_var.set(default_port) else: self.port_var.set(ports_avail[0]) self.port_select = OptionMenu(frame, self.port_var, *ports_avail) self.port_select.grid(row=0, column=2, columnspan=2, sticky="nsew") self.port_var.trace("w", self.on_change_port) self.connect_button = Button(frame, text="Connect", command=self.connect) self.connect_button.grid(row=0, column=4, columnspan=2, sticky="nsew") # debug on and off self.debug_on = Button(frame, text="Start pad data", command=self.turn_debug_on) self.debug_on["state"] = "disable" self.debug_on.grid(row=1, column=0, columnspan=3, sticky="nsew") self.debug_off = Button(frame, text="Stop pad data", command=self.turn_debug_off) self.debug_off["state"] = "disable" self.debug_off.grid(row=1, column=3, columnspan=3, sticky="nsew") for row in range(2): frame.grid_columnconfigure(row, weight=1) for col in range(6): frame.grid_columnconfigure(col, weight=1) def change_debounce(self, *args): values = serial_prog.get_debounce() for index, item in enumerate(self.debounce_vars): try: value = item.get() value = int(value) value = clamp_long(value) values[index] = value item.set(value) except: item.set(values[index]) raise serial_prog.set_debounce_config(values) self.update() def on_write_debounce_remote(self): self.change_debounce( ) # bug where you click this when a textbox is focused. self.connection.port_write_debounce() self.update() def on_write_sens_remote(self): # bug where defocus might not always work for sen in self.sens_bars: sen.set_critical_entry() sens = [sen.critical for sen in self.sens_bars] serial_prog.set_sens_config(sens) self.connection.port_write_sens() self.update() def update(self): self.master.update() def on_change_port(self, *args): value = self.port_var.get() if value != "No ports available": serial_prog.set_saved_port(self.port_var.get()) def connect(self): self.connection = serial_prog.SerialPort() self.connection.connect() self.port_select.configure(state="disabled") self.connect_button.configure(command=self.disconnect) self.connect_button["text"] = "Disconnect" self.debug_on["state"] = "normal" self.debug_off["state"] = "disabled" self.write_sens_out["state"] = "normal" self.write_debounce_out["state"] = "normal" self.turn_debug_on() self.update() def disconnect(self): self.turn_debug_off() self.connection.disconnect() self.connection = None self.connect_button.configure(command=self.connect) self.connect_button["text"] = "Connect" self.debug_on["state"] = "disabled" self.debug_off["state"] = "disabled" self.write_sens_out["state"] = "disabled" self.write_debounce_out["state"] = "disabled" self.update() def turn_debug_off(self): self.connection.port_debug_off() self.debug_on["state"] = "normal" self.debug_off["state"] = "disabled" self.update() def turn_debug_on(self): self.connection.port_debug_on() self.debug_on["state"] = "disabled" self.debug_off["state"] = "normal" self.update() def read(self): data = self.connection.read() # get last two lines data = data[-2:] pins = None sens = None debounce = None for item in data: item = item.decode("utf-8").lower().strip() if item.startswith("pins"): pins = get_numbers(item) if item.startswith("sens"): sens = get_numbers(item) if item.startswith("debounce"): debounce = get_numbers(item) if pins is not None: for i in range(len(pins)): self.sens_bars[i].set_value(pins[i]) if sens is not None: for i in range(len(sens)): self.sens_bars[i].set_firmware_value(sens[i]) if debounce is not None: for i in range(len(debounce)): self.debounce_label[i]["text"] = debounce[i] self.update()
def show(self, tab: Tab) -> None: # If the user already has dialogs open for editing the plot, close the extras to avoid confusion. self.tab = tab self.tab.freeze( ) # You have to finish dealing with this before, say, opening another analysis box. buttons = {"close": {}} if tab.x_axis != "contour": self.plot_settings_dialog = VerticalScrolledDialog(self.controller, "Plot Settings", "", buttons=buttons, button_width=13, min_height=715, width=360) self.plot_settings_dialog.top.wm_geometry("360x600") else: self.plot_settings_dialog = VerticalScrolledDialog(self.controller, "Plot Settings", "", buttons=buttons, button_width=13, min_height=300, width=300) self.plot_settings_dialog.top.wm_geometry("300x370") self.plot_settings_dialog.top.attributes("-topmost", True) outer_title_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_title_frame.pack(expand=True, fill=BOTH) title_frame = Frame(outer_title_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) title_frame.pack(fill=BOTH, expand=True) title_label = Label(title_frame, text="Plot title:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.title_entry = Entry( title_frame, width=20, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) title_button = Button( title_frame, text="Apply", command=self.set_title, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) title_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) title_button.pack(side=RIGHT, padx=(10, 20)) self.title_entry.pack(side=RIGHT, padx=self.tk_format.padx) title_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_outer_zoom_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_outer_zoom_frame.pack(expand=True, fill=BOTH) zoom_title_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg) zoom_title_frame.pack(pady=(5, 10)) zoom_title_label = Label(zoom_title_frame, text="Adjust plot x and y limits:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) zoom_title_label.pack(side=LEFT, pady=(0, 4)) outer_zoom_frame = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame = Frame(outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame.pack() zoom_label = Label(zoom_frame, text="x1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry_x = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label2 = Label(zoom_frame, text="x2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry_x = Entry( zoom_frame, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button = Button( zoom_frame, text="Apply", command=self.apply_x, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry_x.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry_x.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label.pack(side=RIGHT, padx=self.tk_format.padx) outer_zoom_frame2 = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame2.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame2 = Frame(outer_zoom_frame2, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame2.pack() zoom_label3 = Label(zoom_frame2, text="y1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry_y = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label4 = Label(zoom_frame2, text="y2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry_y = Entry( zoom_frame2, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button2 = Button( zoom_frame2, text="Apply", command=self.apply_y, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button2.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button2.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry_y.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label4.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry_y.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label3.pack(side=RIGHT, padx=self.tk_format.padx) if self.tab.plot.x_axis == "contour": outer_zoom_frame_z = Frame(outer_outer_zoom_frame, bg=self.tk_format.bg, padx=self.tk_format.padx) outer_zoom_frame_z.pack(expand=True, fill=BOTH, pady=(0, 10)) zoom_frame_z = Frame(outer_zoom_frame_z, bg=self.tk_format.bg, padx=self.tk_format.padx) zoom_frame_z.pack() zoom_label_z1 = Label(zoom_frame_z, text="z1:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.left_zoom_entry_z = Entry( zoom_frame_z, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_label_z2 = Label(zoom_frame_z, text="z2:", bg=self.tk_format.bg, fg=self.tk_format.textcolor) self.right_zoom_entry_z = Entry( zoom_frame_z, width=7, bd=self.tk_format.bd, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) zoom_button_z = Button( zoom_frame_z, text="Apply", command=self.apply_z, width=7, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) zoom_button_z.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) zoom_button_z.pack(side=RIGHT, padx=(10, 10)) self.right_zoom_entry_z.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label_z2.pack(side=RIGHT, padx=self.tk_format.padx) self.left_zoom_entry_z.pack(side=RIGHT, padx=self.tk_format.padx) zoom_label_z1.pack(side=RIGHT, padx=self.tk_format.padx) if tab.x_axis != "contour": outer_color_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_color_frame.pack(expand=True, fill=BOTH) color_label = Label(outer_color_frame, text="Color settings", bg=self.tk_format.bg, fg=self.tk_format.textcolor) color_label.pack() color_frame = Frame(outer_color_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) color_frame.pack(fill=BOTH, expand=True) color_sample_frame = Frame(color_frame, bg=self.tk_format.bg, padx=30, pady=0) color_sample_frame.pack(fill=BOTH, expand=True) color_sample_label = Label(color_sample_frame, text="Sample: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) color_sample_label.pack(side=LEFT) sample_names = [] repeats = False max_len = 0 for sample in self.tab.samples: if sample.name in sample_names: repeats = True else: sample_names.append(sample.name) max_len = np.max([max_len, len(sample.name)]) if repeats: sample_names = [] for sample in self.tab.samples: sample_names.append(sample.title + ": " + sample.name) max_len = np.max([max_len, len(sample_names[-1])]) self.color_sample_var.set(sample_names[0]) # pylint: disable = no-value-for-parameter color_menu = OptionMenu(color_sample_frame, self.color_sample_var, *sample_names) color_menu.configure( width=max_len, highlightbackground=self.tk_format.highlightbackgroundcolor) color_menu.pack(side=LEFT) color_color_frame = Frame(color_frame, bg=self.tk_format.bg, padx=40, pady=0) color_color_frame.pack(fill=BOTH, expand=True) color_sample_label = Label(color_color_frame, text="Color: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) color_sample_label.pack(side=LEFT) color_names = self.tab.plot.color_names self.color_color_var.set(color_names[0]) # pylint: disable = no-value-for-parameter color_menu = OptionMenu(color_color_frame, self.color_color_var, *color_names) color_menu.configure( width=max_len, highlightbackground=self.tk_format.highlightbackgroundcolor) color_menu.pack(side=LEFT) color_button = Button( color_frame, text="Apply", command=self.set_color, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) color_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) color_button.pack() if self.tab.plot.lines_drawn: outer_linestyle_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_linestyle_frame.pack(expand=True, fill=BOTH) linestyle_label = Label(outer_linestyle_frame, text="Linestyle settings", bg=self.tk_format.bg, fg=self.tk_format.textcolor) linestyle_label.pack() linestyle_frame = Frame(outer_linestyle_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) linestyle_frame.pack(fill=BOTH, expand=True) linestyle_sample_frame = Frame(linestyle_frame, bg=self.tk_format.bg, padx=30, pady=0) linestyle_sample_frame.pack(fill=BOTH, expand=True) linestyle_sample_label = Label(linestyle_sample_frame, text="Sample: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) linestyle_sample_label.pack(side=LEFT) sample_names = [] repeats = False max_len = 0 for sample in self.tab.samples: if sample.name in sample_names: repeats = True else: sample_names.append(sample.name) max_len = np.max([max_len, len(sample.name)]) if repeats: sample_names = [] for sample in self.tab.samples: sample_names.append(sample.title + ": " + sample.name) max_len = np.max([max_len, len(sample_names[-1])]) self.linestyle_sample_var.set(sample_names[0]) # pylint: disable = no-value-for-parameter linestyle_menu = OptionMenu(linestyle_sample_frame, self.linestyle_sample_var, *sample_names) linestyle_menu.configure(width=max_len, highlightbackground=self.tk_format. highlightbackgroundcolor) linestyle_menu.pack(side=LEFT) linestyle_linestyle_frame = Frame(linestyle_frame, bg=self.tk_format.bg, padx=44, pady=0) linestyle_linestyle_frame.pack(fill=BOTH, expand=True) linestyle_sample_label = Label(linestyle_linestyle_frame, text="Style: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) linestyle_sample_label.pack(side=LEFT) linestyle_names = ["Solid", "Dash", "Dot", "Dot-dash"] self.linestyle_linestyle_var.set(linestyle_names[0]) # pylint: disable = no-value-for-parameter linestyle_menu = OptionMenu(linestyle_linestyle_frame, self.linestyle_linestyle_var, *linestyle_names) linestyle_menu.configure(width=max_len, highlightbackground=self.tk_format. highlightbackgroundcolor) linestyle_menu.pack(side=LEFT) linestyle_button = Button( linestyle_frame, text="Apply", command=self.set_linestyle, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) linestyle_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format. highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) linestyle_button.pack() if self.tab.plot.markers_drawn: outer_markerstyle_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_markerstyle_frame.pack(expand=True, fill=BOTH) markerstyle_label = Label( outer_markerstyle_frame, text="Markerstyle settings", bg=self.tk_format.bg, fg=self.tk_format.textcolor, ) markerstyle_label.pack() markerstyle_frame = Frame(outer_markerstyle_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) markerstyle_frame.pack(fill=BOTH, expand=True) markerstyle_sample_frame = Frame(markerstyle_frame, bg=self.tk_format.bg, padx=30, pady=0) markerstyle_sample_frame.pack(fill=BOTH, expand=True) markerstyle_sample_label = Label(markerstyle_sample_frame, text="Sample: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) markerstyle_sample_label.pack(side=LEFT) sample_names = [] repeats = False max_len = 0 for sample in self.tab.samples: if sample.name in sample_names: repeats = True else: sample_names.append(sample.name) max_len = np.max([max_len, len(sample.name)]) if repeats: sample_names = [] for sample in self.tab.samples: sample_names.append(sample.title + ": " + sample.name) max_len = np.max([max_len, len(sample_names[-1])]) self.markerstyle_sample_var.set(sample_names[0]) # pylint: disable = no-value-for-parameter markerstyle_menu = OptionMenu(markerstyle_sample_frame, self.markerstyle_sample_var, *sample_names) markerstyle_menu.configure(width=max_len, highlightbackground=self.tk_format. highlightbackgroundcolor) markerstyle_menu.pack(side=LEFT) markerstyle_markerstyle_frame = Frame(markerstyle_frame, bg=self.tk_format.bg, padx=44, pady=0) markerstyle_markerstyle_frame.pack(fill=BOTH, expand=True) markerstyle_sample_label = Label(markerstyle_markerstyle_frame, text="Style: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) markerstyle_sample_label.pack(side=LEFT) markerstyle_names = ["Circle", "X", "Diamond", "Triangle"] self.markerstyle_markerstyle_var.set(markerstyle_names[0]) # pylint: disable = no-value-for-parameter markerstyle_menu = OptionMenu(markerstyle_markerstyle_frame, self.markerstyle_markerstyle_var, *markerstyle_names) markerstyle_menu.configure(width=max_len, highlightbackground=self.tk_format. highlightbackgroundcolor) markerstyle_menu.pack(side=LEFT) markerstyle_button = Button( markerstyle_frame, text="Apply", command=self.set_markerstyle, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) markerstyle_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format. highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) markerstyle_button.pack() outer_legend_frame = Frame( self.plot_settings_dialog.interior, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15, highlightthickness=1, ) outer_legend_frame.pack(expand=True, fill=BOTH) legend_frame = Frame(outer_legend_frame, bg=self.tk_format.bg, padx=self.tk_format.padx, pady=15) legend_frame.pack(fill=BOTH, expand=True) legend_legend_frame = Frame(legend_frame, bg=self.tk_format.bg, padx=20, pady=0) legend_legend_frame.pack(fill=BOTH, expand=True) legend_sample_label = Label(legend_legend_frame, text="Legend style: ", bg=self.tk_format.bg, fg=self.tk_format.textcolor) legend_sample_label.pack(side=LEFT) legend_names = ["Full list", "Gradient"] self.legend_legend_var.set(legend_names[0]) # pylint: disable = no-value-for-parameter legend_menu = OptionMenu(legend_legend_frame, self.legend_legend_var, *legend_names) legend_menu.configure( width=max_len, highlightbackground=self.tk_format.highlightbackgroundcolor) legend_menu.pack(side=LEFT) legend_button = Button( legend_legend_frame, text="Apply", command=self.set_legend, width=6, fg=self.tk_format.buttontextcolor, bg=self.tk_format.buttonbackgroundcolor, bd=self.tk_format.bd, ) legend_button.config( fg=self.tk_format.buttontextcolor, highlightbackground=self.tk_format.highlightbackgroundcolor, bg=self.tk_format.buttonbackgroundcolor, ) legend_button.pack(side=LEFT, padx=(5, 5), pady=(5, 3))