def __init__(self, boss, personnage, numero): LabelFrame.__init__(self, boss, text=personnage.type) self.pv = Label(self) self.pv.pack() self.atk = Label(self) self.atk.pack() self.deff = Label(self) self.deff.pack() self.critChc = Label(self) self.critChc.pack() Button(self, text='Choisir', command=self.choisir).pack() self.personnage = personnage self.maj()
def __init__(self, boss): #Magasin d'améliorations (cadre) LabelFrame.__init__(self, boss, text='Magasin') frameAmel = LabelFrame(self, text='Amelioration') frameAmel.pack(side='left') #Cadre objets frameObjets = LabelFrame(self, text='Objets') frameObjets.pack(side='right') #Statistiques possibles pour les améliorations (contenu) #listeStat = [[nom, nomAmel, max, prix par niveau, icone]] listeStat = [['Points de vie', 'pv', 50, 75, 5, 'pv'], ['Dégats', 'atk', 75, 75, 5, 'atk'], ['Mana', 'mana', 50, 50, 5, 'mana'], ['Armure (%)', 'deff', 25, 15, 1, 'deff'], ['Dégats critiques (%)', 'critDmg', 20, 50, 5, 'critDmg'], ['Chance de critique (%)', 'critChc', 10, 40, 5, 'critChc'], ["Multiplicateur d'or (%)", 'multOR', 20, 100, 10, 'multOR']] chargerImages() for i in range(len(listeStat)): Amel(frameAmel, listeStat[i][0], listeStat[i][1], listeStat[i][2], listeStat[i][3], listeStat[i][4], listeStat[i][5]).pack(fill=X) #Magasin d'objets (contenu) self.listComboBox = [] for typ in range(len(listdir('Objets'))): Label(frameObjets, text=listdir('Objets')[typ]).pack() self.listComboBox.append(ComboboxObjet(frameObjets, listdir('Objets')[typ])) self.listComboBox[typ].pack()
def create_monitor(self): self.monitor_frame = LabelFrame(self, text="Monitor and Transport") this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL, from_=1, to=16, resolution=1) this_cycle.disable, this_cycle.enable = (None, None) this_cycle.ref = 'cycle_pos' this_cycle.grid(column=0, row=0, sticky=E + W) self.updateButton = Button(self.monitor_frame, text='Reload all Settings', command=self.request_update) self.updateButton.grid(row=1, sticky=E + W) self.ForceCaesuraButton = Button(self.monitor_frame, text='Force Caesura', command=self.force_caesura) self.ForceCaesuraButton.grid(row=2, sticky=E + W) self.saveBehaviourButton = Button(self.monitor_frame, text='Save current behaviour', command=self.request_saving_behaviour) self.saveBehaviourButton.grid(row=3, sticky=E + W) self.saveBehaviourNameEntry = Entry(self.monitor_frame) self.saveBehaviourNameEntry.grid(row=4, sticky=E + W) self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour) self.selected_behaviour = StringVar() self.selected_behaviour.trace('w', self.new_behaviour_chosen) self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, None,) self.savedBehavioursMenu.grid(row=5, sticky=E + W) self.monitor_frame.grid(column=0, row=10, sticky=E + W)
class Menu(Tk): def __init__(self): global FMagasin Tk.__init__(self) self.title('Donjon & Python') self.magasin = Magasin.Magasin(self) self.magasin.grid(row=0, column=0) Button(self, text='Jouer', command=self.play, height=2, width=20).grid(row=1, column=1) Button(self,text='Options', command=__main__.ouvrirOption, height=2, width=9).grid(row=1, column=2) self.framePerso = LabelFrame(self, text='Selection du personnage', width=30) self.framePerso.grid(row=0, column=1, columnspan=2) self.OR = Label(self, background='Yellow', height=2, width=70) self.OR.grid(row=1, column=0) self.majOR() self.remplirFramePerso() def run(self): Audio.playMusic('Rogue Legacy - Castle', -1) self.majPerso() self.mainloop() Sauvegarde.sauvegarder(__main__.savePath) def majPerso(self): for i in range(3): self.listeBox[i].maj() def majOR(self): self.OR.config(text="Pièce d'or : " + str(Magasin.OR)) def remplirFramePerso(self): listePerso = GenerationPersonnage.genererPerso() self.listeBox = [] for i in range(len(listePerso)): self.listeBox.append(BoxPerso(self.framePerso, listePerso[i], i)) self.listeBox[i].pack() def play(self): if __main__.perso: Sauvegarde.sauvegarder(__main__.savePath) self.destroy() __main__.motGraph = MoteurGraphique() # try: #Les thread entrainent parfois des problèmes d'inconsistance dans pygame __main__.motGraph.run() __main__.motGraph = None
def __init__(self, boss, nom, amelioration, maximum, prix, up, logo): """ amelioration (str) : Nom de l'amélioration du bouton maximum (int) : Maximum de fois que l'on peut augmenter l'amélioration prix (int) : Prix de l'amélioration par niveau up (int) : Montant de point apporté par l'amélioration """ global imagesMag self.amel = amelioration self.max = maximum self.prix = prix self.up = up LabelFrame.__init__(self, boss) Label(self, image=imagesMag[logo]).pack(side=LEFT) Label(self, text=nom, width=18).pack(side=LEFT) self.button = Button(self, command=self.acheter, width = 6) self.level = Label(self, width=5) self.total = Label(self, width=11) self.total.pack(side=RIGHT) self.level.pack(side=RIGHT) self.button.pack(side=RIGHT) self.maj()
def __init__(self): global FMagasin Tk.__init__(self) self.title('Donjon & Python') self.magasin = Magasin.Magasin(self) self.magasin.grid(row=0, column=0) Button(self, text='Jouer', command=self.play, height=2, width=20).grid(row=1, column=1) Button(self,text='Options', command=__main__.ouvrirOption, height=2, width=9).grid(row=1, column=2) self.framePerso = LabelFrame(self, text='Selection du personnage', width=30) self.framePerso.grid(row=0, column=1, columnspan=2) self.OR = Label(self, background='Yellow', height=2, width=70) self.OR.grid(row=1, column=0) self.majOR() self.remplirFramePerso()
def get_this_tag_list(self): if hasattr(self, "taglist"): self.taglist.destroy() self.taglist = LabelFrame(self.t) self.taglist.pack() # Get existing tags try: existing_tags = [Button(self.taglist, text=tag, background="yellow", command=lambda: self.delete_existing_tag(tag, self.sel_index)) for tag in self.file.get_tags_by_index(self.sel_index)] for tag in existing_tags: tag.pack() except TypeError: # Greeting, if no tags are present print("No tags in this index")
def __init__(self, master): # Initialize the Frame object. super().__init__(master) # Create every opening widget. self.intro = Label(self, text=self.PROMPT) self.group = LabelFrame(self, text='Filename') self.entry = Entry(self.group, width=35) self.click = Button(self.group, text='Browse ...', command=self.file) self.enter = Button(self, text='Continue', command=self.start) # Make Windows entry bindings. def select_all(event): event.widget.selection_range(0, tkinter.END) return 'break' self.entry.bind('<Control-Key-a>', select_all) self.entry.bind('<Control-Key-/>', lambda event: 'break') # Position them in this frame. options = {'sticky': tkinter.NSEW, 'padx': 5, 'pady': 5} self.intro.grid(row=0, column=0, **options) self.group.grid(row=1, column=0, **options) self.entry.grid(row=0, column=0, **options) self.click.grid(row=0, column=1, **options) self.enter.grid(row=2, column=0, **options)
def create_check_buttons(self): self.cb_frame = LabelFrame(self, text="Global Settings") for cb in CHECK_BUTTONS: label = cb target_parent = self.cb_frame if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()): target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame']) setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and CHECK_BUTTONS[cb]['val'] or CHECK_BUTTONS[cb])) self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and 'disable' in list(CHECK_BUTTONS[cb].keys())) self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children())) self.this_cb.ref = cb for but in GLOBAL_BUTTONS: label = but ele = GLOBAL_BUTTONS[but] this_but = Button(self.cb_frame, text=but) this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler'])) this_but.ref = but this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children())) self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N)
class DownloaderApp(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("Youtube to MP3 GUI") self.pack() self.create_widgets() def create_widgets(self): # menu bar widgets self.menu = Menu(self.master) self.filemenu = Menu(self.menu, tearoff=0) self.filemenu.add_command(label="Help", command=self.helper) self.filemenu.add_command(label="Exit", command=self.master.quit) self.menu.add_cascade(label="File", menu=self.filemenu) self.about = Menu(self.menu, tearoff=0) self.about.add_command(label="Version 2") self.about.add_command(label="About...", command=self.aboutwindow) self.menu.add_cascade(label="About", menu=self.about) # string vars self.url = StringVar() self.message = StringVar() self.artist = StringVar() self.album = StringVar() self.art = None self.art_text = StringVar() # organizing frames self.frame1 = Frame(self.master) self.frame1.pack(side="bottom", fill="both", expand=True) self.frame2 = Frame(self.master) self.frame2.pack(side="top", fill="both", expand=True) self.frame3 = LabelFrame(self.frame1) self.frame3.pack(padx=5, pady=3) # user input widget self.url_label = Label(self.frame3, text="URL:").grid(row=0, column=0) self.url_entry = Entry(self.frame3, width=40, textvariable=self.url).grid(row=0, column=1) self.artist_label = Label(self.frame3, text="Artist:").grid(row=1, column=0) self.artist_entry = Entry(self.frame3, width=40, textvariable=self.artist).grid(row=1, column=1) self.album_label = Label(self.frame3, text="Album:").grid(row=2, column=0) self.album_entry = Entry(self.frame3, width=40, textvariable=self.album).grid(row=2, column=1) # choose album art widgets self.art_button = Button(self.frame3, text="Choose Album Art", command=self.getArt).grid(row=3, column=0) self.art_label = Label(self.frame3, textvariable=self.art_text).grid(row=3, column=1) # padding around each user input widget for child in self.frame3.winfo_children(): child.grid_configure(padx=5, pady=3) # status bar widget; added before download to sticky to bottom first self.statusbar = Label(self.frame1, textvariable=self.message, bd=1, relief="sunken", anchor="w") self.statusbar.pack(side="bottom", fill="x") # download button widget self.download_button = Button(self.frame2, text="Download", command=self.download) self.download_button.pack(side="bottom", padx=5, pady=3) self.master.bind('<Return>', self.download) self.master.config(menu=self.menu) def download(self, *args): #### change the direction of slashes for Windows ### self.folder = str(Path.home()) + '/Desktop/NewMusic' request = str(self.url.get()) self.artist_text = str(self.artist.get()) self.album_text = str(self.album.get()) if request != EMPTY: try: if path.isdir(self.folder) != True: mkdir(self.folder) else: self.remove_temp() mkdir(self.folder) output = self.folder + '/%(title)s.%(ext)s' ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': output, 'progress_hooks': [self.my_hook], 'quiet': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192' }] } with YoutubeDL(ydl_opts) as ydl: ydl.download([request]) self.add_meta() self.itunes_import() self.remove_temp() if self.art != None: remove(self.art) self.url.set(EMPTY) self.artist.set(EMPTY) self.album.set(EMPTY) self.art_text.set(EMPTY) self.master.update() except DownloadError: self.remove_temp() string = self.url.get() string = "Download Error..." + string + " is not a valid URL." self.message.set(string) self.url.set(EMPTY) self.master.update() def my_hook(self, d): if d['status'] == 'downloading': string = 'Downloading.....' + d['_percent_str'] self.message.set(string) self.master.update() elif d['status'] == 'finished': string = 'Download Complete....' self.message.set(string) self.master.update() else: pass def getArt(self): # get rid of tilde for WINDOWS self.art = filedialog.askopenfilename( initialdir="~/Desktop", title="Select Image", filetypes=(("jpeg files", "*.jpg"), ("jpeg files", "*.jpeg"))) self.art_text.set(self.art) def itunes_import(self): if path.isdir(ITUNES) == True: if path.isdir(self.folder) == True: for file in listdir(self.folder): #removes unwanted title strings before move #doesnt work right might need to eyed3 title of file # still doesnt work with path rename # need to idv3 the title x = self.artist_text + " - " y = "(Offical Video)" newname = sub(x, EMPTY, file) newname = sub(y, EMPTY, newname) file_path = self.folder + "/" + file new_path = self.folder + "/" + newname rename(file_path, new_path) import_path = ITUNES + '/' + file move(new_path, import_path) def remove_temp(self): if path.isdir(self.folder) == True: for file in listdir(self.folder): file_path = self.folder + "/" + file remove(file_path) rmdir(self.folder) def add_meta(self): #test artist and album tags with mutagen if self.artist != EMPTY: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = eyed3.load(file_path) audiofile.tag.artist = self.artist_text audiofile.tag.save() if self.album != EMPTY: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = eyed3.load(file_path) audiofile.tag.album = self.album_text audiofile.tag.save() if self.art != None: for file in listdir(self.folder): file_path = self.folder + "/" + file audiofile = MP3(file_path, ID3=ID3) audiofile.tags.add( APIC(mime='image/jpeg', type=3, desc=u'Cover', data=open(self.art, 'rb').read())) audiofile.save() def helper(self): HELP_TEXT = """ In the case of Errors or Failed Download: - Download Location: - downloads are save the iTunes Automatic Import folder - if the song is not in your itunes then the download failed - Check video URL: - navigate directly to video/playlist and copy url from the web browser - make sure you are not signed into Youtube Premium premium videos are unsupported """ toplevel = Toplevel() label1 = Label(toplevel, text=HELP_TEXT, height=0, width=100, justify='left') label1.pack() def aboutwindow(self): ABOUT = """About""" ABOUT_TEXT = """ Youtube to MP3 Downloader is a GUI interface that allows users to download high quality albums from Youtube and other music hosting sites directly to the users desktop. For a full list of support sites visit:""" SITES = "http://ytdl-org" DISCLAIMER = """ Disclaimer""" DISCLAIMER_TEXT = """ Youtube to MP3 Downloader was created using Python 3 and youtube-dl, an open sourced command line tool. This software is protected by the GNU General Public License and as such can be shared freely. """ WARNING = """******* This software comes with no guarantee. Use at your own risk. ******* Copyright 2011-2020 youtube-dl developers """ toplevel = Toplevel() label0 = Label(toplevel, text=ABOUT, height=0, width=100) label0.pack() label1 = Label(toplevel, text=ABOUT_TEXT, height=0, width=100, justify="left") label1.pack() label2 = Label(toplevel, text=SITES, fg="blue", cursor="hand2", height=0, width=100) label2.pack() label3 = Label(toplevel, text=DISCLAIMER, height=0, width=100) label3.pack() label4 = Label(toplevel, text=DISCLAIMER_TEXT, height=0, width=100, justify="left") label4.pack() label5 = Label(toplevel, text=WARNING, height=0, width=100) label5.pack()
def __init__(self, master): ##### Configure Canvas ##### Frame.__init__(self, master) self.master = master self.canvas = Canvas(master, borderwidth=0) self.frame = Frame(self.canvas) self.canvas.create_window((4,4), window=self.frame, anchor='nw', tags='self.frame') self.master.title('Born Digital Accessioner 1.0') self.initmenu() self.frame.config(bg='gainsboro', highlightthickness=0) self.canvas.config(bg='gainsboro', highlightthickness=0) self.canvas.grid_rowconfigure(0, weight=1) self.canvas.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.frame.grid_columnconfigure(0, weight=1) self.master.grid_rowconfigure(0, weight=1) self.master.grid_columnconfigure(0, weight=1) self.canvas.grid(row=0, column=0, sticky="nsew") self.frame.grid(row=0, column=0, sticky="nsew") ##### Execute login process by pressing Enter #### self.master.bind('<Return>', self.asloginprocess) ########### Step 1: Login to ArchivesSpace API ########### ## Set Step 1 Variable Inputs ## self.authenticate = StringVar() self.api_url = StringVar() self.username = StringVar() self.password = StringVar() self.login_confirmed = StringVar() ## Create Step 1 Widgets ## self.login_labelframe = LabelFrame(self.frame, text='Step 1: Connect to ArchivesSpace', font=('Arial', 14), bg='gainsboro', padx=1, pady=1) self.api_url_label = Label(self.login_labelframe, text='ArchivesSpace URL: ', font=('Arial', 13), bg='gainsboro') self.username_label = Label(self.login_labelframe, text='ArchivesSpace Username: '******'Arial', 13), bg='gainsboro') self.password_label = Label(self.login_labelframe, text='ArchivesSpace Password: '******'Arial', 13), bg='gainsboro') self.api_url_entry = Entry(self.login_labelframe, width=32, textvariable=self.api_url, highlightthickness=0) self.username_entry = Entry(self.login_labelframe, width=32, textvariable=self.username, highlightthickness=0) self.password_entry =Entry(self.login_labelframe, width=32, textvariable=self.password, show='*', highlightthickness=0) self.login_confirmed_variable = Label(self.login_labelframe, textvariable=self.login_confirmed, width=25, font=('Arial', 13), bg='gainsboro', highlightthickness=0, anchor='e') self.connect_button = Button(self.login_labelframe, text='Connect!',command=self.asloginprocess, width=10, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Set Step 1 Widget Layout ## self.login_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.login_labelframe.grid_rowconfigure(0, weight=1) self.login_labelframe.grid_columnconfigure(0, weight=1) self.api_url_label.grid(column=0, row=2, sticky="nw") self.api_url_entry.grid(column=0, row=3, sticky="nw") self.username_label.grid(column=0, row=4, sticky="nw") self.username_entry.grid(column=0, row=5, sticky="nw") self.password_label.grid(column=0, row=6, sticky="nw") self.password_entry.grid(column=0, row=7, sticky="nw") self.login_confirmed_variable.grid(column=1, row=6, sticky="ns") self.connect_button.grid(column=1, row=7, sticky="ne") ########### Step 2: Select Input CSV ########### ## Set Step 2 Variable Inputs ## self.csv_filename = StringVar() ## Create Step 2 Widgets ## self.fileselect_labelframe = LabelFrame(self.frame, text='Step 2: Select Input CSV', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.file_selected_label = Label(self.fileselect_labelframe, text='Selection: ', font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.selected_csv_variable = Label(self.fileselect_labelframe, textvariable=self.csv_filename, width=65, font=('Arial', 11), anchor='w', bg='gainsboro', highlightthickness=0) self.input_csv_button = Button(self.fileselect_labelframe, text='Select File', command=self.csvbutton, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 2 Layout ## self.fileselect_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.fileselect_labelframe.grid_rowconfigure(0, weight=1) self.fileselect_labelframe.grid_columnconfigure(0, weight=1) self.input_csv_button.grid(column=1, row=9, sticky='se') self.file_selected_label.grid(column=0, columnspan=1, row=10, sticky='w') self.selected_csv_variable.grid(column=0, row=11, columnspan=2, sticky='w') ## Set Step _ Variable Inputs ## self.csv_output = StringVar() ########### Step 3: Choose an Action ########### ## Create Step 3 Widgets ## self.action_labelframe = LabelFrame(self.frame, text='Step 3: Choose Action', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.create_components_button = Button(self.action_labelframe, text='Create records', width=30, command=self.run_create_script, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.update_components_button = Button(self.action_labelframe, text='Update records', width=30, command=self.run_update_script, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 3 Layout ## self.action_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.action_labelframe.grid_rowconfigure(0, weight=1) self.action_labelframe.grid_columnconfigure(0, weight=1) self.create_components_button.grid(row=12, columnspan=2) self.update_components_button.grid(row=13, columnspan=2) ########### Step 4: Review Output ########### ## Set Step 4 Variable Inputs ## self.update_attempts = StringVar() self.updates_success = StringVar() self.elapsed_time = StringVar() self.log_file = StringVar() self.error_dialog = StringVar() self.script_status = StringVar() self.parent_id = StringVar() self.resource_id = StringVar() self.repo_id_no = StringVar() ## Create Step 4 Widgets ## self.output_labelframe = LabelFrame(self.frame, text='Step 4: Review Output', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.script_status_variable = Label(self.output_labelframe, textvariable=self.script_status, font=('Arial', 13), anchor='e', bg='gainsboro', highlightthickness=0) self.record_updates_attempted_label = Label(self.output_labelframe, text='Record updates attempted: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.record_updates_attempted_variable = Label(self.output_labelframe, textvariable=self.update_attempts, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.records_updated_successsfully_label = Label(self.output_labelframe, text='Records updated successfully: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.records_updated_successsfully_variable = Label(self.output_labelframe, textvariable=self.updates_success, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.elapsed_time_label = Label(self.output_labelframe, text='Elapsed time: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.elapsed_time_variable = Label(self.output_labelframe, textvariable=self.elapsed_time, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.view_output_file_button = Button(self.output_labelframe, text='Open Output File', command=self.opencsvoutput, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.view_error_log_button = Button(self.output_labelframe, text='Open Log', command=self.openerrorlog, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.view_url_button = Button(self.output_labelframe, text='Open in ArchivesSpace', command=self.openparent_record, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 5 Layout ## self.output_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.output_labelframe.grid_rowconfigure(0, weight=1) self.output_labelframe.grid_columnconfigure(0, weight=1) self.script_status_variable.grid(column=1, row=14, sticky='e') self.record_updates_attempted_label.grid(column=0, row=15) self.records_updated_successsfully_label.grid(column=0, row=16) self.elapsed_time_label.grid(column=0, row=17) self.record_updates_attempted_variable.grid(column=1, row=15, sticky='w') self.records_updated_successsfully_variable.grid(column=1, row=16, sticky='w') self.elapsed_time_variable.grid(column=1, row=17, sticky='w') self.view_output_file_button.grid(column=1, row=18, sticky="ne") self.view_error_log_button.grid(column=1, row=19, sticky="ne") self.view_url_button.grid(column=1, row=20, sticky="ne") ## Clear Inputs, Help Buttons self.clear_labelframe = LabelFrame(self.frame, text=None, bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.clear_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.clear_labelframe.grid_rowconfigure(0, weight=1) self.clear_labelframe.grid_columnconfigure(0, weight=1) self.clear_all_inputs_button = Button(self.clear_labelframe, text='Clear Inputs', command=self.clear_inputs, relief=RAISED, bd=1, padx=5, pady=5, highlightthickness=0, cursor="hand1") self.clear_all_inputs_button.grid(column=0, row=21) #Initiates error logging self.error_log()
def guiMain(settings=None): frames = {} mainWindow = Tk() mainWindow.wm_title("OoT Randomizer %s" % ESVersion) mainWindow.resizable(False, False) set_icon(mainWindow) notebook = ttk.Notebook(mainWindow) frames['rom_tab'] = ttk.Frame(notebook) frames['rules_tab'] = ttk.Frame(notebook) frames['logic_tab'] = ttk.Frame(notebook) frames['other_tab'] = ttk.Frame(notebook) frames['cosmetic_tab'] = ttk.Frame(notebook) frames['SFX_tab'] = ttk.Frame(notebook) frames['cosmetic_tab_left'] = Frame(frames['cosmetic_tab']) frames['cosmetic_tab_right'] = Frame(frames['cosmetic_tab']) notebook.add(frames['rom_tab'], text='ROM Options') notebook.add(frames['rules_tab'], text='Main Rules') notebook.add(frames['logic_tab'], text='Detailed Logic') notebook.add(frames['other_tab'], text='Other') notebook.add(frames['cosmetic_tab'], text='Cosmetic') notebook.add(frames['SFX_tab'], text='SFX') ####################### # Randomizer controls # ####################### # Hold the results of the user's decisions here guivars = {} widgets = {} presets = {} # Hierarchy ############ #Rules Tab frames['open'] = LabelFrame(frames['rules_tab'], text='Open', labelanchor=NW) frames['world'] = LabelFrame(frames['rules_tab'], text='World', labelanchor=NW) frames['shuffle'] = LabelFrame(frames['rules_tab'], text='Shuffle', labelanchor=NW) # Logic tab frames['checks'] = LabelFrame(frames['logic_tab'], text='Adult Trade Sequence', labelanchor=NW) frames['tricks'] = LabelFrame(frames['logic_tab'], text='Lens of Truth', labelanchor=NW) #Other Tab frames['convenience'] = LabelFrame(frames['other_tab'], text='Timesavers', labelanchor=NW) frames['other'] = LabelFrame(frames['other_tab'], text='Misc', labelanchor=NW) #Cosmetic tab frames['cosmetic'] = LabelFrame(frames['cosmetic_tab_left'], text='General', labelanchor=NW) frames['sword_trails']= LabelFrame(frames['cosmetic_tab_left'], text='Sword Trail Colors',labelanchor=NW) frames['ui_colors']= LabelFrame(frames['cosmetic_tab_left'], text='UI Colors', labelanchor=NW) frames['tunic_colors']= LabelFrame(frames['cosmetic_tab_right'], text='Tunic Colors', labelanchor=NW) frames['navi_colors']= LabelFrame(frames['cosmetic_tab_right'], text='Navi Colors', labelanchor=NW) frames['gauntlet_colors']= LabelFrame(frames['cosmetic_tab_right'], text='Gauntlet Colors', labelanchor=NW) #Cosmetic tab frames['sfx'] = LabelFrame(frames['SFX_tab'], text='General', labelanchor=NW) frames['menu_sfx'] = LabelFrame(frames['SFX_tab'], text='Menu', labelanchor=NW) frames['npc_sfx'] = LabelFrame(frames['SFX_tab'], text='NPC', labelanchor=NW) # Shared def toggle_widget(widget, enabled): widget_type = widget.winfo_class() if widget_type == 'Frame' or widget_type == 'TFrame' or widget_type == 'Labelframe': if widget_type == 'Labelframe': widget.configure(fg='Black'if enabled else 'Grey') for child in widget.winfo_children(): toggle_widget(child, enabled) else: if widget_type == 'TCombobox': widget.configure(state= 'readonly' if enabled else 'disabled') else: widget.configure(state= 'normal' if enabled else 'disabled') if widget_type == 'Scale': widget.configure(fg='Black'if enabled else 'Grey') def show_settings(*event): settings = guivars_to_settings(guivars) settings_string_var.set( settings.get_settings_string() ) # Update any dependencies for info in setting_infos: dep_met = settings.check_dependency(info.name) if info.name in widgets: toggle_widget(widgets[info.name], dep_met) if info.type == list: widgets[info.name].delete(0, END) widgets[info.name].insert(0, *guivars[info.name]) if info.type != list and info.name in guivars and guivars[info.name].get() == 'Custom Color': color = colorchooser.askcolor() if color == (None, None): color = ((0,0,0),'#000000') guivars[info.name].set('Custom (' + color[1] + ')') if info.type != list and info.name in guivars and guivars[info.name].get() == 'Custom Navi Color': innerColor = colorchooser.askcolor(title='Pick an Inner Core color.') if innerColor == (None, None): innerColor = ((0,0,0),'#000000') outerColor = colorchooser.askcolor(title='Pick an Outer Glow color.') if outerColor == (None, None): outerColor = ((0,0,0),'#000000') guivars[info.name].set('Custom (%s %s)' % (innerColor[1], outerColor[1])) update_generation_type() versionCheckFrame = Frame(frames['rom_tab']) versionCheckFrame.pack(side=BOTTOM, anchor=NW, fill=X) fileDialogFrame = Frame(frames['rom_tab']) romDialogFrame = Frame(fileDialogFrame) baseRomLabel = Label(romDialogFrame, text='Base ROM') guivars['rom'] = StringVar(value='') romEntry = Entry(romDialogFrame, textvariable=guivars['rom'], width=50) def RomSelect(): rom = filedialog.askopenfilename(filetypes=[("ROM Files", (".z64", ".n64")), ("All Files", "*")]) if rom != '': guivars['rom'].set(rom) romSelectButton = Button(romDialogFrame, text='Browse', command=RomSelect, width=10) baseRomLabel.pack(side=LEFT, padx=(34,0)) romEntry.pack(side=LEFT, padx=3) romSelectButton.pack(side=LEFT) romDialogFrame.pack() fileDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(5,1)) def output_dir_select(): rom = filedialog.askdirectory(initialdir = default_output_path(guivars['output_dir'].get())) if rom != '': guivars['output_dir'].set(rom) outputDialogFrame = Frame(frames['rom_tab']) outputDirLabel = Label(outputDialogFrame, text='Output Directory') guivars['output_dir'] = StringVar(value='') outputDirEntry = Entry(outputDialogFrame, textvariable=guivars['output_dir'], width=50) outputDirButton = Button(outputDialogFrame, text='Browse', command=output_dir_select, width=10) outputDirLabel.pack(side=LEFT, padx=(3,0)) outputDirEntry.pack(side=LEFT, padx=3) outputDirButton.pack(side=LEFT) outputDialogFrame.pack(side=TOP, anchor=W, pady=3) distFileDialogFrame = Frame(frames['rom_tab']) distFileLabel = Label(distFileDialogFrame, text='Distribution File') guivars['distribution_file'] = StringVar(value='') distFileEntry = Entry(distFileDialogFrame, textvariable=guivars['distribution_file'], width=50) def DistFileSelect(): distFile = filedialog.askopenfilename(filetypes=[("JSON Files", (".json")), ("All Files", "*")]) if distFile != '': guivars['distribution_file'].set(distFile) distFileSelectButton = Button(distFileDialogFrame, text='Browse', command=DistFileSelect, width=10) distFileLabel.pack(side=LEFT, padx=(9,0)) distFileEntry.pack(side=LEFT, padx=3) distFileSelectButton.pack(side=LEFT) distFileDialogFrame.pack(side=TOP, anchor=W, pady=3) countDialogFrame = Frame(frames['rom_tab']) countLabel = Label(countDialogFrame, text='Generation Count') guivars['count'] = StringVar() widgets['count'] = Spinbox(countDialogFrame, from_=1, to=100, textvariable=guivars['count'], width=3) def open_readme(): open_file('https://wiki.ootrandomizer.com/index.php?title=Main_Page') openReadmeButton = Button(countDialogFrame, text='Open Wiki Page', command=open_readme) openReadmeButton.pack(side=RIGHT, padx=5) def open_output(): open_file(default_output_path(guivars['output_dir'].get())) openOutputButton = Button(countDialogFrame, text='Open Output Directory', command=open_output) openOutputButton.pack(side=RIGHT, padx=5) countLabel.pack(side=LEFT) widgets['count'].pack(side=LEFT, padx=2) countDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(1,1)) # Build gui ############ for info in setting_infos: if 'group' in info.gui_params: if info.gui_params['widget'] == 'Checkbutton': # Determine the initial value of the checkbox default_value = 1 if info.choices[info.default] == 'checked' else 0 # Create a variable to access the box's state guivars[info.name] = IntVar(value=default_value) # Create the checkbox widgets[info.name] = Checkbutton(frames[info.gui_params['group']], text=info.gui_params['text'], variable=guivars[info.name], justify=LEFT, wraplength=220, command=show_settings) widgets[info.name].pack(expand=False, anchor=W) elif info.gui_params['widget'] == 'Combobox': # Create the variable to store the user's decision guivars[info.name] = StringVar(value=info.choices[info.default]) # Create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) dropdown = ttk.Combobox(widgets[info.name], textvariable=guivars[info.name], values=list(map(lambda choice: info.choices[choice], info.choice_list)), state='readonly', width=36) dropdown.bind("<<ComboboxSelected>>", show_settings) dropdown.pack(side=BOTTOM, anchor=W) # Label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # Pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Radiobutton': # Create the variable to store the user's decision guivars[info.name] = StringVar(value=info.choices[info.default]) # Create the option menu widgets[info.name] = LabelFrame(frames[info.gui_params['group']], text=info.gui_params.get('text', info.name), labelanchor=NW) # Setup orientation side = TOP anchor = W if "horizontal" in info.gui_params and info.gui_params["horizontal"]: side = LEFT anchor = N # Add the radio buttons for option in map(lambda choice: info.choices[choice], info.choice_list): radio_button = Radiobutton(widgets[info.name], text=option, value=option, variable=guivars[info.name], justify=LEFT, wraplength=220, indicatoron=False, command=show_settings) radio_button.pack(expand=True, side=side, anchor=anchor) # Pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Scale': # Create the variable to store the user's decision guivars[info.name] = IntVar(value=info.choices[info.default]) # Create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) minval = info.gui_params.get('min', 0) maxval = info.gui_params.get('max', 100) stepval = info.gui_params.get('step', 1) scale = Scale(widgets[info.name], variable=guivars[info.name], from_=minval, to=maxval, tickinterval=stepval, resolution=stepval, showvalue=0, orient=HORIZONTAL, sliderlength=15, length=235, command=show_settings) scale.pack(side=BOTTOM, anchor=W) # Label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # Pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'Entry': # Create the variable to store the user's decision guivars[info.name] = StringVar(value=info.default) # Create the option menu widgets[info.name] = Frame(frames[info.gui_params['group']]) if 'validate' in info.gui_params: entry = ValidatingEntry(widgets[info.name], command=show_settings, validate=info.gui_params['validate'], textvariable=guivars[info.name], width=35) else: entry = Entry(widgets[info.name], textvariable=guivars[info.name], width=36) entry.pack(side=BOTTOM, anchor=W) # Label the option if 'text' in info.gui_params: label = Label(widgets[info.name], text=info.gui_params['text']) label.pack(side=LEFT, anchor=W, padx=5) # Pack the frame widgets[info.name].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) elif info.gui_params['widget'] == 'SearchBox' or info.gui_params['widget'] == 'FilteredSearchBox': filtered = (info.gui_params['widget'] == 'FilteredSearchBox') search_frame = LabelFrame(frames[info.gui_params['group']], text=info.gui_params.get('text', info.name), labelanchor=NW) if filtered: filter_frame = Frame(search_frame) widgets[info.name + '_filterlabel'] = Label(filter_frame, text="Filter: ") widgets[info.name + '_filterlabel'].pack(side=LEFT, anchor=W) widgets[info.name + '_entry'] = SearchBox(search_frame, list(map(lambda choice: info.choices[choice], info.choice_list)), width=78) widgets[info.name + '_filter'] = SearchBoxFilterControl(filter_frame, widgets[info.name + '_entry'], info.gui_params['filterdata'], width=50) widgets[info.name + '_filter'].pack(expand=False, side=LEFT, anchor=W) filter_frame.pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) widgets[info.name + '_entry'].pack(expand=False, side=TOP, anchor=W) else: widgets[info.name + '_entry'] = SearchBox(search_frame, list(map(lambda choice: info.choices[choice], info.choice_list)), width=78) widgets[info.name + '_entry'].pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) list_frame = Frame(search_frame) scrollbar = Scrollbar(list_frame, orient=VERTICAL) widgets[info.name] = Listbox(list_frame, width=78, height=7, yscrollcommand=scrollbar.set) guivars[info.name] = list(info.default) scrollbar.config(command=widgets[info.name].yview) scrollbar.pack(side=RIGHT, fill=Y) widgets[info.name].pack(side=LEFT) list_frame.pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) if 'entry_tooltip' in info.gui_params: ToolTips.register(widgets[info.name + '_entry'], info.gui_params['entry_tooltip']) if filtered: ToolTips.register(widgets[info.name + '_filter'], info.gui_params['entry_tooltip']) if 'list_tooltip' in info.gui_params: ToolTips.register(widgets[info.name], info.gui_params['list_tooltip']) def get_lambda(function, *args): return lambda: function(*args) def add_list_selected(name): new_location = widgets[name +'_entry'].get() if new_location in widgets[name +'_entry'].options and new_location not in widgets[name].get(0, END): widgets[name].insert(END, new_location) guivars[name].append(new_location) show_settings() def remove_list_selected(name): location = widgets[name].get(ACTIVE) widgets[name].delete(ACTIVE) guivars[name].remove(location) show_settings() def add_list_all(name): for new_location in widgets[name + '_entry'].options: if new_location not in widgets[name].get(0, END): widgets[name].insert(END, new_location) guivars[name].append(new_location) show_settings() def remove_list_all(name): items = list(widgets[name].get(0, END)) widgets[name].delete(0, END) guivars[name] = [] for item in (x for x in items if x not in widgets[name + '_entry'].options): widgets[name].insert(END, item) guivars[name].append(item) show_settings() def clear_list_all(name): widgets[name].delete(0, END) guivars[name] = [] show_settings() list_button_frame = Frame(search_frame) list_add = Button(list_button_frame, width=10, text='Add', command=get_lambda(add_list_selected, info.name)) list_add.pack(side=LEFT, anchor=N, padx=3, pady=3) list_remove = Button(list_button_frame, width=10, text='Remove', command=get_lambda(remove_list_selected, info.name)) list_remove.pack(side=LEFT, anchor=N, padx=3, pady=3) list_add = Button(list_button_frame, width=10, text='All', command=get_lambda(add_list_all, info.name)) list_add.pack(side=LEFT, anchor=N, padx=3, pady=3) list_remove = Button(list_button_frame, width=10, text='None', command=get_lambda(remove_list_all, info.name)) list_remove.pack(side=LEFT, anchor=N, padx=3, pady=3) if filtered: list_clear = Button(list_button_frame, width=10, text='Clear', command=get_lambda(clear_list_all, info.name)) list_clear.pack(side=LEFT, anchor=N, padx=3, pady=3) list_button_frame.pack(expand=False, side=TOP, padx=3, pady=3) # pack the frame search_frame.pack(expand=False, side=TOP, anchor=W, padx=3, pady=3) if 'tooltip' in info.gui_params: ToolTips.register(widgets[info.name], info.gui_params['tooltip']) # Pack the hierarchy frames['shuffle'].pack(fill=BOTH, expand=True, anchor=N, side=RIGHT, pady=(5,1)) frames['open'].pack( fill=BOTH, expand=True, anchor=W, side=TOP, pady=(5,1)) frames['world'].pack( fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5,1)) # Logic tab frames['checks'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1)) frames['tricks'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1)) # Other Tab frames['convenience'].pack(fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1)) frames['other'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1)) # Cosmetics tab frames['cosmetic'].pack( fill=BOTH, expand=True, anchor=W, side=TOP) frames['cosmetic_tab_left'].pack( fill=BOTH, expand=True, anchor=W, side=LEFT) frames['cosmetic_tab_right'].pack(fill=BOTH, expand=True, anchor=W, side=RIGHT) # Cosmetics tab - Left Side frames['sword_trails'].pack( fill=BOTH, expand=True, anchor=W, side=TOP) frames['ui_colors'].pack( fill=BOTH, expand=True, anchor=W, side=BOTTOM) # Cosmetics tab - Right Side frames['tunic_colors'].pack(fill=BOTH, expand=True, anchor=N, side=TOP) frames['navi_colors'].pack( fill=BOTH, expand=True, anchor=W, side=TOP) frames['gauntlet_colors'].pack(fill=BOTH, expand=True, anchor=W, side=BOTTOM) #SFX tab frames['sfx'].pack( fill=BOTH, expand=True, anchor=N, side=LEFT, pady=(5,1)) frames['menu_sfx'].pack( fill=BOTH, expand=False, anchor=W, side=TOP, pady=(5,1)) frames['npc_sfx'].pack(fill=BOTH, expand=True, anchor=W, side=BOTTOM, pady=(5,1)) notebook.pack(fill=BOTH, expand=True, padx=5, pady=5) #Multi-World widgets['multiworld'] = LabelFrame(frames['rom_tab'], text='Multi-World Generation') countLabel = Label( widgets['multiworld'], wraplength=250, justify=LEFT, text='''This is used for co-op generations. \ Increasing Player Count will drastically \ increase the generation time. \ \nFor more information, see: \ ''' ) hyperLabel = Label(widgets['multiworld'], wraplength=250, justify=LEFT, text='https://github.com/TestRunnerSRL/\nbizhawk-co-op\n', fg='blue', cursor='hand2') hyperLabel.bind("<Button-1>", lambda event: webbrowser.open_new(r"https://github.com/TestRunnerSRL/bizhawk-co-op")) countLabel.pack(side=TOP, anchor=W, padx=5, pady=0) hyperLabel.pack(side=TOP, anchor=W, padx=5, pady=0) worldCountFrame = Frame(widgets['multiworld']) countLabel = Label(worldCountFrame, text='Player Count') guivars['world_count'] = StringVar() widgets['world_count'] = Spinbox(worldCountFrame, from_=1, to=255, textvariable=guivars['world_count'], width=3) guivars['world_count'].trace('w', show_settings) countLabel.pack(side=LEFT) widgets['world_count'].pack(side=LEFT, padx=2) worldCountFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1,5)) playerNumFrame = Frame(widgets['multiworld']) countLabel = Label(playerNumFrame, text='Player ID') guivars['player_num'] = StringVar() widgets['player_num'] = Spinbox(playerNumFrame, from_=1, to=255, textvariable=guivars['player_num'], width=3) countLabel.pack(side=LEFT) widgets['player_num'].pack(side=LEFT, padx=2) ToolTips.register(widgets['player_num'], 'Generate for specific Player.') playerNumFrame.pack(side=LEFT, anchor=N, padx=10, pady=(1,5)) widgets['multiworld'].pack(side=LEFT, fill=BOTH, anchor=NW, padx=5, pady=5) # Settings Presets Functions def import_setting_preset(): if guivars['settings_preset'].get() == '[New Preset]': messagebox.showerror("Invalid Preset", "You must select an existing preset!") return # Get cosmetic settings old_settings = guivars_to_settings(guivars) new_settings = {setting.name: old_settings.__dict__[setting.name] for setting in filter(lambda s: not (s.shared and s.bitwidth > 0), setting_infos)} preset = presets[guivars['settings_preset'].get()] new_settings.update(preset) settings = Settings(new_settings) settings.seed = guivars['seed'].get() settings_to_guivars(settings, guivars) show_settings() def add_settings_preset(): preset_name = guivars['settings_preset'].get() if preset_name == '[New Preset]': preset_name = simpledialog.askstring("New Preset", "Enter a new preset name:") if not preset_name or preset_name in presets or preset_name == '[New Preset]': messagebox.showerror("Invalid Preset", "You must enter a new preset name!") return elif presets[preset_name].get('locked', False): messagebox.showerror("Invalid Preset", "You cannot modify a locked preset!") return else: if messagebox.askquestion("Overwrite Preset", 'Are you sure you want to overwrite the "%s" preset?' % preset_name) != 'yes': return settings = guivars_to_settings(guivars) preset = {setting.name: settings.__dict__[setting.name] for setting in filter(lambda s: s.shared and s.bitwidth > 0, setting_infos)} presets[preset_name] = preset guivars['settings_preset'].set(preset_name) update_preset_dropdown() save_presets() def remove_setting_preset(): preset_name = guivars['settings_preset'].get() if preset_name == '[New Preset]': messagebox.showerror("Invalid Preset", "You must select an existing preset!") return elif presets[preset_name].get('locked', False): messagebox.showerror("Invalid Preset", "You cannot modify a locked preset!") return confirm = messagebox.askquestion('Remove Setting Preset', 'Are you sure you want to remove the setting preset "%s"?' % preset_name) if confirm != 'yes': return del presets[preset_name] guivars['settings_preset'].set('[New Preset]') update_preset_dropdown() save_presets() def update_preset_dropdown(): widgets['settings_preset']['values'] = ['[New Preset]'] + list(presets.keys()) def save_presets(): presets_file = local_path('presets.sav') with open(presets_file, 'w') as outfile: preset_json = {name: preset for name,preset in presets.items() if not preset.get('locked')} json.dump(preset_json, outfile, indent=4) # Settings Presets widgets['settings_presets'] = LabelFrame(frames['rom_tab'], text='Settings Presets') countLabel = Label( widgets['settings_presets'], wraplength=250, justify=LEFT, text='''Presets are settings that can be saved\ and loaded from. Loading a preset\ will overwrite all settings that affect\ the seed.\ \n\ ''' ) countLabel.pack(side=TOP, anchor=W, padx=5, pady=0) selectPresetFrame = Frame(widgets['settings_presets']) guivars['settings_preset'] = StringVar(value='[New Preset]') widgets['settings_preset'] = ttk.Combobox(selectPresetFrame, textvariable=guivars['settings_preset'], values=['[New Preset]'], state='readonly', width=33) widgets['settings_preset'].pack(side=BOTTOM, anchor=W) ToolTips.register(widgets['settings_preset'], 'Select a setting preset to apply.') widgets['settings_preset'].pack(side=LEFT, padx=(5, 0)) selectPresetFrame.pack(side=TOP, anchor=W, padx=5, pady=(1,5)) buttonPresetFrame = Frame(widgets['settings_presets']) importPresetButton = Button(buttonPresetFrame, text='Load', width=9, command=import_setting_preset) addPresetButton = Button(buttonPresetFrame, text='Save', width=9, command=add_settings_preset) removePresetButton = Button(buttonPresetFrame, text='Remove', width=9, command=remove_setting_preset) importPresetButton.pack(side=LEFT, anchor=W, padx=2) addPresetButton.pack(side=LEFT, anchor=W, padx=2) removePresetButton.pack(side=LEFT, anchor=W, padx=2) buttonPresetFrame.pack(side=TOP, anchor=W, padx=5, pady=(1,5)) widgets['settings_presets'].pack(side=RIGHT, fill=BOTH, anchor=NW, padx=5, pady=5) # Create the generation menu def update_generation_type(event=None): settings = guivars_to_settings(guivars) if generation_notebook.tab(generation_notebook.select())['text'] == 'Generate From Seed': notebook.tab(1, state="normal") if guivars['logic_rules'].get() == 'Glitchless': notebook.tab(2, state="normal") else: notebook.tab(2, state="disabled") notebook.tab(3, state="normal") notebook.tab(4, state="normal") notebook.tab(5, state="normal") toggle_widget(widgets['world_count'], settings.check_dependency('world_count')) toggle_widget(widgets['create_spoiler'], settings.check_dependency('create_spoiler')) toggle_widget(widgets['count'], settings.check_dependency('count')) toggle_widget(widgets['settings_presets'], True) else: notebook.tab(1, state="disabled") notebook.tab(2, state="disabled") notebook.tab(3, state="disabled") if guivars['repatch_cosmetics'].get(): notebook.tab(4, state="normal") notebook.tab(5, state="normal") toggle_widget(widgets['create_cosmetics_log'], settings.check_dependency('create_cosmetics_log')) else: notebook.tab(4, state="disabled") notebook.tab(5, state="disabled") toggle_widget(widgets['create_cosmetics_log'], False) toggle_widget(widgets['world_count'], False) toggle_widget(widgets['create_spoiler'], False) toggle_widget(widgets['count'], False) toggle_widget(widgets['settings_presets'], False) generation_notebook = ttk.Notebook(mainWindow) frames['gen_from_seed'] = ttk.Frame(generation_notebook) frames['gen_from_file'] = ttk.Frame(generation_notebook) generation_notebook.add(frames['gen_from_seed'], text='Generate From Seed') generation_notebook.add(frames['gen_from_file'], text='Generate From File') generation_notebook.bind("<<NotebookTabChanged>>", show_settings) # From seed tab def import_settings(event=None): try: settings = guivars_to_settings(guivars) text = settings_string_var.get().upper() settings.seed = guivars['seed'].get() settings.update_with_settings_string(text) settings_to_guivars(settings, guivars) show_settings() except Exception as e: messagebox.showerror(title="Error", message="Invalid settings string") def copy_settings(event=None): mainWindow.clipboard_clear() new_clip = settings_string_var.get().upper() mainWindow.clipboard_append(new_clip) mainWindow.update() settingsFrame = Frame(frames['gen_from_seed']) settings_string_var = StringVar() widgets['setting_string'] = Entry(settingsFrame, textvariable=settings_string_var, width=44) label = Label(settingsFrame, text="Settings String", width=13, anchor=E) widgets['copy_settings'] = Button(settingsFrame, text='Copy', width=5, command=copy_settings) widgets['import_settings'] = Button(settingsFrame, text='Import', width=7, command=import_settings) label.pack(side=LEFT, anchor=W, padx=5) widgets['setting_string'].pack(side=LEFT, anchor=W) widgets['copy_settings'].pack(side=LEFT, anchor=W, padx=(5, 0)) widgets['import_settings'].pack(side=LEFT, anchor=W) settingsFrame.pack(fill=BOTH, anchor=W, padx=5, pady=(10,0)) def multiple_run(settings, window): orig_seed = settings.seed for i in range(settings.count): settings.update_seed(orig_seed + '-' + str(i)) window.update_title("Generating Seed %s...%d/%d" % (settings.seed, i+1, settings.count)) main(settings, window) def generateRom(): settings = guivars_to_settings(guivars) if settings.count: BackgroundTaskProgress(mainWindow, "Generating Seed %s..." % settings.seed, multiple_run, settings) else: BackgroundTaskProgress(mainWindow, "Generating Seed %s..." % settings.seed, main, settings) generateSeedFrame = Frame(frames['gen_from_seed']) seedLabel = Label(generateSeedFrame, text='Seed', width=13, anchor=E) generateButton = Button(generateSeedFrame, text='Generate!', width=14, command=generateRom) guivars['seed'] = StringVar() widgets['seed'] = Entry(generateSeedFrame, textvariable=guivars['seed'], width=44) seedLabel.pack(side=LEFT, padx=5) widgets['seed'].pack(side=LEFT) generateButton.pack(side=LEFT, padx=(5, 0)) generateSeedFrame.pack(side=BOTTOM, anchor=W, padx=5, pady=10) # From file tab patchDialogFrame = Frame(frames['gen_from_file']) patchFileLabel = Label(patchDialogFrame, text='Patch File') guivars['patch_file'] = StringVar(value='') patchEntry = Entry(patchDialogFrame, textvariable=guivars['patch_file'], width=52) def PatchSelect(): patch_file = filedialog.askopenfilename(filetypes=[("Patch File Archive", "*.zpfz *.zpf"), ("All Files", "*")]) if patch_file != '': guivars['patch_file'].set(patch_file) patchSelectButton = Button(patchDialogFrame, text='Select File', command=PatchSelect, width=14) patchFileLabel.pack(side=LEFT, padx=(5,0)) patchEntry.pack(side=LEFT, padx=3) patchSelectButton.pack(side=LEFT) patchDialogFrame.pack(side=TOP, anchor=W, padx=5, pady=(10,5)) def generateFromFile(): settings = guivars_to_settings(guivars) BackgroundTaskProgress(mainWindow, "Generating From File %s..." % os.path.basename(settings.patch_file), from_patch_file, settings) patchCosmeticsAndGenerateFrame = Frame(frames['gen_from_file']) guivars['repatch_cosmetics'] = IntVar() widgets['repatch_cosmetics'] = Checkbutton(patchCosmeticsAndGenerateFrame, text='Update Cosmetics', variable=guivars['repatch_cosmetics'], justify=LEFT, wraplength=220, command=show_settings) widgets['repatch_cosmetics'].pack(side=LEFT, padx=5, anchor=W) generateFileButton = Button(patchCosmeticsAndGenerateFrame, text='Generate!', width=14, command=generateFromFile) generateFileButton.pack(side=RIGHT, anchor=E) patchCosmeticsAndGenerateFrame.pack(side=BOTTOM, fill=BOTH, expand=True, pady=(0,10), padx=(0, 10)) generation_notebook.pack(fill=BOTH, expand=True, padx=5, pady=5) guivars['checked_version'] = StringVar() guivars['cosmetics_only'] = IntVar() if settings is not None: # Load values from commandline args settings_to_guivars(settings, guivars) else: # Try to load saved settings settingsFile = local_path('settings.sav') try: with open(settingsFile) as f: settings = Settings( json.load(f) ) except: settings = Settings({}) settings_to_guivars(settings, guivars) guivars['seed'].set("") presets = {} for file in [data_path('presets_default.json')] \ + [local_path(f) for f in os.listdir(local_path()) if f.startswith('presets_') and f.endswith('.sav')] \ + [local_path('presets.sav')]: try: with open(file) as f: presets_temp = json.load(f) if file != local_path('presets.sav'): for preset in presets_temp.values(): preset['locked'] = True presets.update(presets_temp) except: pass update_preset_dropdown() show_settings() def gui_check_version(): task = BackgroundTask(mainWindow, check_version, guivars['checked_version'].get()) while task.running: mainWindow.update() if task.status: versionCheckLabel = LabelFrame(versionCheckFrame, text="New Version Available!") versionCheckText = Label(versionCheckLabel, justify=LEFT, text=task.status[(task.status.find(' ')+1):]) versionCheckLink = Label(versionCheckLabel, justify=LEFT, text='Click here and download the current version.', fg='blue', cursor='hand2') versionCheckLink.bind("<Button-1>", lambda event: webbrowser.open_new(r"https://github.com/TestRunnerSRL/OoT-Randomizer/tree/Dev")) versionCheckText.pack(anchor=NW, padx=5, pady=0) versionCheckLink.pack(anchor=NW, padx=5, pady=0) versionCheckLabel.pack(anchor=NW, fill=X, expand="yes", padx=5, pady=5) mainWindow.after(1000, gui_check_version) mainWindow.mainloop() # Save settings on close settings_file = local_path('settings.sav') with open(settings_file, 'w') as outfile: settings = guivars_to_settings(guivars) del settings.__dict__["distribution"] del settings.__dict__["seed"] del settings.__dict__["numeric_seed"] del settings.__dict__["check_version"] if "locked" in settings.__dict__: del settings.__dict__["locked"] json.dump(settings.__dict__, outfile, indent=4) save_presets()
def openaboutwindow(main_root_title): global about_window # Defines the path to config.ini and opens it for reading/writing config_file = 'Runtime/config.ini' # Creates (if doesn't exist) and defines location of config.ini config = ConfigParser() config.read(config_file) try: # If "About" window is already opened, display a message, then close the "About" window if about_window.winfo_exists(): messagebox.showinfo( title=f'"{about_window.wm_title()}" Info!', parent=about_window, message= f'"{about_window.wm_title()}" is already opened, closing window instead' ) about_window.destroy() return except NameError: pass def about_exit_function(): # Exit function when hitting the 'X' button func_parser = ConfigParser() func_parser.read(config_file) if func_parser['save_window_locations'][ 'about'] == 'yes': # If auto save position on close is checked try: if func_parser['save_window_locations'][ 'about position'] != about_window.geometry(): func_parser.set('save_window_locations', 'about position', about_window.geometry()) with open(config_file, 'w') as configfile: func_parser.write(configfile) except (Exception, ): pass about_window.destroy() # Close window about_window = Toplevel() about_window.title('About') about_window.configure(background="#434547") if config['save_window_locations']['about position'] == '' or config[ 'save_window_locations']['about'] == 'no': window_height = 650 window_width = 720 screen_width = about_window.winfo_screenwidth() screen_height = about_window.winfo_screenheight() x_coordinate = int((screen_width / 2) - (window_width / 2)) y_coordinate = int((screen_height / 2) - (window_height / 2)) about_window.geometry("{}x{}+{}+{}".format(window_width, window_height, x_coordinate, y_coordinate)) elif config['save_window_locations']['about position'] != '' and config[ 'save_window_locations']['about'] == 'yes': about_window.geometry( config['save_window_locations']['about position']) about_window.resizable(False, False) about_window.protocol('WM_DELETE_WINDOW', about_exit_function) about_window.grid_columnconfigure(0, weight=1) detect_font = font.nametofont( "TkDefaultFont") # Get default font value into Font object set_font = detect_font.actual().get("family") about_information_frame = LabelFrame(about_window, text=' About ', labelanchor="nw") about_information_frame.grid(column=0, row=0, columnspan=1, padx=5, pady=(0, 3), sticky=N + S + E + W) about_information_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold")) about_information_frame.grid_rowconfigure(0, weight=1) about_information_frame.grid_columnconfigure(0, weight=1) about_window_text = Text(about_information_frame, background="#434547", foreground="white", relief=FLAT, height=10) about_window_text.pack() about_window_text.insert(INSERT, f"{main_root_title}\n") about_window_text.insert(INSERT, "\n") about_window_text.insert( INSERT, "Development: jlw4049\n\nContributors: BassThatHertz, aaronrausch") about_window_text.insert(INSERT, "\n\n") about_window_text.insert( INSERT, "Power audio encoding GUI, that mostly uses FFMPEG at the heart. \n") about_window_text.configure(state=DISABLED) about_information_frame = LabelFrame(about_window, text=' License ', labelanchor="nw") about_information_frame.grid(column=0, row=1, columnspan=1, padx=5, pady=(0, 3), sticky=N + S + E + W) about_information_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold")) about_information_frame.grid_rowconfigure(0, weight=1) about_information_frame.grid_columnconfigure(0, weight=1) license_text = """ Copyright (c) 2012-2022 Scott Chacon and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ about_window_license = Text(about_information_frame, background="#434547", foreground="white", relief=FLAT) about_window_license.pack(anchor='center') about_window_license.insert(INSERT, license_text) about_window_license.configure(state=DISABLED)
class SNMPManager: def __init__(self, master=None): # setup tab objects self.master = master self.navigation_tabs = ttk.Notebook(self.master) self.setup = Frame(self.navigation_tabs) self.setup.pack() self.title_container = Frame(self.setup) self.title = Label(self.title_container, text="SNMP Manager") self.create_title() self.agent_container = Frame(self.setup) self.agent_label = Label(self.agent_container, text="Agent IP:", font=font, width=label_width) self.agent = Entry(self.agent_container) self.create_agent() self.community_container = Frame(self.setup) self.community_label = Label(self.community_container, text="Community:", font=font, width=label_width) self.community = Entry(self.community_container) self.create_community() self.object_container = Frame(self.setup) self.object_label = Label(self.object_container, text="Object instance:", font=font, width=label_width) self.object = Entry(self.object_container) self.create_object() self.time_container = Frame(self.setup) self.time_label = Label(self.time_container, text="Refresh time (s):", font=font, width=label_width) validation = self.time_container.register(only_numbers) self.time = Entry(self.time_container, validate="key", validatecommand=(validation, '%S')) self.create_charts = False self.create_time() self.buttons_container = Frame(self.setup) self.get_object = Button(self.buttons_container, text="Get Object", font=font, width=button_width) self.settings = Button(self.buttons_container, text="Settings", font=font, width=button_width) self.start_monitor = Button(self.buttons_container, text="Start monitor", font=font, width=button_width) self.stop_monitor = Button(self.buttons_container, text="Stop monitor", font=font, width=button_width) self.create_setup_buttons() # results frames self.result_tabs = ttk.Notebook(self.setup) self.response_label_frame = LabelFrame(self.result_tabs, font=font) self.response_value = StringVar(self.response_label_frame) self.response_text = Text(self.response_label_frame, font=font) self.warning_label_frame = LabelFrame(self.result_tabs, font=font) self.warning_value = StringVar(self.warning_label_frame) self.warning_text = Text(self.warning_label_frame, font=font) self.create_result() # charts objects self.link_chart = Frame(self.navigation_tabs) self.ip_chart = Frame(self.navigation_tabs) self.tcp_chart = Frame(self.navigation_tabs) self.udp_chart = Frame(self.navigation_tabs) self.icmp_chart = Frame(self.navigation_tabs) self.snmp_chart = Frame(self.navigation_tabs) self.create_charts_frames() self.assemble_tabs() # placeholders self.threads = None self.link = 0 self.input_octets = 0 self.output_octets = 0 self.link_list = [] self.ip_send = 0 self.ip_receive = 0 self.ip_send_list = [] self.ip_receive_list = [] self.tcp_send = 0 self.tcp_receive = 0 self.tcp_send_list = [] self.tcp_receive_list = [] self.udp_send = 0 self.udp_receive = 0 self.udp_send_list = [] self.udp_receive_list = [] self.icmp_send = 0 self.icmp_receive = 0 self.icmp_send_list = [] self.icmp_receive_list = [] self.snmp_send = 0 self.snmp_receive = 0 self.snmp_send_list = [] self.snmp_receive_list = [] def create_title(self): self.title_container["pady"] = 10 self.title["font"] = title_font self.title_container.pack() self.title.pack() def create_agent(self): set_container_padding(self.agent_container) set_entry_configuration(self.agent) self.agent_container.pack() self.agent_label.pack(side=LEFT) self.agent.pack(side=LEFT) def create_community(self): set_container_padding(self.community_container) set_entry_configuration(self.community) self.community_container.pack() self.community_label.pack(side=LEFT) self.community.pack(side=LEFT) def create_object(self): set_container_padding(self.object_container) set_entry_configuration(self.object) self.object_container.pack() self.object_label.pack(side=LEFT) self.object.pack(side=LEFT) def create_time(self): set_container_padding(self.time_container) set_entry_configuration(self.time) self.time_container.pack() self.time_label.pack(side=LEFT) self.time.pack(side=LEFT) def create_setup_buttons(self): set_container_padding(self.buttons_container) self.get_object["command"] = lambda: self.get_snmp_object() self.start_monitor["command"] = lambda: self.start_charts_monitor() self.stop_monitor["command"] = lambda: self.stop_charts_monitor() self.settings["command"] = lambda: self.set_settings() self.buttons_container.pack() self.get_object.pack(side=LEFT) self.start_monitor.pack(side=LEFT) self.stop_monitor.pack(side=LEFT) self.settings.pack(side=LEFT) def create_result(self): self.response_value.set("") self.warning_value.set("") self.response_label_frame.pack() self.warning_label_frame.pack() self.result_tabs.add(self.response_label_frame, text="Response") self.result_tabs.add(self.warning_label_frame, text="Warning") self.response_text.pack() self.warning_text.pack() self.result_tabs.pack() def create_charts_frames(self): self.link_chart.pack() self.ip_chart.pack() self.tcp_chart.pack() self.udp_chart.pack() self.icmp_chart.pack() self.snmp_chart.pack() def assemble_tabs(self): self.navigation_tabs.add(self.setup, text="Setup") self.navigation_tabs.add(self.link_chart, text="Link") self.navigation_tabs.add(self.ip_chart, text="IP") self.navigation_tabs.add(self.tcp_chart, text="TCP") self.navigation_tabs.add(self.udp_chart, text="UDP") self.navigation_tabs.add(self.icmp_chart, text="ICMP") self.navigation_tabs.add(self.snmp_chart, text="SNMP") self.navigation_tabs.pack() def get_snmp_object(self): parameters = self.extract_snmp_parameters() snmp_response = snmp_api.run(parameters) self.response_value.set(snmp_response) self.update_return_value() def extract_snmp_parameters(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": self.object.get() } return parameters def clear_return_value(self): self.response_text.delete("1.0", END) def update_return_value(self): self.clear_return_value() self.response_text.insert(INSERT, self.response_value.get()) def start_charts_monitor(self): self.create_charts = True self.create_threads() for thread in self.threads: thread.daemon = True thread.start() def create_threads(self): self.threads = [ Thread(target=self.create_link_chart), Thread(target=self.create_ip_chart), Thread(target=self.create_tcp_chart), Thread(target=self.create_udp_chart), Thread(target=self.create_icmp_chart), Thread(target=self.create_snmp_chart) ] def create_link_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_link_chart() new_input_octets = self.get_input_octets() new_output_octets = self.get_output_octets() input_difference = new_input_octets - self.input_octets output_difference = new_output_octets - self.output_octets link_utilization = self.get_link_utilization(input_difference, output_difference) if (self.link): self.link_list.append(link_utilization) self.verify_link_limits(link_utilization) self.input_octets = new_input_octets self.output_octets = new_output_octets self.link = link_utilization fig = Figure() ax = fig.add_subplot() ax.grid() ax.plot(self.link_list) ax.set_title("Link utilization") graph = FigureCanvasTkAgg(fig, master=self.link_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating link chart.\n") self.update_warning_value() def verify_link_limits(self, difference): limits = dao.get_limits_from_link()[0] inferior = limits[0] superior = limits[1] if difference < inferior or difference > superior: self.warning_value.set("Link is out of defined limits.\n") self.update_warning_value() def get_link_utilization(self, input_octets, output_octets): if_speed = self.get_if_speed() return (input_octets + output_octets) * 8 / if_speed def get_input_octets(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "ifInOctets.2" } return int(snmp_api.run(parameters)) def get_output_octets(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "ifOutOctets.2" } return int(snmp_api.run(parameters)) def get_if_speed(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "ifSpeed.2" } return int(snmp_api.run(parameters)) def create_ip_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_ip_chart() new_send = self.get_ip_send() new_receive = self.get_ip_receive() send_difference = new_send - self.ip_send receive_difference = new_receive - self.ip_receive if (self.ip_send or self.ip_receive): self.ip_send_list.append(send_difference) self.ip_receive_list.append(receive_difference) self.verify_ip_limits(send_difference, receive_difference) self.ip_send = new_send self.ip_receive = new_receive fig = Figure() ax = fig.add_subplot() ax.grid() ax.set_ylabel("% of packets") ax.set_title("IP send/receive") ax.plot(self.ip_send_list, label="Send") ax.plot(self.ip_receive_list, label="Receive") ax.legend(loc=0) graph = FigureCanvasTkAgg(fig, master=self.ip_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating IP chart.\n") self.update_warning_value() def verify_ip_limits(self, send_difference, receive_difference): limits = dao.get_limits_from_ip()[0] inferior = limits[0] superior = limits[1] if send_difference < inferior or send_difference > superior or receive_difference < inferior or receive_difference > superior: self.warning_value.set("IP is out of defined limits.\n") self.update_warning_value() def get_ip_send(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "ipInDelivers.0" } return int(snmp_api.run(parameters)) def get_ip_receive(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "ipOutRequests.0" } return int(snmp_api.run(parameters)) def create_tcp_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_tcp_chart() new_send = self.get_tcp_send() new_receive = self.get_tcp_receive() send_difference = new_send - self.tcp_send receive_difference = new_receive - self.tcp_receive if (self.tcp_send or self.tcp_receive): self.tcp_send_list.append(send_difference) self.tcp_receive_list.append(receive_difference) self.verify_tcp_limits(send_difference, receive_difference) self.tcp_send = new_send self.tcp_receive = new_receive fig = Figure() ax = fig.add_subplot() ax.grid() ax.set_ylabel("% of packets") ax.set_title("TCP send/receive") ax.plot(self.tcp_send_list, label="Send") ax.plot(self.tcp_receive_list, label="Receive") ax.legend(loc=0) graph = FigureCanvasTkAgg(fig, master=self.tcp_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating TCP chart.\n") self.update_warning_value() def verify_tcp_limits(self, send_difference, receive_difference): limits = dao.get_limits_from_tcp()[0] inferior = limits[0] superior = limits[1] if send_difference < inferior or send_difference > superior or receive_difference < inferior or receive_difference > superior: self.warning_value.set("TCP is out of defined limits.\n") self.update_warning_value() def get_tcp_send(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "tcpOutSegs.0" } return int(snmp_api.run(parameters)) def get_tcp_receive(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "tcpInSegs.0" } return int(snmp_api.run(parameters)) def create_udp_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_udp_chart() new_send = self.get_udp_send() new_receive = self.get_udp_receive() send_difference = new_send - self.udp_send receive_difference = new_receive - self.udp_receive if (self.udp_send or self.udp_receive): self.udp_send_list.append(send_difference) self.udp_receive_list.append(receive_difference) self.verify_udp_limits(send_difference, receive_difference) self.udp_send = new_send self.udp_receive = new_receive fig = Figure() ax = fig.add_subplot() ax.grid() ax.set_ylabel("% of packets") ax.set_title("UDP send/receive") ax.plot(self.udp_send_list, label="Send") ax.plot(self.udp_receive_list, label="Receive") ax.legend(loc=0) graph = FigureCanvasTkAgg(fig, master=self.udp_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating UDP chart.\n") self.update_warning_value() def verify_udp_limits(self, send_difference, receive_difference): limits = dao.get_limits_from_udp()[0] inferior = limits[0] superior = limits[1] if send_difference < inferior or send_difference > superior or receive_difference < inferior or receive_difference > superior: self.warning_value.set("UDP is out of defined limits.\n") self.update_warning_value() def get_udp_send(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "udpOutDatagrams.0" } return int(snmp_api.run(parameters)) def get_udp_receive(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "udpInDatagrams.0" } return int(snmp_api.run(parameters)) def create_icmp_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_icmp_chart() new_send = self.get_icmp_send() new_receive = self.get_icmp_receive() send_difference = new_send - self.icmp_send receive_difference = new_receive - self.icmp_receive if (self.icmp_send or self.icmp_receive): self.icmp_send_list.append(send_difference) self.icmp_receive_list.append(receive_difference) self.verify_icmp_limits(send_difference, receive_difference) self.icmp_send = new_send self.icmp_receive = new_receive fig = Figure() ax = fig.add_subplot() ax.grid() ax.set_ylabel("% of packets") ax.set_title("ICMP send/receive") ax.plot(self.icmp_send_list, label="Send") ax.plot(self.icmp_receive_list, label="Receive") ax.legend(loc=0) graph = FigureCanvasTkAgg(fig, master=self.icmp_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating ICMP chart.\n") self.update_warning_value() def verify_icmp_limits(self, send_difference, receive_difference): limits = dao.get_limits_from_icmp()[0] inferior = limits[0] superior = limits[1] if send_difference < inferior or send_difference > superior or receive_difference < inferior or receive_difference > superior: self.warning_value.set("ICMP is out of defined limits.\n") self.update_warning_value() def get_icmp_send(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "icmpOutMsgs.0" } return int(snmp_api.run(parameters)) def get_icmp_receive(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "icmpInMsgs.0" } return int(snmp_api.run(parameters)) def create_snmp_chart(self): try: refresh_time = self.get_refresh_time() while self.create_charts: self.clear_snmp_chart() new_send = self.get_snmp_send() new_receive = self.get_snmp_receive() send_difference = new_send - self.snmp_send receive_difference = new_receive - self.snmp_receive if (self.snmp_send or self.snmp_receive): self.snmp_send_list.append(send_difference) self.snmp_receive_list.append(receive_difference) self.verify_snmp_limits(send_difference, receive_difference) self.snmp_send = new_send self.snmp_receive = new_receive fig = Figure() ax = fig.add_subplot() ax.grid() ax.set_ylabel("% of packets") ax.set_title("SNMP send/receive") ax.plot(self.snmp_send_list, label="Send") ax.plot(self.snmp_receive_list, label="Receive") ax.legend(loc=0) graph = FigureCanvasTkAgg(fig, master=self.snmp_chart) graph.get_tk_widget().pack() time.sleep(refresh_time) except Exception: self.warning_value.set("Error creating SNMP chart.\n") self.update_warning_value() def verify_snmp_limits(self, send_difference, receive_difference): limits = dao.get_limits_from_snmp()[0] inferior = limits[0] superior = limits[1] if send_difference < inferior or send_difference > superior or receive_difference < inferior or receive_difference > superior: self.warning_value.set("SNMP is out of defined limits.\n") self.update_warning_value() def get_snmp_send(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "snmpOutPkts.0" } return int(snmp_api.run(parameters)) def get_snmp_receive(self): parameters = { "agent": self.agent.get(), "community": self.community.get(), "object": "snmpInPkts.0" } return int(snmp_api.run(parameters)) def clear_link_chart(self): for child in self.link_chart.winfo_children(): child.destroy() def clear_ip_chart(self): for child in self.ip_chart.winfo_children(): child.destroy() def clear_tcp_chart(self): for child in self.tcp_chart.winfo_children(): child.destroy() def clear_udp_chart(self): for child in self.udp_chart.winfo_children(): child.destroy() def clear_icmp_chart(self): for child in self.icmp_chart.winfo_children(): child.destroy() def clear_snmp_chart(self): for child in self.snmp_chart.winfo_children(): child.destroy() def get_refresh_time(self): try: refresh_time = int(self.time.get()) if refresh_time > 0: self.clear_warning_value() return refresh_time except Exception: self.warning_value.set("Refresh time must be higher than zero.\n") self.update_warning_value() return 0 def clear_warning_value(self): self.warning_text.delete("1.0", END) def update_warning_value(self): self.warning_text.insert(INSERT, self.warning_value.get()) def stop_charts_monitor(self): self.create_charts = False def set_settings(self): SNMPSettings(self.master)
def main(): window = Tk() window.title("HintPad") window.geometry("600x600+500+100") locations.sort() items.sort() #Way the hero way = LabelFrame(window, text="Way the hero", padx=20, pady=20) way.pack(fill="both", expand="yes") for i in range(4): createComboBox(way, elements=locations).grid(row=int(i / 2), column=i % 2) #Barren of treasure barren = LabelFrame(window, text="Barren of treasure", padx=20, pady=20) barren.pack(fill="both", expand="yes") for i in range(2): createComboBox(barren, elements=locations).grid(row=int(i / 2), column=i % 2) #Other other = LabelFrame(window, text="Other", padx=20, pady=20) other.pack(fill="both", expand="yes") value = BooleanVar() value.set(True) check = Checkbutton(other, text="Remove useless item", variable=value, command=(lambda: removeUseless(value))) check.grid(row=0, column=0) Label(other, text="30 skulls").grid(row=1, column=0) Label(other, text="40 skulls").grid(row=2, column=0) Label(other, text="50 skulls").grid(row=3, column=0) Label(other, text="Frogs").grid(row=4, column=0) Label(other, text="Ocarina Of Time").grid(row=5, column=0) Label(other, text="Biggoron Sword").grid(row=6, column=0) for i in range(6): combo = createComboBox(other, elements=items) combosWithItem.append(combo) combo.grid(row=i + 1, column=1) Button(other, text="+", command=lambda: addEntry(other, value)).grid(row=7, column=0) Button(other, text="-", command=removeEntry).grid(row=7, column=1) window.mainloop()
class GraphicalUserInterface(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.__initUI() def __initUI(self): self.parent.title("Fuel Manager") # parameters that the user can modify self.__exchvar = BooleanVar() self.__exchrate = True self.__datevar = BooleanVar() self.__datetime = True self.__empty_tank_var = BooleanVar() self.__empty_tank = False self.__airport_file = "input files/airport.csv" self.__aircraft_file = "input files/aircraft.csv" self.__currency_file = "input files/countrycurrency.csv" self.__exchange_rate_file = "input files/currencyrates.csv" self.__itinerary_file = "input files/testroutes.csv" self.__output_file = "bestroutes/bestroutes.csv" self.__home_airport = ["DUB"] self.__other_airports = ["LHR", "CDG", "JFK", "AAL", "AMS", "ORK"] self.__hubs = ["MHP"] self.__stopover_cost = 0 self.__constraints = "JFK AAL / JFK CDG" self.__aircraft_code = "747" # main frame frame = Frame(self, relief=RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) # manage single itinerary frame self.manual_frame = LabelFrame(self, text="Manage a single itinerary", font=("Helvetica", 14), width=300) self.manual_frame.place(x=50, y=50) # Empty row to put some space between the other rows and to control the width of this frame because # I don't know what I'm doing self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=0, sticky="W") # Text field where user can enter home airport self.home_airport_label = Label(self.manual_frame, width=22, text="Home airport:", anchor='w') self.home_airport_label.grid(row=1, sticky="W") self.home_airport_entry = Entry(self.manual_frame, width=50) self.home_airport_entry.grid(row=2, sticky="E") self.home_airport_entry.insert(0, self.__home_airport) self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=3, sticky="W") # Text field where user can enter other airports self.other_airports_label = Label(self.manual_frame, width=22, text="Other airports:", anchor='w') self.other_airports_label.grid(row=4, sticky="W") self.other_airports_entry = Entry(self.manual_frame, width=50) self.other_airports_entry.grid(row=5, sticky="E") self.other_airports_entry.insert(0, self.__other_airports) self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=6, sticky="W") # Text field where user can enter aircraft code self.aircraft_label = Label(self.manual_frame, width=22, text="Aircraft code:", anchor='w') self.aircraft_label.grid(row=7, sticky="W") self.aircraft_entry = Entry(self.manual_frame, width=50) self.aircraft_entry.grid(row=8, sticky="E") self.aircraft_entry.insert(0, self.__aircraft_code) self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=9, sticky="W") # Text field where user can enter constraints self.constraints_label = Label(self.manual_frame, width=22, text="Constraints:", anchor='w') self.constraints_label.grid(row=13, sticky="W") self.constraints_entry = Entry(self.manual_frame, width=50) self.constraints_entry.grid(row=14, sticky="E") self.constraints_entry.insert(0, self.__constraints) self.constraints_explanation_label = \ Label(self.manual_frame, width=50, text="Each constraint should consist of three-letter airport codes" "\nseparated by spaces. To enter more than one constraint," "\nuse ' / ' to separate them", anchor='w', justify='left') self.constraints_explanation_label.grid(row=15, sticky="W") self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=16, sticky="W") # run button self.run_button = Button(self.manual_frame, text='Manage itinerary', command=self.__manage_single_itinerary, bg="#CCE1E8") self.run_button.grid(row=16, sticky="E") # manage list of itineraries frame self.itinerary_list_frame = LabelFrame(self, text="Manage a list of itineraries", font=("Helvetica", 14), width=300) self.itinerary_list_frame.place(x=50, y=375) # Empty row to put some space between the other rows and to control the width of this frame self.empty_label = Label(self.itinerary_list_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=12, sticky="W") # Text field where user can enter itinerary filepath self.itinerary_label = Label(self.itinerary_list_frame, width=22, text="Itinerary list: ", anchor='w') self.itinerary_label.grid(row=13, sticky="W") self.itinerary_entry = Entry(self.itinerary_list_frame, width=50) self.itinerary_entry.grid(row=13, sticky="E") self.itinerary_entry.insert(0, self.__itinerary_file) self.itinerary_button = Button(self.itinerary_list_frame, text='Browse...', command=self.__get_itinerary_filename) self.itinerary_button.grid(row=14, sticky="E") self.empty_label = Label(self.itinerary_list_frame, text=" ", width=60, height=2, font=("Helvetica", 1)) self.empty_label.grid(row=15, sticky="W") # run button self.run_button = Button(self.itinerary_list_frame, text='Manage list of itineraries', command=self.__manage_list, bg="#CCE1E8") self.run_button.grid(row=16, sticky="E") # Fuel management settings frame self.general_frame = LabelFrame(self, text="Fuel management settings", font=("Helvetica", 14), width=300) self.general_frame.place(x=500, y=50) # Empty row to put some space between the other rows and to control the width of this frame self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=0, sticky="W") # Text field where user can enter hubs self.hubs_label = Label(self.general_frame, width=22, text="Hubs:", anchor='w') self.hubs_label.grid(row=1, sticky="W") self.hubs_entry = Entry(self.general_frame, width=50) self.hubs_entry.grid(row=2, sticky="E") self.hubs_entry.insert(0, self.__hubs) self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=3, sticky="W") # Text field where user can enter cost of extra stopovers self.stopover_cost_label = Label(self.general_frame, width=40, text="Cost of each extra stopover (euros):", anchor='w') self.stopover_cost_label.grid(row=4, sticky="W") self.stopover_cost_entry = Entry(self.general_frame, width=50) self.stopover_cost_entry.grid(row=5, sticky="E") self.stopover_cost_entry.insert(0, self.__stopover_cost) self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=6, sticky="W") # bring home extra fuel checkbox self.empty_tank_cb = Checkbutton(self.general_frame, text="Always return to home airport with an empty tank", variable=self.__empty_tank_var, command=self.__empty_tank_toggle) self.empty_tank_cb.grid(row=7, sticky="W") self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=8, sticky="W") # manage inputs frame self.input_frame = LabelFrame(self, text="Inputs", font=("Helvetica", 14), width=300) self.input_frame.place(x=500, y=250) self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=0, sticky="W") # Text field where user can enter airport filepath self.airport_label = Label(self.input_frame, width=22, text="Airport list: ", anchor='w') self.airport_label.grid(row=1, sticky="W") self.airport_entry = Entry(self.input_frame, width=50) self.airport_entry.grid(row=1, sticky="E") self.airport_entry.insert(0, self.__airport_file) self.airport_button = Button(self.input_frame, text='Browse...', command=self.__get_airport_filename) self.airport_button.grid(row=2, sticky="E") self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=3, sticky="W") # Text field where user can enter aircraft filepath self.aircraft_file_label = Label(self.input_frame, width=22, text="Aircraft list: ", anchor='w') self.aircraft_file_label.grid(row=4, sticky="W") self.aircraft_file_entry = Entry(self.input_frame, width=50) self.aircraft_file_entry.grid(row=4, sticky="E") self.aircraft_file_entry.insert(0, self.__aircraft_file) self.aircraft_file_button = Button(self.input_frame, text='Browse...', command=self.__get_aircraft_filename) self.aircraft_file_button.grid(row=5, sticky="E") self.empty_label = Label(self.input_frame, text=" ", width=425, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=6, sticky="W") # Text field where user can enter country-currency filepath self.currency_label = Label(self.input_frame, width=22, text="Currency list: ", anchor='w') self.currency_label.grid(row=7, sticky="W") self.currency_entry = Entry(self.input_frame, width=50) self.currency_entry.grid(row=7, sticky="E") self.currency_entry.insert(0, self.__currency_file) self.currency_button = Button(self.input_frame, text='Browse...', command=self.__get_currency_filename) self.currency_button.grid(row=8, sticky="E") self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=9, sticky="W") # Text field where user can enter exchange rate filepath self.exchange_rate_label = Label(self.input_frame, width=22, text="Exchange rate list: ", anchor='w') self.exchange_rate_label.grid(row=10, sticky="W") self.exchange_rate_entry = Entry(self.input_frame, width=50) self.exchange_rate_entry.grid(row=10, sticky="E") self.exchange_rate_entry.insert(0, self.__exchange_rate_file) self.exchange_rate_button = Button(self.input_frame, text='Browse...', command=self.__get_exchange_rate_filename) self.exchange_rate_button.grid(row=11, sticky="E") # real-time exchange rates checkbox self.forex = Checkbutton(self.input_frame, text="Use real-time exchange rates", variable=self.__exchvar, command=self.__forex_toggle) self.forex.select() self.forex.grid(row=12, sticky="W") # manage output frame self.output_frame = LabelFrame(self, text="Output", font=("Helvetica", 14), width=300) self.output_frame.place(x=500, y=550) self.empty_label = Label(self.output_frame, text=" ", width=60, height=1, font=("Helvetica", 1)) self.empty_label.grid(row=0, sticky="W") # Text field where user can enter output filepath self.output_label = Label(self.output_frame, width=22, text="Output file: ", anchor='w') self.output_label.grid(row=1, sticky="W") self.output_entry = Entry(self.output_frame, width=50) self.output_entry.grid(row=1, sticky="E") self.output_entry.insert(0, self.__output_file) self.output_button = Button(self.output_frame, text='Browse...', command=self.__get_output_filename) self.output_button.grid(row=2, sticky="E") # append date to output filename checkbox self.datetime_cb = Checkbutton(self.output_frame, text="Append date and time to filename (e.g., bestroutes 20151218 160000.csv)", variable=self.__datevar, command=self.__datetime_toggle) self.datetime_cb.grid(row=3, sticky="W") self.datetime_cb.select() # GUI methods def __forex_toggle(self): if self.__exchvar.get() == True: self.__exchrate = True else: self.__exchrate = False def __datetime_toggle(self): if self.__datevar.get() == True: self.__datetime = True else: self.__datetime = False def __empty_tank_toggle(self): if self.__empty_tank_var.get() == True: self.__empty_tank = True else: self.__empty_tank = False def __get_airport_filename(self): self.__airport_file = filedialog.askopenfilename( filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*"))) self.airport_entry.delete(0, END) self.airport_entry.insert(0, self.__airport_file) def __get_aircraft_filename(self): self.__aircraft_file = filedialog.askopenfilename( filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*"))) self.aircraft_file_entry.delete(0, END) self.aircraft_file_entry.insert(0, self.__aircraft_file) def __get_currency_filename(self): self.__currency_file = filedialog.askopenfilename( filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*"))) self.currency_entry.delete(0, END) self.currency_entry.insert(0, self.__currency_file) def __get_exchange_rate_filename(self): self.__exchange_rate_file = filedialog.askopenfilename( filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*"))) self.exchange_rate_entry.delete(0, END) self.exchange_rate_entry.insert(0, self.__exchange_rate_file) def __get_itinerary_filename(self): self.__itinerary_file = filedialog.askopenfilename( filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*"))) self.itinerary_entry.delete(0, END) self.itinerary_entry.insert(0, self.__itinerary_file) def __get_output_filename(self): self.__output_file = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=( ("Comma-separated values file", "*.csv"), ("All Files", "*.*"))) self.output_entry.delete(0, END) self.output_entry.insert(0, self.__output_file) def __manage_list(self): # validate user inputs hubs, stopover_cost = validate_inputs_for_list_of_itineraries(self.hubs_entry.get().upper().split(), self.stopover_cost_entry.get()) print("Managing list of itineraries...") manage_list_of_routes(self.__exchrate, self.__datetime, self.__empty_tank, hubs, stopover_cost, self.itinerary_entry.get(), self.airport_entry.get(), self.aircraft_file_entry.get(), self.currency_entry.get(), self.exchange_rate_entry.get(), self.output_entry.get()) def __manage_single_itinerary(self): # validate user inputs try: hubs, stopover_cost, constraints_list, home_airport, other_airports, aircraft_code = \ validate_inputs_for_single_itinerary(self.hubs_entry.get().upper().split(), self.stopover_cost_entry.get(), self.constraints_entry.get().upper().split(), self.home_airport_entry.get().upper(), self.other_airports_entry.get().upper().split(), self.aircraft_entry.get().upper()) except TypeError: return print("Managing single itinerary...") manage_single_route(home_airport, other_airports, aircraft_code, self.__exchrate, self.__datetime, self.__empty_tank, hubs, stopover_cost, constraints_list, self.airport_entry.get(), self.aircraft_file_entry.get(), self.currency_entry.get(), self.exchange_rate_entry.get(), self.output_entry.get())
class FrameTab1(ttk.Frame): __centralTendencyObj = CentralTendency() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grid_columnconfigure(0, weight = 1) self.grid_rowconfigure(0, weight = 1) self.container = LabelFrame(self, text = 'medidas de tendencia central y Medidas de dispersion') self.container.grid(row = 0, column = 0,sticky = "w,e,s,n", padx = 5, ipadx = 5) #Entries self.containerEntries = ttk.LabelFrame(self.container, text = 'Datos') self.containerEntries.grid(row = 2, column = 0, rowspan = 1, columnspan = 3, sticky = "e,w", ipadx = 10) self.NumIntervLbl = ttk.Label(self.containerEntries, text = "Numero de intervalos:") self.NumIntervLbl.grid(row = 0, column = 0) self.NumInterv = ttk.Entry(self.containerEntries, width = 15) self.NumInterv.grid(row = 0, column = 1, pady = 5) self.ValueLbl = ttk.Label(self.containerEntries, text = "valor:") self.ValueLbl.grid(row = 1, column =0, padx =10) self.Value = ttk.Entry(self.containerEntries, width = 30) self.Value.bind('<Return>', self.enterEvent) self.Value.grid(row = 1, column = 1, columnspan = 2, padx =10) self.btnAggInterv = ttk.Button(self.containerEntries, text = "Agregar", command = self.addValue) self.btnAggInterv.grid(row = 1, column = 3, padx =10) self.btnCalc = ttk.Button(self.containerEntries, text = "Calcular", command = self.calc) self.btnCalc.grid(row = 1, column = 4, padx =10) #TextArea values self.container_val = ttk.LabelFrame(self.container, text = 'valores') self.container_val.grid(row = 0, column = 0, rowspan = 2, sticky = "sw,nw,n,s,w", ipadx = 5) self.valuesTxt = Text(self.container_val, width = 25) self.valuesTxt.grid(row = 0, sticky = "sw,nw,n,s,w", padx = 5) self.valuesTxt["state"] = "disabled" self.scrollbar = ttk.Scrollbar(self.container_val) self.scrollbar.grid(row = 0, sticky = "e, n, s") self.valuesTxt.config( yscrollcommand = self.scrollbar.set ) self.scrollbar.config( command = self.valuesTxt.yview ) #frequence table self.containerTable = ttk.LabelFrame(self.container, text = 'tabla de frecuencia') self.containerTable.grid(row = 0, column = 1, columnspan = 2, sticky = "n, s, e, w") self.freqTable = ttk.Treeview(self.containerTable, height = 10, columns =('#1', '#2', '#3', '#4', '#5', '#6')) self.freqTable['show'] = 'headings' self.freqTable.heading('#1', text = "intervalos", anchor = CENTER) self.freqTable.heading('#2', text = "M", anchor = CENTER) self.freqTable.heading('#3', text = "f", anchor = CENTER) self.freqTable.heading('#4', text = "F", anchor = CENTER) self.freqTable.heading('#5', text = "Fr", anchor = CENTER) self.freqTable.heading('#6', text = "F%", anchor = CENTER) self.freqTable.column("#1", width = 100) self.freqTable.column("#2", width = 70) self.freqTable.column("#3", width = 70) self.freqTable.column("#4", width = 70) self.freqTable.column("#5", width = 120) self.freqTable.column("#6", width = 120) self.freqTable.grid(row = 0, column = 0, sticky = "n, e, w, s") #result container self.containerResult = ttk.LabelFrame(self.container, text = 'Resultados') self.containerResult.grid(row = 1, column = 1, sticky = "n,s,e,w") self.ResultTxt = Text(self.containerResult, height = 10, width = 67) self.ResultTxt.grid(row = 0, sticky = "w, n, s, e") self.ResultTxt["state"] = "disabled" self.scrollbar2 = ttk.Scrollbar(self.containerResult) self.scrollbar2.grid(row = 0, sticky = "e, n, s") self.ResultTxt.config( yscrollcommand = self.scrollbar2.set ) self.scrollbar2.config( command = self.ResultTxt.yview ) def enterEvent(self,event): self.addValue() def addValue(self): value = self.Value.get() self.__centralTendencyObj.add( int( value ) ) self.valuesTxt["state"] = "normal" self.valuesTxt.insert(END, str(value + ",\n")) self.valuesTxt["state"] = "disabled" def calc(self): if len(self.NumInterv.get()) == 0: messagebox.showinfo(title = "Error", message = "Ingrese el numero de intervalos") else: numIntervals = int(self.NumInterv.get()) if numIntervals < 1: messagebox.showinfo(title = "Error", message = "El numero de intervalos no puede ser 0") else: self.ResultTxt["state"] = "normal" self.ResultTxt.insert(END, self.__centralTendencyObj.calc( numIntervals )) self.ResultTxt["state"] = "disabled" self.createTable() def createTable(self): intervals = self.__centralTendencyObj.getTable() for i in intervals: self.freqTable.insert('', 0,text = "", values = i.get())
def Build_global(self): ''' Create global generate ini ''' def about_citation(): """ Create about popup """ popup = tk.Toplevel() popup.wm_title("About: Ver: " + str(self.__version__)) popup.resizable(False,False) cite = tk.Label(popup,text='Citation:',font='TkTextFont') cite.grid(column=0,row=0,sticky=N,padx=self.padx,pady=self.pady) citation = scrolledtext.ScrolledText(popup, width = 75, height = 10, font="TkTextFont") citation.grid(column=0,row=1,sticky=N,padx=self.padx,pady=self.pady) citation.configure(state ='disabled') with open('media/Citation') as f: citation.insert(tk.END,f.read()) License_Label = tk.Label(popup,text='License:',font='TkTextFont') License_Label.grid(column=0,row=2,sticky=N,padx=self.padx,pady=self.pady) license = scrolledtext.ScrolledText(popup, width = 75, font = "TkTextFont") license.grid(column=0,row=3,sticky=N,padx=self.padx,pady=self.pady) license.configure(state ='disabled') with open('../LICENSE') as f: license.insert(tk.END,f.read()) B1 = ttk.Button(popup, text="Okay", command = popup.destroy) B1.grid(column=0,row=4,padx=self.padx,pady=self.pady) # popup.grid_columnconfigure((1,3),weight=1) # popup.grid_rowconfigure((1,3),weight=1) popup.grid_columnconfigure((0,2),weight=1) popup.grid_rowconfigure((0,2),weight=1) popup.protocol('WM_DELETE_WINDOW', popup.destroy) self.generate_button = tk.Button(self.root, text="Generate Input", command=self.Generate_ini) self.generate_button.grid(column=3,row=2,sticky=E,padx=self.padx,pady=self.pady) self.run_button = tk.Button(self.root,text='Run',command=self.run_term) self.run_button.grid(column=1,row=2,columnspan=1,sticky=E,padx=self.padx,pady=self.pady) self.stop_button = tk.Button(self.root,text='Stop',command=self.stop_term) self.stop_button.grid(column=2,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) if self.os == 'Windows': self.stop_button.config(state='disabled') self.about_button = tk.Button(self.root,text='About',command=about_citation) self.about_button.grid(column=0,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) self.root.grid_columnconfigure(1, weight=1) self.root.grid_columnconfigure(2, weight=1) self.root.grid_rowconfigure(0,weight=1) # Create a empty frame self.label_frame = LabelFrame(self.root, text="Terminal", padx=5, pady=5) self.label_frame.grid(column=0,row=1, columnspan=4, padx=self.padx, pady=self.pady, sticky=E+W+N+S) # Create the textbox self.label_frame.rowconfigure(0,weight=1) self.label_frame.columnconfigure(0,weight=1) self.txtbox = scrolledtext.ScrolledText(self.label_frame, width=40, height=10) self.txtbox.grid(row=0, column=0, sticky=E+W+N+S)
class Zzzscoring(): def __init__(self, master): self.master = master master.title("Zzzscoring: Automatic sleep scoring package") #### !!~~~~~~~~~~~~~~~~~ DEFINE INPUT DATAFRAME ~~~~~~~~~~~~~~~~~!!#### self.frame_import = LabelFrame(self.master, text="Import files section", padx=150, pady=100, font='Calibri 18 bold') self.frame_import.grid(row=0, column=0, padx=200, pady=50, columnspan=8) #### ==================== Help pop-up button ======================#### self.popup_button = Button(self.master, text="Help", command=self.help_pop_up_func, font='Calibri 13 bold', fg='white', bg='black') self.popup_button.grid(row=1, column=8) #### ==================== Import data EDFs ========================#### # Label: Import EDF self.label_import = Label(self.frame_import, text="Import EDF files here:", font='Calibri 12 bold') self.label_import.grid(row=0, column=0, padx=15, pady=10) # Button: Import EDF (Browse) self.button_import_browse = Button(self.frame_import, text="Browse data", padx=100, pady=20, font='Calibri 10 bold', command=self.load_data_file_dialog, fg='blue', relief=RIDGE) self.button_import_browse.grid(row=1, column=0, padx=15, pady=10) #### ================== Import hypnogram files ====================#### # Show a message about hypnograms self.label_hypnos = Label(self.frame_import, text="Import hypnogram file (.txt) here:", font='Calibri 12 bold') self.label_hypnos.grid(row=0, column=1, padx=15, pady=10) # Define browse button to import hypnos self.button_hypnos_browse = Button(self.frame_import, text="Browse labels", padx=100, pady=20, font='Calibri 10 bold', command=self.load_hypno_file_dialog, fg='blue', relief=RIDGE) self.button_hypnos_browse.grid(row=1, column=1, padx=15, pady=10) #### ===================== Define train size ======================#### # Define train size section self.label_train_size = Label( self.frame_import, text="Train size portion (between 0 - 1):", font='Calibri 12 bold') self.label_train_size.grid(row=0, column=3, padx=15, pady=10) # Bar to ask for user's entry self.train_size = DoubleVar() self.entry_train_size = Entry(self.frame_import, text=" Enter the value here ", borderwidth=8, width=10) self.entry_train_size.grid(row=1, column=3, padx=15, pady=10) #### =================== Push apply to load data ==================#### #Label to read data and extract features self.label_apply = Label( self.frame_import, text="Press to Load, pre-process, and extract features!", font='Calibri 12 bold') self.label_apply.grid(row=0, column=4) # Apply button self.button_apply = Button(self.frame_import, text="Apply", padx=100, pady=20, font='Calibri 10 bold', relief=RIDGE, fg='blue', command=self.Apply_button) self.button_apply.grid(row=1, column=4, padx=15, pady=10) #### !!~~~~~~~~~~~~~~ DEFINE ML SECTION FRAME ~~~~~~~~~~~~~~~~~~~!!#### self.frame_ML = LabelFrame(self.master, text="Machine Learning Section", padx=150, pady=100, font='Calibri 18 bold') self.frame_ML.grid(row=1, column=0, padx=200, pady=50, columnspan=8) #### ================ Pick ML Algorithm of interest ===============#### # Label self.label_ML_algorithm = Label( self.frame_ML, text="Choose the machine learning algorithm:", font='Calibri 12 bold') self.label_ML_algorithm.grid(row=0, column=0, padx=15, pady=10) # Dropdown menu self.selected_ML = StringVar() self.selected_ML.set("Random forest") self.drop = OptionMenu(self.frame_ML, self.selected_ML, "SVM", "Random forest", "XGBoost", "Logistic regression", "Naive bayes", "Randomized trees", "GradientBoosting", "ADABoost") self.drop.grid(row=1, column=0) self.drop.config(font='Calibri 10 bold', fg='blue') # label_selec self.label_select = Label(self.frame_ML, text="Press after choosing ML algorithm:", font='Calibri 12 bold') self.label_select.grid(row=0, column=1) # select button self.button_select = Button(self.frame_ML, text="Select!", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.Select_ML_button) self.button_select.grid(row=1, column=1, padx=15, pady=10) # Chekbox for time-dependency self.td_var = IntVar() self.checkbox_td = Checkbutton(self.frame_ML, text="Multi-to-one classifcation", font='Calibri 12 bold', variable=self.td_var) self.checkbox_td.grid(row=2, column=0) # Chekbox for feature selection self.feat_select_var = IntVar() self.checkbox_feat_select = Checkbutton(self.frame_ML, text="Feature Selection", font='Calibri 12 bold', variable=self.feat_select_var) self.checkbox_feat_select.grid(row=3, column=0) #%% ################### DEFINE FUNCTIONS OF BUTTONS ####################### #%% Function: Import EDF (Browse) def load_data_file_dialog(self): global data_files_list self.filenames = filedialog.askopenfilenames( initialdir="C:/", title='select data files', filetype=(("edf", "*.edf"), ("All Files", "*.*"))) # Make a list of imported file names (full path) data_files_list = self.frame_import.tk.splitlist(self.filenames) self.n_data_files = len(data_files_list) # check if the user chose somthing if not data_files_list: self.label_data = Label(self.frame_import, text="No file has been selected!", fg='red', font='Helvetica 9 bold').grid(row=2, column=0) else: self.label_data = Label(self.frame_import, text=str(self.n_data_files) + " EDF files has been loaded!", fg='green', font='Helvetica 9 bold').grid(row=2, column=0) #%% Function: Import Hypnogram (Browse) def load_hypno_file_dialog(self): global hypno_files_list self.filenames = filedialog.askopenfilenames( initialdir="C:/", title='select label files', filetype=(("txt", "*.txt"), ("csv", "*.csv"), ("All Files", "*.*"))) hypno_files_list = self.frame_import.tk.splitlist(self.filenames) self.n_label_files = len(hypno_files_list) # check if the user chose somthing if not hypno_files_list: self.label_labels = Label(self.frame_import, text="No hypnogram has been selected!", fg='red', font='Helvetica 9 bold').grid(row=2, column=1) else: self.label_labels = Label(self.frame_import, text=str(self.n_label_files) + " hypnogram files has been loaded!", fg='green', font='Helvetica 9 bold').grid(row=2, column=1) #%% Read EDF and hypnograms and apply feature extraction def Read_Preproc_FeatExtract(self): global subjects_dic, hyp_dic, dic_pciked_chans subjects_dic = {} hyp_dic = {} dic_pciked_chans = {} #### ======================= Create log window ====================#### self.log_win = Toplevel() self.log_win.title("Log file of current processes") # Label self.label = Label(self.log_win, text="Process log file:", font='Helvetica 12 bold') self.label.pack() self.close_log_win = Button(self.log_win, text="Dismiss", command=self.log_win.destroy) self.close_log_win.pack() #### ======================= Read data files ======================#### for idx, c_subj in enumerate(data_files_list): self.log1_ = Label(self.log_win, text="Analyzing data: " + str(c_subj[-11:-4]) + "\tPlease wait ...").pack() print(f'Analyzing data: {c_subj[-11:-4]}') ## Read in data file = data_files_list[idx] tic = time.time() data = mne.io.read_raw_edf(file) # Data raw EEG --> Deactive # data.plot(duration = 30, highpass = .3 , lowpass = 25 ) raw_data = data.get_data() print('Time to read EDF: {}'.format(time.time() - tic)) self.log2_ = Label(self.log_win, text="Time to read EDF data (s): " + str(np.round(time.time() - tic))).pack() #####=================Retrieving information from data====================##### DataInfo = data.info AvailableChannels = DataInfo['ch_names'] self.fs = int(DataInfo['sfreq']) #####==================Choosing channels of interest======================##### # 1. The channels that need to be referenced Mastoids = ['TP10'] # Reference electrodes RequiredChannels = ['C3'] # main electrodes # 2. Channels that don't need to be referenced: --> Deactive Idx = [] Idx_Mastoids = [] #####================= Find index of required channels ===================##### for indx, c in enumerate(AvailableChannels): if c in RequiredChannels: Idx.append(indx) elif c in Mastoids: Idx_Mastoids.append(indx) #####===== Sampling rate is 200hz; thus 1 epoch(30s) is 6000 samples =====##### T = 30 #secs len_epoch = self.fs * T start_epoch = 0 n_channels = len(AvailableChannels) #####============ Cut tail; use modulo to find full epochs ===============##### raw_data = raw_data[:, 0:raw_data.shape[1] - raw_data.shape[1] % len_epoch] #####========== Reshape data [n_channel, len_epoch, n_epochs] ============##### data_epoched = np.reshape( raw_data, (n_channels, len_epoch, int(raw_data.shape[1] / len_epoch)), order='F') #####===================== Reading hypnogram data ========================##### hyp = loadtxt(hypno_files_list[idx], delimiter="\t") ### Create sepereate data subfiles based on hypnogram (N1, N2, N3, NREM, REM) tic = time.time() #####================= Concatenation of selected channels ================##### # Calculate referenced channels: data_epoched_selected = data_epoched[Idx] - data_epoched[ Idx_Mastoids] #####================= Find order of the selected channels ===============##### #Init picked_channels = [] picked_refs = [] List_Channels = [] # Find main channels for jj, kk in enumerate(Idx): picked_channels = np.append(picked_channels, AvailableChannels[kk]) # Find references for jj, kk in enumerate(Idx_Mastoids): picked_refs = np.append(picked_refs, AvailableChannels[kk]) print( f'subject LK {c_subj} --> detected channels: {str(picked_channels)} - {str(picked_refs)}' ) self.log3_ = Label(self.log_win, text="Dectected channels:" + str(picked_channels) + "-" + str(picked_refs)).pack() # Create lis of channels for kk in np.arange(0, len(Idx)): List_Channels = np.append( List_Channels, picked_channels[kk] + '-' + picked_refs[kk]) #%% Analysis section #####================= remove chanbnels without scroing ==================##### # assign the proper data and labels x_tmp_init = data_epoched_selected y_tmp_init = hyp #Define ssccoorriinngg object: self.Object = ssccoorriinngg(filename='', channel='', fs=self.fs, T=30) # Ensure equalituy of length for arrays: self.Object.Ensure_data_label_length(x_tmp_init, y_tmp_init) # Remove non-scored epochs x_tmp, y_tmp = self.Object.remove_channels_without_scoring( hypno_labels=y_tmp_init, input_feats=x_tmp_init) # Remove disconnections '''x_tmp, y_tmp = self.Object.remove_disconnection(hypno_labels= y_tmp, input_feats=x_tmp) ''' #####============= Create a one hot encoding form of labels ==============##### # Create binary labels array self.yy = self.Object.One_hot_encoding(y_tmp) # Ensure all the input labels have a class self.Object.Unlabaled_rows_detector(self.yy) #%% Function: Feature_Extraction # Initialize feature array: self.Feat_all_channels = np.empty((np.shape(x_tmp)[-1], 0)) #####================== Extract the relevant features ====================##### for k in np.arange(np.shape(data_epoched_selected)[0]): feat_temp = self.Object.FeatureExtraction_per_subject( Input_data=x_tmp[k, :, :]) self.Feat_all_channels = np.column_stack( (self.Feat_all_channels, feat_temp)) toc = time.time() print( f'Features of subject { c_subj[-11:-4]} were successfully extracted in: {toc-tic} secs' ) self.log4_ = Label(self.log_win, text="Features of subject" + str(c_subj[-11:-4]) + " were successfully extracted in (secs):" + str(np.round(toc - tic))).pack() # Double check the equality of size of arrays self.Object.Ensure_feature_label_length(self.Feat_all_channels, self.yy) # Defining dictionary to save features PER SUBJECT subjects_dic["subject{}".format( c_subj[-11:-4])] = self.Feat_all_channels # Defining dictionary to save hypnogram PER SUBJECT hyp_dic["hyp{}".format(c_subj[-11:-4])] = self.yy # Show picked channels per subject dic_pciked_chans["subj{}".format(c_subj[-11:-4])] = List_Channels #####=============== Removing variables for next iteration ===============##### del x_tmp, y_tmp, feat_temp toc = time.time() print( 'Feature extraction of subject { c_subj[-11:-4]} has been finished.' ) self.log5_ = Label(self.log_win, text="Feature extraction of subject " + str(c_subj[-11:-4]) + " has been finished.").pack() print( 'Total feature extraction of subjects took {tic_tot - time.time()} secs.' ) #%% Function: Import Hypnogram (Browse) def Apply_button(self): #### ======================= Get the train size ===================#### self.train_size = self.entry_train_size.get() # Has the user loaded hypnos?! if not hypno_files_list: self.label_apply1 = Label(self.frame_import, text="You haven't added any hypnogram!", fg='red', font='Helvetica 9 bold').grid(row=2, column=4) # Has the user loaded EDF files?! elif not data_files_list: self.label_apply2 = Label(self.frame_import, text="You haven't added any EDF files!", fg='red', font='Helvetica 9 bold').grid(row=2, column=4) # Check if train size is a valid value elif not self.train_size: self.label_apply1 = Label(self.frame_import, text="No train size is entered!", fg='red', font='Helvetica 9 bold').grid(row=2, column=4) elif float(self.train_size) > 0.99 or float(self.train_size) < 0.01: self.label_apply1 = Label( self.frame_import, text="Invalid train size! (acceptable range:0-1)", fg='red', font='Helvetica 9 bold').grid(row=2, column=4) # Do the imported data an hypnos have the same amount of inputs? elif len(data_files_list) != len(hypno_files_list): self.label_apply3 = Label( self.frame_import, text= "Size of the loaded hypons and EDF files do not match! Please recheck ...", fg='red', font='Helvetica 9 bold').grid(row=2, column=4) # Else --> Go next if len(data_files_list) == len(hypno_files_list) and float( self.train_size) < .99 and float(self.train_size) > 0.01: self.label_apply4 = Label( self.frame_import, text="Train size: " + str(self.train_size) + "\nData and hypnogram have received in a good order!\n Go to next section to proceed ...", fg='green', font='Helvetica 9 bold').grid(row=2, column=4) subjects_dic, hyp_dic, dic_pciked_chans = self.Read_Preproc_FeatExtract( ) #%% Function: Import Hypnogram (Browse) def Select_ML_button(self): # Check the current ML flag self.selected_ML = self.selected_ML.get() # Define label self.label_select1 = Label( self.frame_ML, text=str(self.selected_ML) + " has been selected.\n Please adjust the folloiwng hypermarameters.", fg='green', font='Helvetica 9 bold').grid(row=2, column=1) #### ============== Train the model and predict test ==============#### self.label_train = Label(self.frame_ML, text="Start Taining!", font='Calibri 12 bold') self.label_train.grid(row=0, column=3) # Activate train Button self.button_train = Button(self.frame_ML, text="Train model!", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.Training_function) self.button_train.grid(row=1, column=3) #### ============== multi-to-one classification flag ============ #### if int(self.td_var.get()) == 1: # Label self.label_checkbox = Label(self.frame_ML, text="Time-dependence (#epochs):", font='Calibri 12 bold') self.label_checkbox.grid(row=2, column=2) # entry for td # ============================================================================= # self.td = IntVar() # self.td.set(6) # ============================================================================= self.entry_td = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_td.grid(row=3, column=2, padx=15, pady=10) # SVM Hyperparameters if self.selected_ML == "SVM": self.kernel_ = StringVar() #init self.kernel_.set('rbf') # Differnt Kernel functions of SVM: Kernel_rbf = Radiobutton(self.frame_ML, text='rbf', variable=self.kernel_, value='rbf', font='Helvetica 12 bold') Kernel_sig = Radiobutton(self.frame_ML, text='sigmoid', variable=self.kernel_, value='sigmoid', font='Helvetica 12 bold') Kernel_pol = Radiobutton(self.frame_ML, text='poly', variable=self.kernel_, value='poly', font='Helvetica 12 bold') # Get the chosen Kernel #self.kernel = self.kernel.get() # Shoving the radio buttons to the frame Kernel_rbf.grid(row=0, column=2) Kernel_sig.grid(row=1, column=2) Kernel_pol.grid(row=2, column=2) # Random forest hyperparameters elif self.selected_ML == "Random forest": self.n_estimator_RF = IntVar() self.n_estimator_RF.set(10) # Create n_estimators label self.label_n_estimators = Label(self.frame_ML, text="Number of trees:", font='Calibri 12 bold') self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10) # Create entry for user self.entry_n_estimator_RF = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_n_estimator_RF.grid(row=1, column=2, padx=15, pady=10) # Assign the value to send to classifier #self.n_estimator_RF = self.entry_n_estimator_RF.get() # XGBoost elif self.selected_ML == "XGBoost": self.n_estimator_xgb = IntVar() # Create n_estimators label self.label_n_estimators = Label(self.frame_ML, text="Number of trees:", font='Calibri 12 bold') self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10) # Create entry for user self.entry_n_estimator_xgb = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_n_estimator_xgb.grid(row=1, column=2, padx=15, pady=10) # Assign the value to send to classifier #self.n_estimator_xgb = self.entry_n_estimator_xgb.get() # ADABoost elif self.selected_ML == "ADABoost": self.n_estimator_ada = IntVar() # Create n_estimators label self.label_n_estimators = Label(self.frame_ML, text="Number of trees:", font='Calibri 12 bold') self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10) # Create entry for user self.entry_n_estimator_ada = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_n_estimator_ada.grid(row=1, column=2, padx=15, pady=10) # Assign the value to send to classifier #self.n_estimator_ada = self.entry_n_estimator_ada.get() # GradientBoosting elif self.selected_ML == "GradientBoosting": self.n_estimator_gb = IntVar() # Create n_estimators label self.label_n_estimators = Label(self.frame_ML, text="Number of trees:", font='Calibri 12 bold') self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10) # Create entry for user self.entry_n_estimator_gb = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_n_estimator_gb.grid(row=1, column=2, padx=15, pady=10) # Assign the value to send to classifier #self.n_estimator_gb = self.entry_n_estimator_gb.get() # Randomized trees elif self.selected_ML == "Randomized trees": self.n_estimator_rt = IntVar() # Create n_estimators label self.label_n_estimators = Label(self.frame_ML, text="Number of trees:", font='Calibri 12 bold') self.label_n_estimators.grid(row=0, column=2, padx=15, pady=10) # Create entry for user self.entry_n_estimator_rt = Entry(self.frame_ML, text=" Enter the value here ", borderwidth=8, width=10) self.entry_n_estimator_rt.grid(row=1, column=2, padx=15, pady=10) # Assign the value to send to classifier #self.n_estimator_rt = self.entry_n_estimator_rt.get() # Naive Bayes elif self.selected_ML == "Naive Bayes": pass # Logistic regression elif self.selected_ML == "Logistic regression": pass #%% Function: Help pop-up def help_pop_up_func(self): line1 = "Welcome to Zzzscoring!\n" line2 = "Pick the EDF files of interest and their corresponding hypnograms!\n" line3 = "** Notes:\n- hypnograms should be in .txt or .csv format.\n" line4 = "- The first and second column of hypnos are labels and artefact annotations, respecively.\n" line5 = "- Default labels should be as below:\n" line6 = "- Wake:0, N1: 1, N2: 2, SWS: 3, REM: 4.\n" line7 = "- Once pushing a button e,.g. 'Apply' or 'Train' the process is time-taking. One can follow the status of process in the console (e.g. command prompt).\n" line8 = "- After choosing a ML algorithm you should press 'Select' and then specify hyperparameters. After this, one is allowed to press 'Train' button.\n" line9 = "- Activating feature selection extend the process time. Don't forget to follow the status from console. " lines = line1 + line2 + line3 + line4 + line5 + line6 + line7 + line8 + line9 messagebox.showinfo(title="Help", message=lines) #%% Training function def Training_function(self): # Training perentage self.n_train = round(float(self.train_size) * len(data_files_list)) # ========================== Show reuslt ============================ # # Label self.label_results = Label(self.frame_ML, text="Train and prediction finished!", font='Calibri 12 bold') self.label_results.grid(row=0, column=4) # Activate results Button self.button_show_results = Button(self.frame_ML, text="Show results", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.show_results_function) self.button_show_results.grid(row=1, column=4) # ========================== Plot conf mat ========================== # # Activate plot confusion Button self.button_plot_conf = Button(self.frame_ML, text="Plot confusion mat", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.plot_conf_mat) self.button_plot_conf.grid(row=1, column=5) # ========================== Activate plot hypnogram ================ # self.button_plot_hyp = Button(self.frame_ML, text="Plot hypnograms", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.plot_hyp_function) self.button_plot_hyp.grid(row=2, column=4) #######=== Randomly shuffle subjects to choose train and test splits ===###### # ============================================================================= # subj_c = np.random.RandomState(seed=42).permutation(subj_c) # # ============================================================================= #######=============== Initialize train and test arrays ================####### global X_train, X_test, y_train, y_test X_train = np.empty((0, np.shape(self.Feat_all_channels)[1])) X_test = np.empty((0, np.shape(self.Feat_all_channels)[1])) y_train = np.empty((0, np.shape(self.yy)[1])) y_test = np.empty((0, np.shape(self.yy)[1])) ########======= Picking the train subjetcs and concatenate them =======######## for c_subj in data_files_list[0:self.n_train]: self.tmp_name = c_subj[-11:-4] # train hypnogram self.str_train_hyp = 'hyp' + str(self.tmp_name) # train featureset self.str_train_feat = 'subject' + str(self.tmp_name) # create template arrays for featurs and label self.tmp_x = subjects_dic[self.str_train_feat] self.tmp_y = hyp_dic[self.str_train_hyp] # Concatenate features and labels X_train = np.row_stack((X_train, self.tmp_x)) y_train = np.row_stack((y_train, self.tmp_y)) #del self.tmp_x, self.tmp_y, self.tmp_name, self.str_train_hyp, self.str_train_feat ########======== Picking the test subjetcs and concatenate them =======######## self.test_subjects_list = [] for c_subj in data_files_list[self.n_train:]: self.tmp_name = c_subj[-11:-4] # test hypnogram str_test_hyp = 'hyp' + str(self.tmp_name) # test featureset str_test_feat = 'subject' + str(self.tmp_name) # create template arrays for featurs and label self.tmp_x = subjects_dic[str_test_feat] self.tmp_y = hyp_dic[str_test_hyp] # Concatenate features and labels X_test = np.row_stack((X_test, self.tmp_x)) y_test = np.row_stack((y_test, self.tmp_y)) # keep the subject id self.test_subjects_list.append(str_test_feat) # remove for next iteration #del self.tmp_x, self.tmp_y,self.tmp_name, self.str_test_feat, self.str_test_hyp ################# FOR NOW WE IGNOR MOVEMENT AROUSAL ################### y_train = y_train[:, :5] y_test = y_test[:, :5] # ========================= Time-dependency ========================= # global X_train_td, X_test_td if int(self.td_var.get()) == 1: X_train_td = self.Object.add_time_dependence_backward( X_train, n_time_dependence=int(self.entry_td.get()), padding_type='sequential') X_test_td = self.Object.add_time_dependence_backward( X_test, n_time_dependence=int(self.entry_td.get()), padding_type='sequential') # ======================== Feature selection ======================== # self.y_train_td = self.Object.binary_to_single_column_label(y_train) # Check activation of flag if int(self.feat_select_var.get()) == 1: # ============================================================================= # tmp1,tmp2,self.selected_feats_ind = self.Object.FeatSelect_Boruta(self.X_train_td, y_train, max_iter = 50) # X_train = self.X_train_td[:, self.selected_feats_ind] # X_test = self.X_test_td[:, self.selected_feats_ind] # ============================================================================= tmp1, tmp2, self.selected_feats_ind = self.Object.FeatSelect_Boruta( X_train, self.y_train_td[:, 0], max_iter=50) X_train = X_train[:, self.selected_feats_ind] X_test = X_test[:, self.selected_feats_ind] ######## ================= Apply chosen ML ================= ########## global y_pred # SVM if self.selected_ML == "SVM": y_pred = self.Object.KernelSVM_Modelling(X_train, y_train, X_test, y_test, kernel=self.kernel_.get()) y_pred = np.expand_dims(y_pred, axis=1) # One hot encoding # Random forest elif self.selected_ML == "Random forest": y_pred = self.Object.RandomForest_Modelling( X_train, y_train, X_test, y_test, n_estimators=int(self.entry_n_estimator_RF.get())) #y_pred = self.Object.RandomForest_Modelling(X_train, y_train, X_test, y_test, n_estimators = 10) self.Object.multi_label_confusion_matrix(y_test, y_pred, print_results='on') # XGB elif self.selected_ML == "XGBoost": y_pred = self.Object.XGB_Modelling( X_train, y_train, X_test, y_test, n_estimators=int(self.entry_n_estimator_xgb.get()), max_depth=3, learning_rate=.1) # ADABoost elif self.selected_ML == "ADABoost": y_pred = self.Object.ADAboost_Modelling( X_train, y_train, X_test, y_test, n_estimators=int(self.entry_n_estimator_ada.get())) # GRadient Boosting elif self.selected_ML == "GradientBoosting": y_pred = self.Object.gradient_boosting_classifier( X_train, y_train, X_test, y_test, n_estimators=int(self.entry_n_estimator_gb.get()), learning_rate=1.0, max_depth=1) # Randomized trees elif self.selected_ML == "Randomized trees": y_pred = self.Object.Extra_randomized_trees( X_train, y_train, X_test, y_test, n_estimators=int(self.entry_n_estimator_rt.get()), max_depth=None, min_samples_split=2, max_features="sqrt") #%% Def show_results function def show_results_function(self): from sklearn.metrics import multilabel_confusion_matrix, cohen_kappa_score #### =================== Create results window ================#### self.results_win = Toplevel() self.results_win.title("Results of classification") # Label self.label_results_win = Label(self.results_win, text="Results were found as below:\n", font='Calibri 16 bold') self.label_results_win.pack() self.close_res_win = Button(self.results_win, text="Dismiss", command=self.results_win.destroy) self.close_res_win.pack() # ============================================================================= # try: # if np.shape(y_test)[1] != np.shape(y_pred)[1]: # self.y_true = self.Object.binary_to_single_column_label(y_test) # except IndexError: # y_test = self.Object.binary_to_single_column_label(y_test) # ============================================================================= self.mcm = multilabel_confusion_matrix(y_test, y_pred) self.tn = self.mcm[:, 0, 0] self.tp = self.mcm[:, 1, 1] self.fn = self.mcm[:, 1, 0] self.fp = self.mcm[:, 0, 1] self.Recall = self.tp / (self.tp + self.fn) self.prec = self.tp / (self.tp + self.fp) self.f1_sc = 2 * self.Recall * self.prec / (self.Recall + self.prec) self.Acc = (self.tp + self.tn) / (self.tp + self.fp + self.fn + self.tn) #kappa = cohen_kappa_score(y_true, y_pred) self.label_res1 = Label( self.results_win, text="Accuracy for Wake,N1,N2,N3,REM were respectively:" + str(self.Acc), font='Calibri 12 bold').pack() self.label_res2 = Label( self.results_win, text="Precision for Wake,N1,N2,N3,REM were respectively:" + str(self.prec), font='Calibri 12 bold').pack() self.label_res3 = Label( self.results_win, text="Recall for Wake,N1,N2,N3,REM were respectively:" + str(self.Recall), font='Calibri 12 bold').pack() self.label_res4 = Label( self.results_win, text="F1-score for Wake,N1,N2,N3,REM were respectively:" + str(self.f1_sc), font='Calibri 12 bold').pack() #%% Plot confusion matrix def plot_conf_mat(self): self.Object.plot_confusion_matrix( y_test, y_pred, target_names=['Wake', 'N1', 'N2', 'SWS', 'REM'], title='Confusion matrix of ssccoorriinngg algorithm', cmap=None, normalize=True) #%% Plot hypnograms def plot_hyp_function(self): self.hyp_true = self.Object.binary_to_single_column_label(y_test) self.hyp_pred = self.Object.binary_to_single_column_label(y_pred) self.Object.plot_comparative_hyp(self.hyp_true, self.hyp_pred, mark_REM='active', Title='True Hypnogram')
class OptimizerMainWindow: """ classdocs """ # TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"]) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode="w") as fd: fd.write(self.optimizer.optimizedSequence)
def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb if isinstance(options, dict) and 'label' in list(options.keys()): label = options['label'] else: label = cb[9:] if cb[:9] == 'automate_' else cb setattr(self, name, IntVar( value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W)
def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop()
def create_files_list_frame(self): files_list_frame = LabelFrame(self.root, text='Files to merge') self.FilesList = Listbox(files_list_frame) self.FilesList.pack(side='left', fill='both', expand=1) files_list_frame.pack(fill='x')
num = arr[i] if num == 0: label['text'] = 'Хипхоп' if num == 6: label['text'] = 'Электроника' if num == 2: label['text'] = 'Джаз' if num == 3: label['text'] = 'Рок' if num == 4: label['text'] = 'Классика' def deleteText(): text.delete(1.0, END) label['text'] = '' root = Tk() root.title("Определитель жанра 1.3") f_top = LabelFrame(root) f_top = LabelFrame( text="Путь к файлу(Желательно использование форматов wav или flac):") f_top.pack(padx=10, pady=10) text = Text(f_top, width=50, height=1) text.pack() label = Label(f_top) label.pack() frame = Frame() frame.pack() b_get = Button(frame, text="Определить жанр", command=getText) b_get.pack(side=LEFT)
class Editor: def __init__(self): # Initialize the text editor self.root = tk.Tk(className='Tekstieditori') # Text editor text area self.textpad = tkst.ScrolledText(self.root, width=100, height=36, highlightthickness=0) # Text area, inner padding and font config added self.textpad.config(font=('tkDefaultFont', 16, 'normal'), padx=10, pady=10) # Add text area to parent self.textpad.pack() # Create a file menu in menu bar self.menu = Menu(self.root) self.filemenu = Menu(self.menu) self.file_menu_conf() self.file = {} # Initialize the selection index class variable self.sel_index = [0, 1] # Configurate click events self.event_config() def open(self): """ File open dialog, used via a file menu in menu bar TODO(maybe): open when no file is opened """ # Redirect user to save when there's data in textarea if len(self.textpad.get("1.0", tk.END+'-1c')) == 0: # Ask the user for a file to open userinput = tk.filedialog.askopenfilename(parent=self.root, title='Valitse tiedosto') # Wait for user input if userinput is None or userinput is "": self.open() else: # Use the fileSystem class for all file operations self.file = File(userinput) contents = self.file.read() # Empty the editor self.textpad.delete('1.0', tk.END+'-1c') # Insert the contents to the editor self.textpad.insert('1.0', contents) # Populate with existing tags self.populate_tags() else: self.save() def file_menu_conf(self): """ File menu configuration, add the menu buttons. """ self.root.config(menu=self.menu) self.menu.add_cascade(label="Tiedosto", menu=self.filemenu) self.filemenu.add_command(label="Avaa..", command=self.open) self.filemenu.add_command(label="Tallenna", command=self.save) self.filemenu.add_separator() self.filemenu.add_command(label="Poistu", command=self.exit) def create_window(self, event): """ Popup window which is used for adding and reading tags. Opened with a right click on selected text, contains an entry field, which shows existing tags, and can be used to add new ones. """ if hasattr(self.file, 'path'): # Create a new popup window self.t = Toplevel(self.root) self.t.title("Lisää tägi") # Get the selection index before # inserting its tags in the entry field self.get_index() # Get existing tags self.get_this_tag_list() # Tag entry field self.e = Entry(self.t) self.e.pack() # Tag submit button self.b = Button(self.t, text="Lisää tägi", command=self.entry_callback) self.b.pack() else: self.save() def save(self): """ Save the original file or create a new one, if there's no file opened already. """ # Open the file dialog userinput = tk.filedialog.asksaveasfilename() # Wait for user input if userinput is not None: self.file = File(userinput) # Get text editor contents data = self.textpad.get('1.0', tk.END+'-1c') # Write data to file self.file.write(data) def exit(self): """ Exit command, which is called whenever user wants to close the whole editor. """ self.root.protocol('WM_DELETE_WINDOW', self.exit) if tk.messagebox.askokcancel("Poistu", "Haluatko todella poistua?"): self.root.destroy() def populate_tags(self): """ Get existing tags from the tag file, and print them with tkinter tag_add as yellow highlighted areas in the text. """ for tag in self.textpad.tag_names(): self.textpad.tag_delete(tag) for tag in self.file.readtags(): if len(tag) > 0: for contents in tag["tag"]: print(contents) print(tag["index"]) self.textpad.tag_add(contents, tag["index"][0], tag["index"][1]) # Muted yellow accent for tags self.textpad.tag_config(contents, background="yellow", bgstipple="gray50") # Lower all incoming tags, # so that selection always shows self.textpad.tag_lower(contents) def get_this_tag_list(self): if hasattr(self, "taglist"): self.taglist.destroy() self.taglist = LabelFrame(self.t) self.taglist.pack() # Get existing tags try: existing_tags = [Button(self.taglist, text=tag, background="yellow", command=lambda: self.delete_existing_tag(tag, self.sel_index)) for tag in self.file.get_tags_by_index(self.sel_index)] for tag in existing_tags: tag.pack() except TypeError: # Greeting, if no tags are present print("No tags in this index") def entry_callback(self): """ Callback event for adding a tag. Called when the tag submit button is pressed, because tkinter button event can't have any input. """ self.add_tag(self.e.get()) self.get_this_tag_list() def add_tag(self, description): """ GUI implementation of tagging. Uses the filesystem for saving tags to a file, and saves new tags graphically with tkinter tag_add() """ try: # Add the tag(s) graphically to the text self.textpad.tag_add(description, self.sel_index[0], self.sel_index[1]) # Muted yellow accent for tags self.textpad.tag_config(description, background="yellow", bgstipple="gray50") # Lower all incoming tags, # so that selection always shows self.textpad.tag_lower(description) # Add the tag(s) to original file's tag file in data/ self.file.tag(description, self.sel_index) except Exception: # When something goes wrong... print("...Whoooops...") def delete_existing_tag(self, description, index): self.file.remove_tag(description, index) self.get_this_tag_list() self.populate_tags() def get_index(self): """ Get the indeces of selected text. Used whenever and before any new tags are added. """ try: self.sel_index = [self.textpad.index("sel.first"), self.textpad.index("sel.last")] except tk.TclError: # Error, which is raised when no selection indeces are present. print("You need to select something + \ before getting selection index!") def event_config(self): # self.textpad.bind("<Button-2>", self.create_window) # Remove unnecessary copy and paste on second mouse click self.root.bind_class("Text", sequence='<Button-2>', func=self.create_window)
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.reserve_time = StringVar() self.reserve_date = StringVar() self.success = StringVar() self.success.set("No") self.counter = IntVar() self.counter.set(0) self.run_flag = IntVar() self.run_flag.set(0) self.T = {} self.message_count_down = False self.show_notice = True self.successed_info = [] self.Config_Path = self.controller.Config_Path self.Cookie_Path = self.controller.Cookie_Path self.frame_1 = LabelFrame( self, text="选择预定日期与开始时间(点击自动选择并查询)", height=100, width=630 ) self.day = 0 self.days = {} self.choose_days = {} for i in range(7): _today = date.today() self.days[i] = StringVar() _day = _today + timedelta(days=i) _day = _day.strftime("%Y-%m-%d") self.days[i].set(_day) self.choose_days[i] = Radiobutton( self.frame_1, text=self.days[i].get(), variable=self.reserve_date, value=self.days[i].get(), command=partial(self.set_reserve_date, i), ) self.times = {} self.choose_times = {} for i in range(7): self.times[i] = StringVar() _time = "{0:02d}:00:00".format(8 + 2 * i) self.times[i].set(_time) self.choose_times[i] = Radiobutton( self.frame_1, text=self.times[i].get(), variable=self.reserve_time, value=self.times[i].get(), command=self.set_reserve_time, ) # ------------------- self.frame_2 = LabelFrame(self, height=150, width=630) self.label_date_1 = Label(self.frame_2, text="预定日期:", anchor=E) self.label_date_2 = Label( self.frame_2, textvariable=self.reserve_date, anchor=W ) self.label_time_1 = Label(self.frame_2, text="预定时间段(2小时):", anchor=E) self.label_time_2 = Label( self.frame_2, textvariable=self.reserve_time, anchor=W ) self.label_couner = Label(self.frame_2, text="刷新次数:", anchor=E) self.couner_num = Label(self.frame_2, textvariable=self.counter) self.label_sucessed = Label(self.frame_2, text="是否预定成功?:", anchor=E) self.is_sucessed = Label(self.frame_2, bg="Red", textvariable=self.success) self.button_start = Button( self.frame_2, text="开始监控", bg="SpringGreen", command=self.start_job ) self.button_stop = Button( self.frame_2, text="结束", state=DISABLED, bg="LightGray", command=self.stop_job, ) self.label_notice = Label(self.frame_2, text="显示警告与提示?", anchor=E) self.button_notice = Button( self.frame_2, text="是", bg="Pink", command=self.turn_on_notice ) self.label_sucessed_place = Label(self.frame_2, text="预定成功的场地:", anchor=E) self.label_successed_place_info = Label(self.frame_2) # ------------------- self.frame_3 = LabelFrame(self, text="场地状态(点击刷新)", height=600, width=630) self.courts = {} self.show_courts = {} for i in range(8): self.courts[i] = IntVar() self.courts[i].set("") self.show_courts[i] = Button( self.frame_3, font=("Helvetica 10"), text="{}号场地".format(i + 1), command=self.get_status, ) self.create_page()
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((host, port)) self.grid() self.columnconfigure(0, minsize=100) self.columnconfigure(1, minsize=200) self.columnconfigure(2, minsize=200) self.columnconfigure(3, minsize=150) self.columnconfigure(4, minsize=150) self.columnconfigure(5, minsize=150) self.columnconfigure(6, minsize=150) self.create_widgets() self.settables = self.assemble_settables() self.gui_logger = logging.getLogger('gui') self.request_update() def create_widgets(self): self.create_monitor() self.create_check_buttons() self.create_ranges() self.create_scales() self.create_radio_buttons() self.create_voices() self.quitButton = Button(self, text='Quit', command=self.quit) self.quitButton.grid(columnspan=7, sticky=E + W) def assemble_settables(self): settables = self.winfo_children() for w in settables: settables += w.winfo_children() return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']] def create_radio_buttons(self): # Scale related entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR', 'GREEK_CHROMATIC', 'GREEK_ENHARMONIC'] self.scale = StringVar() self.scale.set('DIATONIC') self.rb_frame = Frame(self) for e in entries: rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W, command=self.send_scale, variable=self.scale) rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W) self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3) def create_monitor(self): self.monitor_frame = LabelFrame(self, text="Monitor and Transport") this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL, from_=1, to=16, resolution=1) this_cycle.disable, this_cycle.enable = (None, None) this_cycle.ref = 'cycle_pos' this_cycle.grid(column=0, row=0, sticky=E + W) self.updateButton = Button(self.monitor_frame, text='Reload all Settings', command=self.request_update) self.updateButton.grid(row=1, sticky=E + W) self.ForceCaesuraButton = Button(self.monitor_frame, text='Force Caesura', command=self.force_caesura) self.ForceCaesuraButton.grid(row=2, sticky=E + W) self.saveBehaviourButton = Button(self.monitor_frame, text='Save current behaviour', command=self.request_saving_behaviour) self.saveBehaviourButton.grid(row=3, sticky=E + W) self.saveBehaviourNameEntry = Entry(self.monitor_frame) self.saveBehaviourNameEntry.grid(row=4, sticky=E + W) self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour) self.selected_behaviour = StringVar() self.selected_behaviour.trace('w', self.new_behaviour_chosen) self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, None,) self.savedBehavioursMenu.grid(row=5, sticky=E + W) self.monitor_frame.grid(column=0, row=10, sticky=E + W) def request_update(self): self.send({'sys': 'update'}) def request_saving_behaviour(self, event=None): """callback for save behaviour button and textentry""" if event and event.widget == self.saveBehaviourNameEntry: if event.keysym == 'Return': name = self.saveBehaviourNameEntry.get() self.saveBehaviourNameEntry.delete(0, len(name)) else: return else: # button was pressed name = self.saveBehaviourNameEntry.get() if name: self.send({'sys': ['save_behaviour', name]}) def force_caesura(self): self.send({'force_caesura': True}) def create_voices(self): voice_ids = ['1', '2', '3', '4'] SCALES = OrderedDict([ ('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}), ('volume', {'min': 0, 'max': 1, 'start': 0.666, 'res': 0.001}), ('slide_duration_msecs', {'min': 0, 'max': 2000, 'start': 60, 'res': 1}), ('slide_duration_prop', {'min': 0, 'max': 2, 'start': 0.666, 'res': 0.001}), ('binaural_diff', {'min': 0, 'max': 66, 'start': 0.2, 'res': 0.01}) ]) for vid in voice_ids: counter = 0 for sca in SCALES: name = 'voice_' + vid + '_' + sca setattr(self, 'min_' + name, SCALES[sca]['min']) setattr(self, 'max_' + name, SCALES[sca]['max']) this_sca = Scale(self, label=sca, orient=HORIZONTAL, from_=getattr(self, 'min_' + name), to=getattr(self, 'max_' + name), resolution=SCALES[sca]['res']) this_sca.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) this_sca.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) this_sca.grid(column=int(2 + int(vid)), row=counter, sticky=E + W) this_sca.bind("<ButtonRelease>", self.scale_handler) this_sca.ref = name counter += 1 CHECK_BUTTONS = OrderedDict( [('mute', False), ('automate_binaural_diffs', True), ('automate_note_duration_prop', True), ('use_proportional_slide_duration', {'val': True, 'label': 'proportional slide'}), ('automate_pan', True), ('automate_wavetables', True)]) for vid in voice_ids: counter = 0 cb_frame = LabelFrame(self, text="Voice {0} - Automation".format(vid)) setattr(self, 'voice_' + vid + '_cb_frame', cb_frame) for cb in CHECK_BUTTONS: options = CHECK_BUTTONS[cb] name = 'voice_' + vid + '_' + cb if isinstance(options, dict) and 'label' in list(options.keys()): label = options['label'] else: label = cb[9:] if cb[:9] == 'automate_' else cb setattr(self, name, IntVar( value=type(options) == dict and options['val'] or options)) self.this_cb = Checkbutton(cb_frame, text=label, variable=getattr(self, name)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = None self.this_cb.grid(sticky=W, column=0, row=counter) self.this_cb.ref = name counter += 1 # add trigger wavetable-button trigWavetableButton = Button(cb_frame, text='Next Wavetable') trigWavetableButton.bind('<Button-1>', self.trigger_waveform_handler) trigWavetableButton.ref = 'voice_' + vid + "_trigger_wavetable" trigWavetableButton.grid(row=counter) cb_frame.grid(column=int(vid) + 2, row=5, sticky=E + W + N, rowspan=8) for vid in voice_ids: generation_types = ["random", "random_harmonic", "harmonic"] partial_pools = ["even", "odd", "all"] prefix = 'voice_' + vid + '_' types_name = prefix + 'wavetable_generation_type' pools_name = prefix + 'partial_pool' setattr(self, types_name, StringVar()) getattr(self, types_name).set("random") setattr(self, pools_name, StringVar()) getattr(self, pools_name).set("all") target_frame = getattr(self, 'voice_' + vid + '_cb_frame') gen_typ_frame = LabelFrame(target_frame, text="type") gen_typ_frame.grid(row=len(target_frame.winfo_children()), sticky=W) for gen_t in generation_types: gen_t_entry = Radiobutton(gen_typ_frame, value=gen_t, text=gen_t, anchor=W, variable=getattr(self, types_name)) gen_t_entry.bind('<ButtonRelease-1>', self.wt_handler) gen_t_entry.ref = types_name gen_t_entry.grid(row=len(gen_typ_frame.winfo_children()), sticky=W) pp_frame = LabelFrame(target_frame, text="harmonics") for pp in partial_pools: pp_entry = Radiobutton(pp_frame, value=pp, text=pp, anchor=W, variable=getattr(self, pools_name)) pp_entry.bind('<ButtonRelease-1>', self.wt_handler) pp_entry.ref = pools_name pp_entry.grid(row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials = Scale(pp_frame, label='number of harmonics', orient=HORIZONTAL, from_=1, to=24, resolution=1) this_num_partials.ref = prefix + 'num_partials' this_num_partials.grid(column=0, row=len(pp_frame.winfo_children()), sticky=E + W) this_num_partials.bind("<ButtonRelease>", self.scale_handler) pp_frame.grid(row=len(target_frame.winfo_children()), sticky=E + W) def wt_handler(self, event): print(event.widget.tk) ref = event.widget.ref self.send({ref: getattr(self, ref).get()}) def create_check_buttons(self): self.cb_frame = LabelFrame(self, text="Global Settings") for cb in CHECK_BUTTONS: label = cb target_parent = self.cb_frame if isinstance(CHECK_BUTTONS[cb], dict) and 'sub_frame' in list(CHECK_BUTTONS[cb].keys()): target_parent = getattr(self, CHECK_BUTTONS[cb]['sub_frame']) setattr(self, cb, IntVar(value=type(CHECK_BUTTONS[cb]) == dict and CHECK_BUTTONS[cb]['val'] or CHECK_BUTTONS[cb])) self.this_cb = Checkbutton(target_parent, text=label, variable=getattr(self, cb)) self.this_cb.bind('<Button-1>', self.check_boxes_handler) self.this_cb.disable = (type(CHECK_BUTTONS[cb]) == dict and 'disable' in list(CHECK_BUTTONS[cb].keys())) self.this_cb.grid(sticky=W, column=0, row=len(target_parent.winfo_children())) self.this_cb.ref = cb for but in GLOBAL_BUTTONS: label = but ele = GLOBAL_BUTTONS[but] this_but = Button(self.cb_frame, text=but) this_but.bind('<ButtonRelease-1>', getattr(self, ele['handler'])) this_but.ref = but this_but.grid(sticky=W, column=0, row=len(self.cb_frame.winfo_children())) self.cb_frame.grid(column=0, row=0, rowspan=10, sticky=N) def new_behaviour_chosen(self, a, b, c): self.send({'sys': ['change_behaviour', self.selected_behaviour.get()]}) def set_value(self, name, val): '''sets a widget to the specified value various different widget types need custom setting functionality''' direct = ['scale', 'wavetable_generation_type', 'partial_pool'] if [x for x in direct if match("(voice_\d_|)" + x, name)]: self.gui_logger.info("setting: '{0}' to '{1}' in GUI".format(name, val)) getattr(self, name).set(val) return if name == 'saved_behaviours' and len(val): self.savedBehavioursMenu.destroy() self.savedBehavioursMenu = OptionMenu(self.monitor_frame, self.selected_behaviour, *sorted(val)) self.savedBehavioursMenu.grid(row=5, sticky=E + W) return for w in self.settables: typ = w.__class__.__name__ if w.ref == name: # print "setting '{0}' of type: '{1}' to: {2}".format(name, typ, val) if typ == 'Scale': w.set(val) elif typ == "Checkbutton": w.select() if val else w.deselect() def check_boxes_handler(self, event): '''handles checkbox events. shows and hides gui elements according to their enable/disable fields''' # print event.__dict__ # print event.widget.__dict__ ref = event.widget.ref val = not getattr(self, ref).get() # because is read before the var is changed self.send({ref: val}) # print ref, val # handle gui elements # enable/disable functionality temporarily(?) commented on: # Wed Aug 17 09:39:54 CEST 2011 # if event.widget.disable: # for w in self.children.values(): # # # this try clause is for debugging, remove when stable # try: # w.ref # #print w.ref # except: # pass # if (w.__class__.__name__ == 'Scale' and # (w.disable or w.enable)): # if w.disable == ref: # if val: # w.grid() # else: # w.grid_remove() # elif w.enable == ref: # if val: # w.grid_remove() # else: # w.grid() # #print w.disable, w.enable def create_scales(self): counter = 0 for sca in SCALES: label = SCALES[sca]['label'] if 'label' in list(SCALES[sca].keys()) else sca setattr(self, 'min_' + sca, SCALES[sca]['min']) setattr(self, 'max_' + sca, SCALES[sca]['max']) self.this_scale = Scale(self, label=label, orient=HORIZONTAL, from_=getattr(self, 'min_' + sca), to=getattr(self, 'max_' + sca), resolution=SCALES[sca]['res']) self.this_scale.set(SCALES[sca]['start']) self.this_scale.enable = ('enable' in list(SCALES[sca].keys()) and SCALES[sca]['enable'] or None) self.this_scale.disable = ('disable' in list(SCALES[sca].keys()) and SCALES[sca]['disable'] or None) if 'pos' in list(SCALES[sca].keys()): pos = SCALES[sca]['pos'] col = pos['c'] row = pos['r'] else: row = counter col = 1 counter += 1 self.this_scale.grid(column=col, row=row, sticky=E + W) self.this_scale.ref = sca self.this_scale.bind("<ButtonRelease>", self.scale_handler) def scale_handler(self, event): self.send({event.widget.ref: event.widget.get()}) self.gui_logger.info("handling scale: {0}, with new value: {1}".format( event.widget.ref, event.widget.get())) def trigger_waveform_handler(self, event): self.send({event.widget.ref: True}) # print event.widget.ref, "- triggering wavetable" def send_scale(self): do = {'scale': self.scale.get()} self.send(do) def send(self, msg): self.gui_logger.info("sending: {0}".format(msg)) self.send_sock.sendto(json.dumps(msg), (remote_host, send_port)) def create_ranges(self): counter = 0 for ran in RANGES: setattr(self, 'min_' + ran, RANGES[ran]['min']) setattr(self, 'max_' + ran, RANGES[ran]['max']) self.this_min_scale = Scale(self, label='min ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_max_scale = Scale(self, label='max ' + ran, orient=HORIZONTAL, from_=getattr(self, 'min_' + ran), to=getattr(self, 'max_' + ran), resolution=RANGES[ran]['res']) self.this_min_scale.set(RANGES[ran]['min_start']) self.this_max_scale.set(RANGES[ran]['max_start']) self.this_min_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_min_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_max_scale.enable = ('enable' in list(RANGES[ran].keys()) and RANGES[ran]['enable'] or None) self.this_max_scale.disable = ('disable' in list(RANGES[ran].keys()) and RANGES[ran]['disable'] or None) self.this_min_scale.grid(column=2, row=counter, sticky=E + W) self.this_max_scale.grid(column=2, row=counter + 1, sticky=E + W) self.this_min_scale.ref = 'min_' + ran self.this_max_scale.ref = 'max_' + ran self.this_min_scale.bind("<ButtonRelease>", self.scale_handler) self.this_max_scale.bind("<ButtonRelease>", self.scale_handler) counter += 2 def socket_read_handler(self, file, mask): data_object = json.loads(file.recv(1024)) do = list(data_object.items())[0] self.set_value(do[0], do[1])
def __init__(self, master): self.master = master master.title("Zzzscoring: Automatic sleep scoring package") #### !!~~~~~~~~~~~~~~~~~ DEFINE INPUT DATAFRAME ~~~~~~~~~~~~~~~~~!!#### self.frame_import = LabelFrame(self.master, text="Import files section", padx=150, pady=100, font='Calibri 18 bold') self.frame_import.grid(row=0, column=0, padx=200, pady=50, columnspan=8) #### ==================== Help pop-up button ======================#### self.popup_button = Button(self.master, text="Help", command=self.help_pop_up_func, font='Calibri 13 bold', fg='white', bg='black') self.popup_button.grid(row=1, column=8) #### ==================== Import data EDFs ========================#### # Label: Import EDF self.label_import = Label(self.frame_import, text="Import EDF files here:", font='Calibri 12 bold') self.label_import.grid(row=0, column=0, padx=15, pady=10) # Button: Import EDF (Browse) self.button_import_browse = Button(self.frame_import, text="Browse data", padx=100, pady=20, font='Calibri 10 bold', command=self.load_data_file_dialog, fg='blue', relief=RIDGE) self.button_import_browse.grid(row=1, column=0, padx=15, pady=10) #### ================== Import hypnogram files ====================#### # Show a message about hypnograms self.label_hypnos = Label(self.frame_import, text="Import hypnogram file (.txt) here:", font='Calibri 12 bold') self.label_hypnos.grid(row=0, column=1, padx=15, pady=10) # Define browse button to import hypnos self.button_hypnos_browse = Button(self.frame_import, text="Browse labels", padx=100, pady=20, font='Calibri 10 bold', command=self.load_hypno_file_dialog, fg='blue', relief=RIDGE) self.button_hypnos_browse.grid(row=1, column=1, padx=15, pady=10) #### ===================== Define train size ======================#### # Define train size section self.label_train_size = Label( self.frame_import, text="Train size portion (between 0 - 1):", font='Calibri 12 bold') self.label_train_size.grid(row=0, column=3, padx=15, pady=10) # Bar to ask for user's entry self.train_size = DoubleVar() self.entry_train_size = Entry(self.frame_import, text=" Enter the value here ", borderwidth=8, width=10) self.entry_train_size.grid(row=1, column=3, padx=15, pady=10) #### =================== Push apply to load data ==================#### #Label to read data and extract features self.label_apply = Label( self.frame_import, text="Press to Load, pre-process, and extract features!", font='Calibri 12 bold') self.label_apply.grid(row=0, column=4) # Apply button self.button_apply = Button(self.frame_import, text="Apply", padx=100, pady=20, font='Calibri 10 bold', relief=RIDGE, fg='blue', command=self.Apply_button) self.button_apply.grid(row=1, column=4, padx=15, pady=10) #### !!~~~~~~~~~~~~~~ DEFINE ML SECTION FRAME ~~~~~~~~~~~~~~~~~~~!!#### self.frame_ML = LabelFrame(self.master, text="Machine Learning Section", padx=150, pady=100, font='Calibri 18 bold') self.frame_ML.grid(row=1, column=0, padx=200, pady=50, columnspan=8) #### ================ Pick ML Algorithm of interest ===============#### # Label self.label_ML_algorithm = Label( self.frame_ML, text="Choose the machine learning algorithm:", font='Calibri 12 bold') self.label_ML_algorithm.grid(row=0, column=0, padx=15, pady=10) # Dropdown menu self.selected_ML = StringVar() self.selected_ML.set("Random forest") self.drop = OptionMenu(self.frame_ML, self.selected_ML, "SVM", "Random forest", "XGBoost", "Logistic regression", "Naive bayes", "Randomized trees", "GradientBoosting", "ADABoost") self.drop.grid(row=1, column=0) self.drop.config(font='Calibri 10 bold', fg='blue') # label_selec self.label_select = Label(self.frame_ML, text="Press after choosing ML algorithm:", font='Calibri 12 bold') self.label_select.grid(row=0, column=1) # select button self.button_select = Button(self.frame_ML, text="Select!", padx=100, pady=20, font='Calibri 12 bold', relief=RIDGE, fg='blue', command=self.Select_ML_button) self.button_select.grid(row=1, column=1, padx=15, pady=10) # Chekbox for time-dependency self.td_var = IntVar() self.checkbox_td = Checkbutton(self.frame_ML, text="Multi-to-one classifcation", font='Calibri 12 bold', variable=self.td_var) self.checkbox_td.grid(row=2, column=0) # Chekbox for feature selection self.feat_select_var = IntVar() self.checkbox_feat_select = Checkbutton(self.frame_ML, text="Feature Selection", font='Calibri 12 bold', variable=self.feat_select_var) self.checkbox_feat_select.grid(row=3, column=0)
class Main: def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button def manage_config(self): if not os.path.isfile(os.path.expanduser("~\\documents\\lloader_cfg.ini")): with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.add_section('basic_config') # cfg file not exists so we make it config.set('basic_config', 'save_folder', self.save_folder) config.set('basic_config', 'html_tag1', ".filecontainer figcaption a") config.set('basic_config', 'html_tag2', ".filecontainer .file a") config.set('basic_config', 'url_1', "ylilauta.org") config.set('basic_config', 'url_2', "www.ylilauta.org") # .filecontainer .file a = ALL images (np included) but not mp4 # .filecontainer figcaption a = not np images, but all uploaded images & mp4 config.write(cfgfile) logger.debug("Created a config file") else: try: config.read(os.path.expanduser('~\\documents\\lloader_cfg.ini')) self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.save_folder = config.get('basic_config', 'save_folder') # get save folder from file self.folder_entry.insert(0, self.save_folder) # write to folder field self.folder_entry['state'] = 'readonly' # make it read-only again logger.debug("Read from config") except (IOError, OSError): logger.exception("Config error") except (configparser.MissingSectionHeaderError, configparser.NoSectionError): # correct section not found from file os.remove(os.path.expanduser("~\\documents\\lloader_cfg.ini")) self.manage_config() # delete file and try to create it from start def get_folder(self): dir_opt = options = {} # define options for get folder function options['initialdir'] = self.save_folder options['mustexist'] = False options['parent'] = self.master options['title'] = 'Choose a directory' self.save_folder = filedialog.askdirectory(**dir_opt) # actual function to get the folder name with open((os.path.expanduser("~\\documents\\lloader_cfg.ini")), 'w') as cfgfile: config.set('basic_config', 'save_folder', self.save_folder) config.write(cfgfile) # write new save folder to config file self.folder_entry['state'] = 'normal' # make the folder field writable self.folder_entry.delete(0, END) self.folder_entry.insert(0, self.save_folder) # update folder field self.folder_entry['state'] = 'readonly' # make it read-only again self.clear_savefolder_list() self.openfolderbutton['state'] = 'normal' # we can now press the open folder and url buttons self.urlbutton['state'] = 'normal' # because we have defined a save folder def openfolder(self): os.startfile(self.save_folder) # opens the save folder def clear_savefolder_list(self): del self.filenames[:] # clears the list of files in a folder self.filenames.append(next(os.walk(self.save_folder))[2]) # adds every file in folder to list def check_for_url(self): parse = urlparse(self.url_texti.lower()) # checks if url is ylilauta logging.debug("url started with %s" % parse.netloc) if (parse.netloc.startswith(self.url_1) or parse.netloc.startswith(self.url_2)): return True else: return False def is_image(self): if (self.image_url.lower().endswith(".jpg") or self.image_url.lower().endswith(".jpeg") or self.image_url.lower().endswith(".png")): # link seems to be image return True else: return False def is_mp4(self): if self.image_url.lower().endswith(".mp4"): # link ends in mp4 so its mp4 return True else: return False def is_mp3(self): if self.image_url.lower().endswith(".mp3"): # link ends in mp3 so its mp3 return True else: return False def we_want_it_anyway(self): if self.c2_selection.get() == 1: # checkbutton2 is selected so we want all files return True else: return False def getting_both(self): if self.r_selection.get() == 1: # first radio button is selected so dl both return True else: return False def getting_img(self): if self.r_selection.get() == 2: # second radio button is selected so dl images only return True else: return False def getting_mp4(self): if self.r_selection.get() == 3: # third radio button is selected so dl mp4 only return True else: return False def getting_mp3(self): if self.r_selection.get() == 4: # fourth radio button is selected so we get mp3 only return True else: return False def rename_file(self): get_filetype = os.path.splitext(os.path.basename(self.image_url))[1] # get filetype new_file_name_start = '' for i in range(0, 15): new_file_name_start += str(random.randint(0, 9)) # create random string of numbers self.name_of_file = (new_file_name_start + get_filetype) # create the whole new name def write_file(self): self.status_text.set('Downloading %s' % self.name_of_file) logger.info('Downloading %s' % self.name_of_file) self.master.update() self.res = requests.get(self.image_url) self.res.raise_for_status() try: with open(os.path.join(self.save_folder, self.name_of_file), 'wb') as self.imagefile: for chunk in self.res.iter_content(100000): self.imagefile.write(chunk) self.imagewritten = True except IOError: logger.exception("Exception with file write") self.status_text.set('File error') self.master.update() def file_get_logic(self): self.clear_savefolder_list() # need to update this list between files self.imagewritten = False # need to change this here because if same thread has same pictures if self.c1_selection.get() == 1: # if want new random name self.rename_file() else: self.name_of_file = os.path.basename(self.image_url) # using default filename if self.name_of_file in self.filenames[0]: # file exists if self.c2_selection.get() == 1: # we want to overwrite self.write_file() else: pass elif self.name_of_file not in self.filenames[0]: # file does not exist in folder self.write_file() # so we take it in self.master.update() def connect_logic(self): try: self.res = requests.get(self.url_texti, headers=self.headers, timeout=(10.0, self.read_timeout)) self.res.raise_for_status() except (requests.exceptions.ReadTimeout, requests.exceptions.HTTPError): logger.exception("Connection exception") self.status_text.set("Network error %s" % self.res.status_code) self.master.update() def logic(self): self.clear_savefolder_list() self.num_pics = 0 # make these 0 because we just called the function self.num_mp4 = 0 self.num_mp3 = 0 self.imagewritten = False self.url_texti = '' self.progressbar["value"] = 0 done = False if self.url_text != '': self.url_texti = (self.url_text.get()) # if url text is not empty we will set it to variable if not self.url_text or self.check_for_url() is False: # if url is wrong or empty self.status_text.set('URL not supported') logger.debug("URL is false: %s" % self.url_texti) while not done and self.check_for_url() is True: self.urlbutton['state'] = 'disabled' # disable buttons so they cant be pressed while run self.selectbutton['state'] = 'disabled' # we will enable them again in the end self.R1['state'] = 'disabled' self.R2['state'] = 'disabled' self.R3['state'] = 'disabled' self.R4['state'] = 'disabled' self.C1['state'] = 'disabled' self.C2['state'] = 'disabled' self.url_entry['state'] = 'readonly' self.status_text.set(("Getting from %s" % self.url_texti)) self.progressbar['value'] = 0 self.master.update() self.connect_logic() soup = bs4.BeautifulSoup(self.res.text, 'html.parser') # create soup total_stuff = 0 html_tag1 = config.get('basic_config', 'html_tag1') # we will fetch from these tags html_tag2 = config.get('basic_config', 'html_tag2') list_of_links = [] for imglink in soup.select(html_tag1): # grab items from tags and put them to list if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) for imglink in soup.select(html_tag2): if imglink.get('href') not in list_of_links: list_of_links.append(str(imglink.get('href'))) try: list_of_links = [x for x in list_of_links if x != "None"] # clear "none"s from list except ValueError: # there is no "none" in list pass total_stuff = len(list_of_links) # variable helps with progressbar logger.debug("total stuff is: %s" % total_stuff) for link in list_of_links: # iterate through list of links link = 'http:' + link # make item a valid link self.image_url = link # file get logic still uses global variable lol if (link.lower().endswith('.jpg') or link.lower().endswith('png') or link.lower().endswith('jpeg')): # we have an image if self.getting_both() or self.getting_img(): # we want an image self.file_get_logic() # we get an image if self.imagewritten: # logic is complete and image is written self.num_pics += 1 if link.lower().endswith('.mp4'): # same as above but with mp4 if self.getting_both() or self.getting_mp4(): self.file_get_logic() if self.imagewritten: self.num_mp4 += 1 if link.lower().endswith('.mp3'): if self.getting_both() or self.getting_mp3(): self.file_get_logic() if self.imagewritten: self.num_mp3 += 1 self.progressbar['value'] += 100 / total_stuff # progressbar fills self.status_text.set('Downloaded %s images, %s mp4, %s mp3.' % (self.num_pics, self.num_mp4, self.num_mp3)) self.urlbutton['state'] = 'normal' self.url_entry['state'] = 'normal' self.selectbutton['state'] = 'normal' self.R1['state'] = 'normal' self.R2['state'] = 'normal' self.R3['state'] = 'normal' self.R4['state'] = 'normal' self.C1['state'] = 'normal' self.C2['state'] = 'normal' # we have enabled all buttons to be used again logger.info("Done.") break logging.shutdown()
class App(): """ Start of the applications """ def __init__(self): self.__version__ = '0.2.1' # Larch self.mylarch = larch.Interpreter() self.root = Tk(className='EXAFS Neo GUI') self.root.wm_title("Graphical User Interface for EXAFS Analysis (Beta)") # Standard default geometry self.root.geometry("750x500") self.padx = 5 self.pady = 3 self.os = get_platform() base_folder = os.path.dirname(os.path.join(os.getcwd(),__file__)) icon_loc = os.path.join(base_folder,'media/icon.png') img = PhotoImage(file=icon_loc) self.root.tk.call('wm','iconphoto',self.root._w,img) # Set default font self.entryFont = Font(family="TkFixedFont", size=10) self.menuFont = Font(family="TkMenuFont",size=10) self.labelFont = Font(family="TkTextFont", size=11) # Generate the mainframe self.mainframe = ttk.Notebook(self.root,height=40,padding="5") self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) # Initalize variable self.initialize_var() self.initialize_tab() self.Build_tabs() def initialize_var(self): """ Initalize all possible variables in the gui. Future additions starts here. """ # Inputs self.data_file = StringVar(self.root,'Please choose a file') self.temp_data_file = StringVar(self.root,'Please choose a file') self.output_file = StringVar(self.root,'Please choose a file') self.ncomp = IntVar(self.root,'0') # Number of compounds self.feff_file = StringVar(self.root,'Please choose a directory') self.series = BooleanVar(self.root,'False') # Populations self.populations = IntVar(self.root,1000) self.num_gen = IntVar(self.root,100) self.best_sample = IntVar(self.root,20) self.lucky_few = IntVar(self.root,20) # Mutations self.chance_of_mutation = IntVar(self.root,20) self.orginal_chance_of_mutation = IntVar(self.root,20) self.chance_of_mutation_e0 = IntVar(self.root,20) self.mutation_options = IntVar(self.root,0) # Paths self.individual_path = BooleanVar(self.root,True) self.path_range = IntVar(self.root,20) temp_list = ",".join(np.char.mod('%i', np.arange(1,self.path_range.get()+1))) self.path_list = StringVar(self.root,temp_list) self.path_optimize = BooleanVar(self.root,False) self.path_optimize_pert = DoubleVar(self.root,0.01) self.path_optimize_only = BooleanVar(self.root,False) # Larch Paths self.kmin = DoubleVar(self.root,2.5) self.kmax = DoubleVar(self.root,15) self.k_weight = DoubleVar(self.root,2) self.delta_k = DoubleVar(self.root,0.05) self.r_bkg = DoubleVar(self.root,1.0) self.bkg_kw = DoubleVar(self.root, 1.0) self.bkg_kmax = DoubleVar(self.root, 15) #Outputs self.print_graph = BooleanVar(self.root, False) self.num_output_paths = BooleanVar(self.root, True) self.steady_state_exit = BooleanVar(self.root, True) # Pertubutuions self.n_ini = IntVar(self.root,100) def initialize_tab(self): """ Initialize tab for the main frame. more tabs """ s = ttk.Style() s.configure('TNotebook.Tab', font=('TkHeadingFont','11') ) height=1 self.tab_Inputs = tk.Frame(self.mainframe,height=height) self.tab_Populations = tk.Frame(self.mainframe,height=height) self.tab_Paths = tk.Frame(self.mainframe,height=height) self.tab_Mutation = tk.Frame(self.mainframe,height=height) self.tab_Larch = tk.Frame(self.mainframe,height=height) self.tab_Bkg = tk.Frame(self.mainframe,height=height) self.tab_Output = tk.Frame(self.mainframe,height=height) self.tab_Analysis = tk.Frame(self.mainframe,height=height) self.tab_Expert = tk.Frame(self.mainframe,height=height) # Add all the secondary tabs on the top window self.mainframe.add(self.tab_Inputs, text="Inputs") self.mainframe.add(self.tab_Populations, text="Populations") self.mainframe.add(self.tab_Paths, text="Paths") self.mainframe.add(self.tab_Mutation, text="Mutations") self.mainframe.add(self.tab_Larch, text="Larch") self.mainframe.add(self.tab_Bkg, text="Background Plots") self.mainframe.add(self.tab_Output, text="Outputs") self.mainframe.add(self.tab_Analysis, text='Analysis') self.mainframe.add(self.tab_Expert, text='Expert') self.mainframe.grid(row=0,column=0,columnspan=4,padx=self.padx,pady=self.pady,sticky=E+W+N+S) def description_tabs(self,arr,tabs,sticky=(W,E),row=None,return_description=False): # Rows = index of rows description_list = [] if row is not None: assert len(row) == len(arr); for i,inputs in enumerate(arr): entry = ttk.Label(tabs,text=inputs,font=self.labelFont) if row is not None: k = row[i] else: k = i entry.grid_configure(column=0,row=k,sticky=sticky,padx=self.padx,pady=self.pady) description_list.append(entry) if description_list: return description_list def Build_tabs(self): """ Build tabs """ # Building all arrays self.Build_global() self.Build_inputs_tab() self.Build_population_tab() self.Build_path_tab() self.Build_mutations_tab() self.Build_larch_tab() self.Build_background_tab() self.Build_output_tab() self.Build_analysis_tab() self.Build_expert_tab() self.mainframe.grid_rowconfigure(0,weight=1) self.mainframe.grid_columnconfigure(0,weight=1) self.mainframe.grid_columnconfigure(1,weight=1) def Write_ini(self,filename): """ Write the ini for the specific file """ inputs = ("[Inputs] \nnum_compounds = {compound} \ncsv_file = {data} \noutput_file = {out} \nfeff_file = {feff}\ncsv_series = {series}" .format(compound=str(self.ncomp.get()), data=str(self.data_file.get()), out=str(self.output_file.get()), feff=str(self.feff_file.get()), series=str(self.series.get()))) populations = ("\n\n[Populations] \npopulation = {pop} \nnum_gen = {numgen} \nbest_sample = {best} \nlucky_few = {luck}" .format(pop=str(self.populations.get()), numgen=str(self.num_gen.get()), best=str(self.best_sample.get()), luck=str(self.lucky_few.get()))) mutations = ("\n\n[Mutations] \nchance_of_mutation = {chance} \noriginal_chance_of_mutation = {original} \nchance_of_mutation_e0 = {e0} \nmutated_options = {opt}" .format(chance=str(self.chance_of_mutation.get()), original=str(self.orginal_chance_of_mutation.get()), e0=str(self.chance_of_mutation_e0.get()), opt=str(self.mutation_options.get()))) paths = ("\n\n[Paths] \nindividual_path = {tf} \npath_range = {range} \npath_list = {list} \npath_optimize = {optimize} \noptimize_percent = {optimize_pert} \noptimize_only = {optimize_only}" .format(tf=str(self.individual_path.get()), range=str(self.path_range.get()), list=str(self.path_list.get().replace(" ","")), optimize=str(self.path_optimize.get()), optimize_pert = str(self.path_optimize_pert.get()), optimize_only = str(self.path_optimize_only.get()) )) larch_paths = ("\n\n[Larch_Paths] \nkmin = {min} \nkmax = {max} \nkweight = {weight} \ndeltak = {delk} \nrbkg = {rb} \nbkgkw = {bk} \nbkgkmax = {bmax}" .format(min=self.kmin.get(), max=self.kmax.get(), weight=self.k_weight.get(), delk=self.delta_k.get(), rb=self.r_bkg.get(), bk=self.bkg_kw.get(), bmax=self.bkg_kmax.get())) outputs = ("\n\n[Outputs] \nprint_graph = {pg} \nnum_output_paths = {outpath}\nsteady_state_exit = {steady}" .format(pg=self.print_graph.get(), outpath=self.num_output_paths.get(), steady=self.steady_state_exit.get())) with open(filename,'w') as writer: writer.write(str(inputs)) writer.write(str(populations)) writer.write(str(mutations)) writer.write(str(paths)) writer.write(str(larch_paths)) writer.write(str(outputs)) def Generate_ini(self): os.chdir("..") #change the working directory from gui to EXAFS # while proceed == False: ini_file= filedialog.asksaveasfilename(initialdir = os.getcwd(), title = "Choose output ini file", filetypes = [("ini files","*.ini")]) if ini_file is None: return if isinstance(ini_file,tuple) == False: if len(ini_file) != 0: self.Write_ini(ini_file) messagebox.showinfo('','Ini file written to {fileloc}'.format(fileloc=ini_file)) os.chdir("gui") def stop_term(self): if hasattr(self,'proc'): # print("Stopped EXAFS") self.proc.kill() def run_term(self,file = 'test_temp.i'): """ if hasattr(self,'terminal'): # Need to close previous threads self.terminal.destroy() # command = ['exafs','-i','test.ini'] self.Write_ini('test_temp.i') command = 'exafs -i test_temp.i'.split(' ') # print(command) self.terminal = Console(self.txtbox,command) """ self.Write_ini('test_temp.i') self.stop_term() # command = 'exafs -i test_temp.i' command = ['exafs','-i',file] if self.os == 'Windows': print(' '.join(command)) self.proc = subprocess.Popen(' '.join(command),shell=True) else: self.proc = subprocess.Popen("exec " + ' '.join(command),shell=True) def run_ini(self,file = 'test_temp.i'): command = ['exafs','-i',file] self.proc = subprocess.Popen("exec " + ' '.join(command),shell=True) self.proc.wait() def Build_global(self): ''' Create global generate ini ''' def about_citation(): """ Create about popup """ popup = tk.Toplevel() popup.wm_title("About: Ver: " + str(self.__version__)) popup.resizable(False,False) cite = tk.Label(popup,text='Citation:',font='TkTextFont') cite.grid(column=0,row=0,sticky=N,padx=self.padx,pady=self.pady) citation = scrolledtext.ScrolledText(popup, width = 75, height = 10, font="TkTextFont") citation.grid(column=0,row=1,sticky=N,padx=self.padx,pady=self.pady) citation.configure(state ='disabled') with open('media/Citation') as f: citation.insert(tk.END,f.read()) License_Label = tk.Label(popup,text='License:',font='TkTextFont') License_Label.grid(column=0,row=2,sticky=N,padx=self.padx,pady=self.pady) license = scrolledtext.ScrolledText(popup, width = 75, font = "TkTextFont") license.grid(column=0,row=3,sticky=N,padx=self.padx,pady=self.pady) license.configure(state ='disabled') with open('../LICENSE') as f: license.insert(tk.END,f.read()) B1 = ttk.Button(popup, text="Okay", command = popup.destroy) B1.grid(column=0,row=4,padx=self.padx,pady=self.pady) # popup.grid_columnconfigure((1,3),weight=1) # popup.grid_rowconfigure((1,3),weight=1) popup.grid_columnconfigure((0,2),weight=1) popup.grid_rowconfigure((0,2),weight=1) popup.protocol('WM_DELETE_WINDOW', popup.destroy) self.generate_button = tk.Button(self.root, text="Generate Input", command=self.Generate_ini) self.generate_button.grid(column=3,row=2,sticky=E,padx=self.padx,pady=self.pady) self.run_button = tk.Button(self.root,text='Run',command=self.run_term) self.run_button.grid(column=1,row=2,columnspan=1,sticky=E,padx=self.padx,pady=self.pady) self.stop_button = tk.Button(self.root,text='Stop',command=self.stop_term) self.stop_button.grid(column=2,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) if self.os == 'Windows': self.stop_button.config(state='disabled') self.about_button = tk.Button(self.root,text='About',command=about_citation) self.about_button.grid(column=0,row=2,columnspan=1,sticky=W,padx=self.padx,pady=self.pady) self.root.grid_columnconfigure(1, weight=1) self.root.grid_columnconfigure(2, weight=1) self.root.grid_rowconfigure(0,weight=1) # Create a empty frame self.label_frame = LabelFrame(self.root, text="Terminal", padx=5, pady=5) self.label_frame.grid(column=0,row=1, columnspan=4, padx=self.padx, pady=self.pady, sticky=E+W+N+S) # Create the textbox self.label_frame.rowconfigure(0,weight=1) self.label_frame.columnconfigure(0,weight=1) self.txtbox = scrolledtext.ScrolledText(self.label_frame, width=40, height=10) self.txtbox.grid(row=0, column=0, sticky=E+W+N+S) def Build_inputs_tab(self): arr_input = ["Data file", "Output File","Number of FEFF folder"] #FEFF Folder self.description_tabs(arr_input,self.tab_Inputs,row = [0,1,3]) self.tab_Inputs.grid_columnconfigure(1,weight=1) entry_data_file = ttk.Combobox(self.tab_Inputs, textvariable=self.temp_data_file, font=self.entryFont) entry_data_file.grid(column=1, row=0, sticky=(W, E),padx=self.padx,pady=self.pady) entry_output_file = tk.Entry(self.tab_Inputs,textvariable=self.output_file,font=self.entryFont) entry_output_file.grid(column=1,row=1,sticky=(W,E),padx=self.padx,pady=self.pady) separator = ttk.Separator(self.tab_Inputs, orient='horizontal') separator.grid(column=0, row=2,columnspan=4,sticky=W+E,padx=self.padx) comp_list = list(range(1,6)) entry_ncomp = ttk.Combobox(self.tab_Inputs, width=7, values=comp_list,textvariable=self.ncomp, font=self.entryFont) entry_ncomp.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def select_data_file(): os.chdir("..") #change the working directory from gui to EXAFS file_name = filedialog.askopenfilenames(initialdir = os.getcwd(), title = "Choose xmu/csv", filetypes = (("xmu files", "*.xmu"),("csv files","*.csv"),("all files","*.*"))) if not file_name: self.data_file.set('Please choose file/s') self.temp_data_file.set('Please choose file/s') else: if isinstance(file_name,tuple): if len(file_name)==1: self.data_file.set(str(file_name[0])) self.temp_data_file.set(str(file_name[0])) else: file_list = list(self.root.splitlist(file_name)) separator = ' ' self.data_file.set(separator.join(file_list)) entry_data_file['value'] = file_list self.series.set(True) os.chdir("gui") def select_output_file(): os.chdir("..") #change the working directory from gui to EXAFS file_name = filedialog.asksaveasfilename(initialdir = os.getcwd(), title = "Choose data_file", filetypes = (("csv files","*.csv"),("all files","*.*"))) if not file_name: self.output_file.set('Please choose a file') else: self.output_file.set(file_name) os.chdir("gui") def feff_trace(var,indx,mode): # Todo: Need to add assertion to make sure every folder is not normal raw_str = [] for i in range(len(self.feff_file_list)): raw_str.append(self.feff_file_list[i].get()) raw_feff = ','.join(raw_str) self.feff_file.set(raw_feff) # print(raw_feff) def gen_feff_folder(var,indx,mode): ncomp = self.ncomp.get() self.feff_file_toggle = [True for i in range(self.ncomp.get())] k = 4 try: self.arr_feff # self.input_list except AttributeError: pass else: for i in range(len(self.feff_input_list)): self.feff_input_list[i].destroy() self.feff_button_list[i].destroy() self.feff_description_list[i].destroy() self.feff_file_list = [] self.arr_feff= [] arr_row = [] # parameter sets self.feff_input_list = [] self.feff_button_list = [] self.feff_description_list = [] # Need to remove previous one for i in range(ncomp): self.arr_feff.append('FEFF Folder (' + str(i+1) +")") arr_row.append(i+k) # Generate a list of variables temp_var = StringVar(self.root,'Please choose a directory') self.feff_file_list.append(temp_var) # Add trace back temp_var.trace_add('write',feff_trace) # Setup each entry temp_entry = tk.Entry(self.tab_Inputs,textvariable=temp_var, font=self.entryFont) temp_entry.grid(column=1,row=k+i,sticky=(W,E), padx=self.padx,pady=self.pady) self.feff_input_list.append(temp_entry) # setup each button temp_button = ttk.Button(self.tab_Inputs,text="Choose", command=lambda x=i:select_feff_folder(self.feff_file_list[x]), style='my.TButton') temp_button.grid(column=3, row=k+i, sticky=W,padx=self.padx,pady=self.pady) self.feff_button_list.append(temp_button) self.feff_description_list = self.description_tabs(self.arr_feff,self.tab_Inputs,row=arr_row,return_description=True) def check_feff_folder(pathlib_Path): feff_inp_exists = False num_feff_file = 0 folder_Path = pathlib.Path(pathlib_Path) for i in folder_Path.iterdir(): file = pathlib.Path(i).name if fnmatch.fnmatch(file,'feff????.dat'): num_feff_file +=1 if num_feff_file == 0: # Check no scattering paths for i in folder_Path.iterdir(): file = pathlib.Path(i).name if fnmatch.fnmatch(file,'feff.inp'): feff_inp_exists = True feff_inp_loc = file abs_feff_inp_loc = folder_Path.joinpath('feff.inp') create_feff_folder(abs_feff_inp_loc) else: # self.txtbox.insert('No feff.inp in folder') self.txtbox.insert(tk.END,"No feff.inp in folder\n") # return False def select_feff_folder(var): os.chdir("..") #change the working directory from gui to EXAFS # select folder name folder_name = filedialog.askdirectory(initialdir = os.getcwd(), title = "Select folder") if not folder_name: var.set('Please choose a directory') else: check_feff_folder(folder_name) folder_name = os.path.join(folder_name,'feff') var.set(folder_name) os.chdir("gui") # add trace back self.ncomp.trace_add('write',gen_feff_folder) self.ncomp.set(1) button_data_file = ttk.Button(self.tab_Inputs, text="Choose", command=select_data_file, style='my.TButton') button_data_file.grid(column=3, row=0, sticky=W,padx=self.padx,pady=self.pady) button_output_file = ttk.Button(self.tab_Inputs,text="Choose", command=select_output_file, style='my.TButton') button_output_file.grid(column=3, row=1, sticky=W,padx=self.padx,pady=self.pady) def Build_population_tab(self): arr_pop = ["Population", "Number of Generations", "Best Individuals(%)", "Lucky Survivor(%)"] self.description_tabs(arr_pop,self.tab_Populations) self.tab_Populations.grid_columnconfigure(1,weight=1) entry_population = tk.Entry(self.tab_Populations, textvariable=self.populations, font=self.entryFont) entry_population.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_num_gen = tk.Entry(self.tab_Populations, textvariable=self.num_gen, font=self.entryFont) entry_num_gen.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_best_sample = tk.Entry(self.tab_Populations, textvariable=self.best_sample, font=self.entryFont) entry_best_sample.grid(column=1, row=2, sticky=(W, E),padx=self.padx) entry_lucky_few = tk.Entry(self.tab_Populations, textvariable=self.lucky_few, font=self.entryFont) entry_lucky_few.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def Build_path_tab(self): """ Build path tabs """ arr_paths = ['Path Optimize','Multi-Path Optimize','Path Optimize Percentage'] self.description_tabs(arr_paths,self.tab_Paths,row = [0,1,2]) def checkbox_individual_paths(): if self.individual_path.get() == True: entry_path_range.config(state='disabled') entry_path_list.config(state='normal') else: entry_path_range.config(state='normal') entry_path_list.config(state='disabled') # def path_list_cb(var, indx, mode): # """ # Path_list call-back for the number of lists # """ # if self.individual_path.get()== True: # self.path_list.set(self.path_list_call.get()) # counts = 0 # test_list = self.path_list.get().split(",") # for i in range(len(test_list)): # if test_list[i] != '': # counts += 1 # self.path_range_call.set(counts) # entry_individual_paths = ttk.Checkbutton(self.tab_Paths, # variable = self.individual_path,command = checkbox_individual_paths) # entry_individual_paths.grid(column=1,row=0,sticky=(W),padx=self.padx) # self.path_range_call = StringVar(self.tab_Paths,str(self.path_range.get())) # self.path_range_call.trace_add("write",path_range_cb) # entry_path_range = ttk.Entry(self.tab_Paths, width=7, # textvariable=self.path_range_call, font=self.entryFont) # entry_path_range.grid(column=1, row=1, sticky=(W),padx=self.padx) # self.path_list_call = StringVar(self.tab_Paths,self.path_list.get()) # self.path_list_call.trace_add('write',path_list_cb) # entry_path_list = ttk.Entry(self.tab_Paths, # textvariable=self.path_list_call, font=self.entryFont) # entry_path_list.grid(column=1, row=2, sticky=(W, E),padx=self.padx) # entry_path_list.config(state='disabled') # def path_range_cb(var, indx, mode): # if self.individual_path.get()==False: # if self.path_range_call.get() == '': # int_test = 0 # else: # int_test = int(float(self.path_range_call.get())) # self.path_range_call.set(int_test) # self.path_range.set(int_test) # # custom_path_list = ",".join(np.char.mod('%i', np.arange(1,self.path_range.get()+1))) # self.path_list_call.set(custom_path_list) # self.path_list.set(custom_path_list) # def test_str(var): def output_var_trace(var,indx,mode): """ Updates the variables whenever it gets changes """ raw_str = [] # compounds if self.ncomp.get() > 1: for i in range(len(self.path_file_list)): # print(self.path_file_list[i].get()) # create the internal brackets # base_str = list(self.path_file_list[i].get()) var = self.path_file_list[i].get() if var == str(0) or var == "": base_str = '' # del the corresponding one from the final output self.feff_file_toggle[i] = False else: base_str = "[" + var + "]" self.feff_file_toggle[i] = True raw_str.append(base_str) # call back for path and feff temp_path_list = [] temp_feff_list = [] for i in range(len(self.path_file_list)): if self.feff_file_toggle[i] == True: temp_path_list.append(raw_str[i]) temp_feff_list.append(self.feff_file_list[i].get()) raw_path = ','.join(temp_path_list) raw_feff = ','.join(temp_feff_list) self.path_list.set(raw_path) self.feff_file.set(raw_feff) self.individual_path.set(True) # else calculate compounds else: self.path_list.set(self.path_file_list[0].get()) # print("-----------------------") # print(self.feff_file_toggle) # print(self.feff_file.get()) # print(self.path_list.get()) def ncomp_trace_cb(var, indx, mode): """ Trace the number of components, if changes, recomputed """ ncomp = self.ncomp.get() k = 5 # Starting components # Check if arr_pathlist exists try: self.arr_pathlist except AttributeError: pass else: # Destory all in the current list for i in range(len(self.path_input_list)): self.path_description_list[i].destroy() self.path_input_list[i].destroy() # Create the list self.arr_pathlist = [] self.path_input_list = [] self.path_file_list = [] arr_row = [] for i in range(ncomp): self.arr_pathlist.append('Pathlist Folder ('+ str(i+1) + ")") arr_row.append(i+k) # Create the entry variable temp_path_var = StringVar(self.root,'Path_list') temp_path_var.trace_add('write',output_var_trace) # temp_path_var.trace_add('write',) self.path_file_list.append(temp_path_var) # Create the entry temp_entry = tk.Entry(self.tab_Paths,textvariable=self.path_file_list[i], font=self.entryFont) # lock to the grid temp_entry.grid(column=1,columnspan=2,row=k+i,sticky=(W,E), padx=self.padx,pady=self.pady) self.path_input_list.append(temp_entry) # create the descriptions for it. self.path_description_list = self.description_tabs(self.arr_pathlist,self.tab_Paths,row=arr_row,return_description=True) entry_path_optimize = ttk.Checkbutton(self.tab_Paths, variable = self.path_optimize) entry_path_optimize.grid(column=1,row=0,sticky=(W,E),padx=self.padx) entry_path_optimize_only = ttk.Checkbutton(self.tab_Paths, variable = self.path_optimize_only) entry_path_optimize_only.grid(column=1,row=1,sticky=(W,E),padx=self.padx) entry_optimize_perc= ttk.Entry(self.tab_Paths, textvariable=self.path_optimize_pert, font=self.entryFont) entry_optimize_perc.grid(column=1, row=2, sticky=(W, E),padx=self.padx) separator = ttk.Separator(self.tab_Paths, orient='horizontal') separator.grid(column=0, row=3,columnspan=4,sticky=(W,E),padx=self.padx) self.tab_Paths.columnconfigure(4,weight=1) # add the call back for it to modify if it get changes self.ncomp.trace_add('write',ncomp_trace_cb) # inital default value self.ncomp.set(1) def Build_mutations_tab(self): arr_muts = ["Mutation Chance (%)", "Original chance of mutation (%)", "E0 Mutation Chance (%)", "Mutation Options"] self.description_tabs(arr_muts,self.tab_Mutation) mut_list = list(range(101)) # self.tab_Inputs.grid_columnconfigure(1,weight=1) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.chance_of_mutation, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.orginal_chance_of_mutation, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.chance_of_mutation_e0, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=2, sticky=(W, E),padx=self.padx) mut_list = list(range(3)) entry_chance_of_mutation = ttk.Combobox(self.tab_Mutation, width=7, values=mut_list,textvariable=self.mutation_options, font=self.entryFont) entry_chance_of_mutation.grid(column=1, row=3, sticky=(W, E),padx=self.padx) def Build_larch_tab(self): arr_larch = ["Kmin", "Kmax", "Kweight", "Delta k", "R Bkg", "Bkg Kw", "Bkg Kmax"] self.description_tabs(arr_larch,self.tab_Larch) entry_kmin = ttk.Entry(self.tab_Larch, textvariable=self.kmin, font=self.entryFont) entry_kmin.grid(column=1, row=0, sticky=(W, E),padx=self.padx) entry_kmax = ttk.Entry(self.tab_Larch, textvariable=self.kmax, font=self.entryFont) entry_kmax.grid(column=1, row=1, sticky=(W, E),padx=self.padx) entry_k_weight = ttk.Entry(self.tab_Larch, textvariable=self.k_weight, font=self.entryFont) entry_k_weight.grid(column=1, row=2, sticky=(W, E),padx=self.padx) entry_delta_k = ttk.Entry(self.tab_Larch, textvariable=self.delta_k, font=self.entryFont) entry_delta_k.grid(column=1, row=3, sticky=(W, E),padx=self.padx) entry_r_bkg = ttk.Entry(self.tab_Larch, textvariable=self.r_bkg, font=self.entryFont) entry_r_bkg.grid(column=1, row=4, sticky=(W, E),padx=self.padx) entry_bkg_kw = ttk.Entry(self.tab_Larch, textvariable=self.bkg_kw, font=self.entryFont) entry_bkg_kw.grid(column=1, row=5, sticky=(W, E),padx=self.padx) entry_bkg_kmax = ttk.Entry(self.tab_Larch, textvariable=self.bkg_kmax, font=self.entryFont) entry_bkg_kmax.grid(column=1, row=6, sticky=(W, E),padx=self.padx) def Build_background_tab(self): def button_bkg_draw(): # TODO: # Makes it so bkg_plot.inital_parameters(self.temp_data_file,self.r_bkg,self.bkg_kw,self.bkg_kmax,self.kmin,self.kmax,self.delta_k,self.k_weight) bkg_plot.draw_background() arr_bkg = ["R Bkg", "K min","K max","Bkg Kw", "Bkg Kmax"] self.description_tabs(arr_bkg,self.tab_Bkg,sticky=(W,E,N)) # self.tab_Bkg.grid_rowconfigure(3,weight=1) # self.tab_Bkg.grid_rowconfigure(4,weight=1) # self.tab_Bkg.grid_rowconfigure(5,weight=1) # self.tab_Bkg.grid_rowconfigure(6,weight=1) self.tab_Bkg.rowconfigure(8,weight=1) self.tab_Bkg.columnconfigure(2,weight=1) entry_r_bkg = ttk.Entry(self.tab_Bkg, textvariable=self.r_bkg, font=self.entryFont) entry_r_bkg.grid(column=1, row=0, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_k_min = ttk.Entry(self.tab_Bkg, textvariable=self.kmin, font=self.entryFont) entry_k_min.grid(column=1, row=1, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_k_max = ttk.Entry(self.tab_Bkg, textvariable=self.kmax, font=self.entryFont) entry_k_max.grid(column=1, row=2, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_bkg_kw = ttk.Entry(self.tab_Bkg, textvariable=self.bkg_kw, font=self.entryFont) entry_bkg_kw.grid(column=1, row=3, sticky=(W,E,N),padx=self.padx,pady=self.pady) entry_bkg_kmax = ttk.Entry(self.tab_Bkg, textvariable=self.bkg_kmax, font=self.entryFont) entry_bkg_kmax.grid(column=1, row=4, sticky=(W,E,N),padx=self.padx,pady=self.pady) bkg_plot = BKG_plot(self.tab_Bkg,self.mylarch) button_bkg_mu = ttk.Button(self.tab_Bkg, text="Plot Background and Mu", command=button_bkg_draw) button_bkg_mu.grid(column=0, row=5,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_kspace = ttk.Button(self.tab_Bkg, text="K space", command=bkg_plot.draw_kspace) button_kspace.grid(column=0, row=6,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_rspace = ttk.Button(self.tab_Bkg, text="R space", command=bkg_plot.draw_rspace) button_rspace.grid(column=0, row=7,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) def Build_output_tab(self): pop_min = IntVar(self.tab_Output,100) pop_max = IntVar(self.tab_Output,5001) gen_min = IntVar(self.tab_Output,20) gen_max = IntVar(self.tab_Output,501) mut_min = IntVar(self.tab_Output,20) mut_max = IntVar(self.tab_Output,51) pertub_check = IntVar(self.tab_Output,0) def generate_multi_ini(): # os.chdir("..") pop_range = np.arange(pop_min.get(),pop_max.get(),100) gen_range = np.arange(gen_min.get(),gen_max.get(),5) mut_range = np.arange(mut_min.get(),mut_max.get(),10) # exit() multi_folder = filedialog.askdirectory(initialdir = os.getcwd(),title = 'Select folder') if not multi_folder: return else: og_pop = self.populations.get() og_gen = self.num_gen.get() og_mut = self.chance_of_mutation.get() og_out_file = self.output_file.get() for i in range(self.n_ini.get()): pop_select = np.random.choice(pop_range) gen_select = np.random.choice(gen_range) mut_select = np.random.choice(mut_range) base_file = os.path.splitext(og_out_file)[0] self.output_file.set(os.path.join(base_file +"_"+str(i).zfill(3) +".ini")) self.populations.set(pop_select) self.num_gen.set(gen_select) self.chance_of_mutation.set(mut_select) self.Write_ini(multi_folder + "/file_" + str(i).zfill(3)+'.i') # set back og ini self.populations.set(og_pop) self.num_gen.set(og_gen) self.chance_of_mutation.set(og_mut) self.output_file.set(og_out_file) # os.chdir("gui") return multi_folder def run_multi_ini(): """ Run multiple ini file """ folder_loc = generate_multi_ini() full_file_list = [] file_list = glob.glob(folder_loc + "/*.i") for i in file_list: full_file_list.append(os.path.join(folder_loc,i)) full_file_list.sort(key=natural_keys) for i in full_file_list: print(bcolors.BOLD + str(i) + bcolors.ENDC) self.run_ini(i) def checkbox_multi(): widget_lists=[ entry_n_ini, entry_pertub_pop_min, entry_pertub_pop_max, entry_pertub_gen_min, entry_pertub_gen_max, entry_pertub_mut_min, entry_pertub_mut_max, button_gen_nini, button_run_nini] if pertub_check.get() == 0: for i in widget_lists: i.config(state='disabled') elif pertub_check.get() == 1: for i in widget_lists: i.config(state='normal') arr_out = ["Print graph", "Steady state exit"] self.description_tabs(arr_out,self.tab_Output) checkbutton_print_graph = ttk.Checkbutton(self.tab_Output, var=self.print_graph) checkbutton_print_graph.grid(column=1, row=0,sticky=W+E,padx=self.padx) checkbutton_steady_state= ttk.Checkbutton(self.tab_Output, var=self.steady_state_exit) checkbutton_steady_state.grid(column=1, row=1,sticky=W+E,padx=self.padx) # Create separators separator = ttk.Separator(self.tab_Output, orient='horizontal') separator.grid(column=0, row=2,columnspan=4,sticky=W+E,padx=self.padx) self.tab_Output.columnconfigure(3,weight=1) arr_out = ["Create Multiple Input Files","Number of Ini Files","Pertubutions-Population(min,max)", "Pertubutions-Generation(min,max)","Pertubutions-Mutation(min,max)"] self.description_tabs(arr_out,self.tab_Output,row=[3,5,6,7,8]) # Create New pertubutuions checkbutton_pertub= ttk.Checkbutton(self.tab_Output, var=pertub_check,command=checkbox_multi) checkbutton_pertub.grid(column=1, row=3,sticky=W+E,padx=self.padx) pertub_list = list(range(1,101)) text ='Each entry allows user to control perturbation percentage of the desire variables.' entry = ttk.Label(self.tab_Output,text=text,font=self.labelFont) entry.grid_configure(column=0,row=4,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) entry_n_ini = tk.Entry(self.tab_Output,textvariable=self.n_ini,font=self.entryFont) entry_n_ini.grid(column=1, row=5,columnspan=2,sticky=(W, E),padx=self.padx) entry_n_ini.config(state='disabled') width = 5 # -------------- entry_pertub_pop_min= ttk.Entry(self.tab_Output, width=width,textvariable=pop_min, font=self.entryFont) entry_pertub_pop_min.grid(column=1, row=6, sticky=(W, E),padx=self.padx) entry_pertub_pop_max= ttk.Entry(self.tab_Output, width=width,textvariable=pop_max, font=self.entryFont) entry_pertub_pop_max.grid(column=2, row=6, sticky=(W, E),padx=self.padx) entry_pertub_pop_min.config(state='disabled') entry_pertub_pop_max.config(state='disabled') # -------------- entry_pertub_gen_min= ttk.Entry(self.tab_Output, width=width,textvariable=gen_min, font=self.entryFont) entry_pertub_gen_min.grid(column=1, row=7, sticky=(W, E),padx=self.padx) entry_pertub_gen_max= ttk.Entry(self.tab_Output, width=width,textvariable=gen_max, font=self.entryFont) entry_pertub_gen_max.grid(column=2, row=7, sticky=(W, E),padx=self.padx) entry_pertub_gen_min.config(state='disabled') entry_pertub_gen_max.config(state='disabled') # -------------- entry_pertub_mut_min= ttk.Entry(self.tab_Output, width=width,textvariable=mut_min, font=self.entryFont) entry_pertub_mut_min.grid(column=1, row=8, sticky=(W, E),padx=self.padx) entry_pertub_mut_max= ttk.Entry(self.tab_Output, width=width,textvariable=mut_max, font=self.entryFont) entry_pertub_mut_max.grid(column=2, row=8, sticky=(W, E),padx=self.padx) entry_pertub_mut_min.config(state='disabled') entry_pertub_mut_max.config(state='disabled') # -------------- button_gen_nini = tk.Button(self.tab_Output,text="Generate Input Files",command=generate_multi_ini) button_gen_nini.grid(column=0, row=9,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) button_gen_nini.config(state='disabled') button_run_nini = tk.Button(self.tab_Output,text="Run Multiple Input Files",command=run_multi_ini) button_run_nini.grid(column=0, row=10,columnspan=3,sticky=W+E,padx=self.padx,pady=self.pady) button_run_nini.config(state='disabled') def Build_analysis_tab(self): def select_analysis_folder(): os.chdir("..") #change the working directory from gui to EXAFS folder_name = filedialog.askdirectory(initialdir = os.getcwd(), title = "Select folder") if not folder_name: analysis_folder.set('Please choose a directory') else: # folder_name = os.path.join(folder_name,'feff') analysis_folder.set(folder_name) # print(self.feff_file.get()) os.chdir("gui") def run_analysis(): params = {} # params['base'] = Path(os.getcwd()).parent params['base'] = '' params['Kmin'] = self.kmin.get() params['Kmax'] = self.kmax.get() params['kweight'] = self.k_weight.get() params['deltak'] = self.delta_k.get() params['rbkg'] = self.r_bkg.get() params['bkgkw'] = self.bkg_kw.get() params['bkgkmax'] = self.bkg_kmax.get() params['front'] = self.feff_file.get().split(',') params['CSV'] = self.data_file.get() params['optimize'] = self.path_optimize.get() params['series_index'] = series_index.get() params['series'] = self.series.get() # set up the params self.txtbox.insert(tk.END,"Running Analysis...\n") analysis_plot.setup_params(params) paths = '[' + self.path_list.get() + ']' paths_list = ast.literal_eval(paths) # analysis_plot.setup_paths(paths) print(paths) print(paths_list) print(type(paths_list)) analysis_plot.setup_paths(ast.literal_eval(paths)) analysis_plot.setup_dirs(analysis_folder.get()) arr_str,latex_str = analysis_plot.extract_and_run(analysis_folder) self.txtbox.insert(tk.END,arr_str) self.txtbox.insert(tk.END,"-------------\n") self.txtbox.insert(tk.END,latex_str) self.txtbox.insert(tk.END,"\n-------------\n") self.txtbox.insert(tk.END,"Done") def plot_occurances(): # plot the self_occurances, and then plot the others """ To do: occurances only works with one """ analysis_plot.plot_occurances(analysis_folder.get(),self.path_optimize_pert.get(),self.path_list.get()) analysis_folder = StringVar(self.tab_Analysis,'Please choose a directory') series_index = IntVar(self.tab_Analysis,0) self.tab_Analysis.columnconfigure(1,weight=1) self.tab_Analysis.columnconfigure(2,weight=1) self.tab_Analysis.rowconfigure(10,weight=1) arr_out = ["Select folder"] self.description_tabs(arr_out,self.tab_Analysis) entry_analysis_folder = tk.Entry(self.tab_Analysis,textvariable=analysis_folder,font=self.entryFont) entry_analysis_folder.grid(column=1,row=0,columnspan=2,sticky=W+E,padx=self.padx,pady=self.pady) button_analysis_folder = ttk.Button(self.tab_Analysis,text="Choose", command=select_analysis_folder, style='my.TButton') button_analysis_folder.grid(column=3, row=0, sticky=W+E,padx=self.padx,pady=self.pady) separator = ttk.Separator(self.tab_Analysis, orient='horizontal') separator.grid(column=0, row=1,columnspan=4,sticky=W+E,padx=self.padx) analysis_plot = Analysis_Plot(self.tab_Analysis,self.mylarch) # ---------------------------------------------------------------------- button_Run_Analysis = ttk.Button(self.tab_Analysis,text="Run Analysis", command=run_analysis, style='my.TButton') button_Run_Analysis.grid(column=0, row=2,columnspan=4, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_kR = ttk.Button(self.tab_Analysis,text="Plot K and R Spectrum", command=analysis_plot.plot_k_r_space, style='my.TButton') button_plot_kR.grid(column=0, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_individual = ttk.Button(self.tab_Analysis,text='Plot K Individual', command=analysis_plot.plot_individual, style='my.TButton') button_plot_individual.grid(column=1, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_error = ttk.Button(self.tab_Analysis,text="Plot Error", command=analysis_plot.plot_error, style='my.TButton') button_plot_error.grid(column=2, row=3,columnspan=1, sticky=W+E,padx=self.padx,pady=self.pady) button_plot_occurances = ttk.Button(self.tab_Analysis,text='Plot Occurances', command=plot_occurances, style='my.TButton') button_plot_occurances.grid(column=3,row=3,columnspan=1,sticky=W+E,padx=self.padx,pady=self.pady) def Build_expert_tab(self): arr_muts = ["Override Num Compounds"] self.description_tabs(arr_muts,self.tab_Expert) ncomp_list = list(range(1,101)) entry_ncomp = ttk.Combobox(self.tab_Expert, width=7, values=ncomp_list,textvariable=self.ncomp, font=self.entryFont) entry_ncomp.grid(column=1, row=0, sticky=(W, E),padx=self.padx) def On_closing(self): """ on closing function """ if messagebox.askokcancel("Quit", "Do you want to quit?"): self.stop_term() if hasattr(self,'terminal'): self.root.quit() self.terminal.destroy() else: self.root.quit() def Run(self): """ Run the code """ self.root.protocol('WM_DELETE_WINDOW', self.On_closing) self.beta_popup() self.root.mainloop() def beta_popup(self): beta_popup = tk.Toplevel(self.root) beta_popup.wm_title("Warning") msg = "This Graphical User Interface is still under active development.\nPlease contact us using Github Issues." entry = ttk.Label(beta_popup,text=msg) entry.grid(column=0,row=0,padx=5,pady=3) B1 = ttk.Button(beta_popup, text="Okay", command = beta_popup.destroy) B1.grid(column=0,row=1,padx=5,pady=3) beta_popup.grid_columnconfigure((0,1),weight=1) beta_popup.grid_rowconfigure((0,1),weight=1) beta_popup.protocol('WM_DELETE_WINDOW', beta_popup.destroy) beta_popup.attributes('-topmost', 'true')
def __init__(self, master): # we will define everything in the UI below logger.info("Program start") self.master = master self.master.wm_title("Lautaloader v.1.03") # title of window self.master.resizable(width=FALSE, height=FALSE) # window is not resizable self.master.geometry('420x240') # resolution of the window in pixels self.master.grid_propagate(False) # window will not resize in any case self.r_selection = IntVar() # these are radiobuttons and checkbuttons self.c1_selection = IntVar() self.c2_selection = IntVar() self.c1_selection.set(0) # checkbuttons will be off at launch self.c2_selection.set(0) self.r_selection.set(1) # we need one radiobutton selected at start self.status_text = StringVar() # status text is visible at the bottom of GUI self.status_text.set('Ready to work') # we can (and will) set the status text like this self.save_folder = '' # we will save into this folder self.filenames = [] # this is our folder filenames list self.url_text = StringVar() self.num_pics = 0 self.num_mp4 = 0 self.num_mp3 = 0 self.image_url = '' self.name_of_file = '' self.res = '' self.imagefile = '' self.filesize = '' self.imagewritten = False self.read_timeout = 1.0 self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Referer': '', 'DNT': '1', 'Accept-Language': 'fi-FI,fi;q=0.8,en-US;q=0.6,en;q=0.4', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } # need to send some headers or server refuses connection self.lf = LabelFrame(master, text=' Get ') self.lf.grid(row=1, column=1, rowspan=4) self.lf2 = LabelFrame(master, text=' Options ') self.lf2.grid(row=1, column=2) self.R1 = Radiobutton(self.lf, text="All", variable=self.r_selection, value=1) self.R1.grid(row=1, column=1, sticky=W) self.R2 = Radiobutton(self.lf, text="only img", variable=self.r_selection, value=2) self.R2.grid(row=2, column=1, sticky=W) self.R3 = Radiobutton(self.lf, text="only mp4", variable=self.r_selection, value=3) self.R3.grid(row=3, column=1, sticky=W) self.R4 = Radiobutton(self.lf, text="only mp3", variable=self.r_selection, value=4) self.R4.grid(row=4, column=1, sticky=W) self.C1 = Checkbutton(self.lf2, text="Create new filenames", variable=self.c1_selection, state=NORMAL, onvalue=1, offvalue=0) self.C1.grid(row=1, column=2, sticky=W) self.C2 = Checkbutton(self.lf2, text="Overwrite if found", variable=self.c2_selection, state=NORMAL, onvalue=1, offvalue=0) self.C2.grid(row=2, column=2, sticky=W) self.folder_label = Label(master, text="Folder: ") self.folder_label.grid(row=5, sticky=E) self.url_label = Label(root, text="URL: ") self.url_label.grid(row=6, sticky=E) self.folder_entry = Entry(master, textvariable=self.save_folder, state="readonly", width=50) self.folder_entry.grid(row=5, column=1, columnspan=2) self.url_entry = Entry(master, textvariable=self.url_text, width=50) self.url_entry.grid(row=6, column=1, columnspan=2) self.selectbutton = Button(master, text="Select..", state=NORMAL, command=self.get_folder) self.selectbutton.grid(row=5, column=3, sticky=W) self.openfolderbutton = Button(master, text="Open folder", state=DISABLED, command=self.openfolder) self.openfolderbutton.grid(row=3, column=2, sticky=W, padx=22) self.urlbutton = Button(master, text="Download", state=DISABLED, command=self.logic) self.urlbutton.grid(row=6, column=3, sticky=W) self.status = Label(master, textvariable=self.status_text, wraplength=300) self.status.grid(row=9, columnspan=4, sticky=W) self.progressbar = Progressbar(master, orient="horizontal", length=100, mode="determinate") self.progressbar.grid(row=8, sticky='we', columnspan=3, pady=3) self.manage_config() # process through config file self.url_1 = config.get('basic_config', 'url_1') logging.debug("url_1 set to %s" % self.url_1) self.url_2 = config.get('basic_config', 'url_2') logging.debug("url_2 set to %s" % self.url_2) if self.save_folder != '': # if save folder is not empty, we probably have a valid folder self.urlbutton['state'] = 'normal' # so we can enable urlbutton already self.openfolderbutton['state'] = 'normal' # and we can also enable open folder button
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grid_columnconfigure(0, weight = 1) self.grid_rowconfigure(0, weight = 1) self.container = LabelFrame(self, text = 'medidas de tendencia central y Medidas de dispersion') self.container.grid(row = 0, column = 0,sticky = "w,e,s,n", padx = 5, ipadx = 5) #Entries self.containerEntries = ttk.LabelFrame(self.container, text = 'Datos') self.containerEntries.grid(row = 2, column = 0, rowspan = 1, columnspan = 3, sticky = "e,w", ipadx = 10) self.NumIntervLbl = ttk.Label(self.containerEntries, text = "Numero de intervalos:") self.NumIntervLbl.grid(row = 0, column = 0) self.NumInterv = ttk.Entry(self.containerEntries, width = 15) self.NumInterv.grid(row = 0, column = 1, pady = 5) self.ValueLbl = ttk.Label(self.containerEntries, text = "valor:") self.ValueLbl.grid(row = 1, column =0, padx =10) self.Value = ttk.Entry(self.containerEntries, width = 30) self.Value.bind('<Return>', self.enterEvent) self.Value.grid(row = 1, column = 1, columnspan = 2, padx =10) self.btnAggInterv = ttk.Button(self.containerEntries, text = "Agregar", command = self.addValue) self.btnAggInterv.grid(row = 1, column = 3, padx =10) self.btnCalc = ttk.Button(self.containerEntries, text = "Calcular", command = self.calc) self.btnCalc.grid(row = 1, column = 4, padx =10) #TextArea values self.container_val = ttk.LabelFrame(self.container, text = 'valores') self.container_val.grid(row = 0, column = 0, rowspan = 2, sticky = "sw,nw,n,s,w", ipadx = 5) self.valuesTxt = Text(self.container_val, width = 25) self.valuesTxt.grid(row = 0, sticky = "sw,nw,n,s,w", padx = 5) self.valuesTxt["state"] = "disabled" self.scrollbar = ttk.Scrollbar(self.container_val) self.scrollbar.grid(row = 0, sticky = "e, n, s") self.valuesTxt.config( yscrollcommand = self.scrollbar.set ) self.scrollbar.config( command = self.valuesTxt.yview ) #frequence table self.containerTable = ttk.LabelFrame(self.container, text = 'tabla de frecuencia') self.containerTable.grid(row = 0, column = 1, columnspan = 2, sticky = "n, s, e, w") self.freqTable = ttk.Treeview(self.containerTable, height = 10, columns =('#1', '#2', '#3', '#4', '#5', '#6')) self.freqTable['show'] = 'headings' self.freqTable.heading('#1', text = "intervalos", anchor = CENTER) self.freqTable.heading('#2', text = "M", anchor = CENTER) self.freqTable.heading('#3', text = "f", anchor = CENTER) self.freqTable.heading('#4', text = "F", anchor = CENTER) self.freqTable.heading('#5', text = "Fr", anchor = CENTER) self.freqTable.heading('#6', text = "F%", anchor = CENTER) self.freqTable.column("#1", width = 100) self.freqTable.column("#2", width = 70) self.freqTable.column("#3", width = 70) self.freqTable.column("#4", width = 70) self.freqTable.column("#5", width = 120) self.freqTable.column("#6", width = 120) self.freqTable.grid(row = 0, column = 0, sticky = "n, e, w, s") #result container self.containerResult = ttk.LabelFrame(self.container, text = 'Resultados') self.containerResult.grid(row = 1, column = 1, sticky = "n,s,e,w") self.ResultTxt = Text(self.containerResult, height = 10, width = 67) self.ResultTxt.grid(row = 0, sticky = "w, n, s, e") self.ResultTxt["state"] = "disabled" self.scrollbar2 = ttk.Scrollbar(self.containerResult) self.scrollbar2.grid(row = 0, sticky = "e, n, s") self.ResultTxt.config( yscrollcommand = self.scrollbar2.set ) self.scrollbar2.config( command = self.ResultTxt.yview )
def create_widgets(self): self.directory_frame = Frame(self) self.directory_frame.pack(side=TOP, fill=X, expand=0, padx=4, pady=4) self.directory_frame.grid_columnconfigure(1, weight=1) self.directory_label = Label(self.directory_frame, text="Directory:") self.directory_label.grid(column=0, row=0) self.directory_entry = Entry(self.directory_frame, textvariable=self.cfg.directory) self.directory_entry.grid(column=1, row=0, sticky=W + E) self.directory_entry.bind('<Return>', lambda arg: self.do_preview()) self.directory_button = Button(self.directory_frame, text="Browse") self.directory_button["command"] = lambda: do_ask_directory(self.cfg.directory) self.directory_button.grid(column=2, row=0) self.glob_label = Label(self.directory_frame, text="Glob:") self.glob_label.grid(column=0, row=1, stick=E) self.glob_entry = Entry(self.directory_frame, textvariable=self.cfg.glob) self.glob_entry.bind('<Return>', lambda arg: self.do_preview()) self.glob_entry.grid(column=1, row=1, sticky=N + S + W) self.search_replace_frame = Frame(self) self.search_replace_frame.grid_columnconfigure(1, weight=1) self.search_replace_frame.pack(anchor=N, side=TOP, fill=X, expand=0, padx=4, pady=4) self.search_label = Label(self.search_replace_frame, text="Search:") self.search_label.grid(column=0, row=0, sticky=E) self.search_entry = Entry(self.search_replace_frame, textvariable=self.cfg.search) self.search_entry.grid(column=1, row=0, sticky=N + S + W + E) self.search_entry.bind('<Return>', lambda arg: self.do_preview()) self.replace_label = Label(self.search_replace_frame, text="Replace:") self.replace_label.grid(column=0, row=1, sticky=E) self.replace_entry = Entry(self.search_replace_frame, textvariable=self.cfg.replace) self.replace_entry.grid(column=1, row=1, sticky=N + S + W + E) self.replace_entry.bind('<Return>', lambda arg: self.do_preview()) self.option_frame = Frame(self) self.option_frame.pack(side=TOP, fill=X, expand=0, pady=4) self.work_frame = LabelFrame(self.option_frame, text="Options") self.work_frame.pack(side=LEFT, padx=4, pady=4) self.ignore_case_checkbutton = Checkbutton( self.work_frame, text="ignore case", variable=self.cfg.ignore_case) self.ignore_case_checkbutton.pack(side=TOP, anchor=W, expand=0) self.create_backups_checkbutton = Checkbutton( self.work_frame, text="create backups", variable=self.cfg.create_backups) self.create_backups_checkbutton.pack(side=TOP, anchor=W, expand=0) self.preview_frame = LabelFrame(self.option_frame, text="Preview") self.preview_frame.pack(side=LEFT, padx=4, pady=4) self.show_full_content_checkbutton = Checkbutton( self.preview_frame, text="show full content", variable=self.cfg.show_full_content) self.show_full_content_checkbutton.pack(side=TOP, anchor=W, expand=0) self.show_original_checkbutton = Checkbutton( self.preview_frame, text="show original", variable=self.cfg.show_original) self.show_original_checkbutton.pack(side=TOP, anchor=W, expand=0) self.text_frame = Frame(self) self.text_frame.pack(side=TOP, fill=BOTH, expand=1, pady=4) self.text_frame.grid_columnconfigure(0, weight=1) self.text_frame.grid_rowconfigure(0, weight=1) self.scrollbar = Scrollbar(self.text_frame) self.scrollbar.grid(column=1, row=0, sticky=N + S) self.text = Text(self.text_frame, yscrollcommand=self.scrollbar.set, width=120, height=20) self.text.tag_config("file", background="lightgray", foreground="black") self.text.tag_config("search", background="lightblue", foreground="black") self.text.tag_config("replace", background="orange", foreground="black") self.text.tag_config("hollow", foreground="gray") self.text.tag_config("highlight", background="lightyellow") self.text.config(state=DISABLED) self.text.grid(column=0, row=0, sticky=N + S + W + E) self.scrollbar.config(command=self.text.yview) self.confirm_button_frame = Frame(self) self.confirm_button_frame.pack(side=BOTTOM, anchor=E) self.cancel_btn = Button(self.confirm_button_frame) self.cancel_btn["text"] = "Quit" self.cancel_btn["command"] = self.quit self.cancel_btn.grid(column=1, row=0, sticky=S, pady=8, padx=8) self.preview_btn = Button(self.confirm_button_frame) self.preview_btn["text"] = "Preview" self.preview_btn["command"] = self.do_preview self.preview_btn.grid(column=2, row=0, sticky=S, pady=8, padx=8) self.run_btn = Button(self.confirm_button_frame) self.run_btn["text"] = "Apply" self.run_btn["command"] = self.do_execute self.run_btn.grid(column=3, row=0, sticky=S, pady=8, padx=8) self.run_btn["state"] = 'disabled'
) ) devices_canvas.create_window((0,0), window=devices, anchor="nw") devices_canvas.configure(yscrollcommand=devices_scrollbar.set) search_button = Button(search_frame, text="SEARCH", width=8, command=lambda: ipPopulate(discoverIp())) add_button = Button(search_frame, text="ADD", width=8, state="disable", command=addDevice) ip_list = Listbox(search_frame, width=29, height=6, relief="flat") ip_list.insert(END, "Active LAN CONTROL first") sep = Separator(search_frame, orient="horizontal") devices_title = Label(search_frame, bg=bg_color, text="DEVICES", font=('Sans-serif', '15', 'bold')) info_lframe = LabelFrame(control_frame, text="Details", width=280, height=35) ip_info_label = Label(info_lframe, text="IP Address:") ip_label = Label(info_lframe, text="") model_info_label = Label(info_lframe, text="Model:") model_label = Label(info_lframe, text="") bulbImg = Label(control_frame, image=imgOff) on = Button(control_frame, text="ON", width=6, state="disable") off = Button(control_frame, text="OFF", width=6, state="disable") rgb = Button(control_frame, text="RGB", width=6, state="disable") delete = Button(control_frame, text="Delete", width=6, state="disable") brightnessInt = IntVar() brightness = Scale(control_frame, label="Brightness", variable=brightnessInt, repeatinterval=10, repeatdelay=150, orient="horizontal", length=250, from_=1.0, to=100, sliderlength=20, state="disable") tempInt = IntVar() temp = Scale(control_frame, label="Temp", variable=tempInt, orient="horizontal", resolution=100, length=250, from_=1700, to=6500, sliderlength=20, state="disable")
class MiniSedGUI(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.cfg = MiniSedConfig() self.source_directory = None self.target_directory = None self.create_widgets() self.pack(anchor=CENTER, fill=BOTH, expand=1) self.files_with_content = [] self.cfg.directory.trace('w', self.disable_apply) self.cfg.glob.trace('w', self.disable_apply) self.cfg.search.trace('w', self.disable_apply) self.cfg.replace.trace('w', self.disable_apply) self.cfg.ignore_case.trace('w', self.disable_apply) def disable_apply(self, *args): self.run_btn["state"] = 'disabled' def create_widgets(self): self.directory_frame = Frame(self) self.directory_frame.pack(side=TOP, fill=X, expand=0, padx=4, pady=4) self.directory_frame.grid_columnconfigure(1, weight=1) self.directory_label = Label(self.directory_frame, text="Directory:") self.directory_label.grid(column=0, row=0) self.directory_entry = Entry(self.directory_frame, textvariable=self.cfg.directory) self.directory_entry.grid(column=1, row=0, sticky=W + E) self.directory_entry.bind('<Return>', lambda arg: self.do_preview()) self.directory_button = Button(self.directory_frame, text="Browse") self.directory_button["command"] = lambda: do_ask_directory(self.cfg.directory) self.directory_button.grid(column=2, row=0) self.glob_label = Label(self.directory_frame, text="Glob:") self.glob_label.grid(column=0, row=1, stick=E) self.glob_entry = Entry(self.directory_frame, textvariable=self.cfg.glob) self.glob_entry.bind('<Return>', lambda arg: self.do_preview()) self.glob_entry.grid(column=1, row=1, sticky=N + S + W) self.search_replace_frame = Frame(self) self.search_replace_frame.grid_columnconfigure(1, weight=1) self.search_replace_frame.pack(anchor=N, side=TOP, fill=X, expand=0, padx=4, pady=4) self.search_label = Label(self.search_replace_frame, text="Search:") self.search_label.grid(column=0, row=0, sticky=E) self.search_entry = Entry(self.search_replace_frame, textvariable=self.cfg.search) self.search_entry.grid(column=1, row=0, sticky=N + S + W + E) self.search_entry.bind('<Return>', lambda arg: self.do_preview()) self.replace_label = Label(self.search_replace_frame, text="Replace:") self.replace_label.grid(column=0, row=1, sticky=E) self.replace_entry = Entry(self.search_replace_frame, textvariable=self.cfg.replace) self.replace_entry.grid(column=1, row=1, sticky=N + S + W + E) self.replace_entry.bind('<Return>', lambda arg: self.do_preview()) self.option_frame = Frame(self) self.option_frame.pack(side=TOP, fill=X, expand=0, pady=4) self.work_frame = LabelFrame(self.option_frame, text="Options") self.work_frame.pack(side=LEFT, padx=4, pady=4) self.ignore_case_checkbutton = Checkbutton( self.work_frame, text="ignore case", variable=self.cfg.ignore_case) self.ignore_case_checkbutton.pack(side=TOP, anchor=W, expand=0) self.create_backups_checkbutton = Checkbutton( self.work_frame, text="create backups", variable=self.cfg.create_backups) self.create_backups_checkbutton.pack(side=TOP, anchor=W, expand=0) self.preview_frame = LabelFrame(self.option_frame, text="Preview") self.preview_frame.pack(side=LEFT, padx=4, pady=4) self.show_full_content_checkbutton = Checkbutton( self.preview_frame, text="show full content", variable=self.cfg.show_full_content) self.show_full_content_checkbutton.pack(side=TOP, anchor=W, expand=0) self.show_original_checkbutton = Checkbutton( self.preview_frame, text="show original", variable=self.cfg.show_original) self.show_original_checkbutton.pack(side=TOP, anchor=W, expand=0) self.text_frame = Frame(self) self.text_frame.pack(side=TOP, fill=BOTH, expand=1, pady=4) self.text_frame.grid_columnconfigure(0, weight=1) self.text_frame.grid_rowconfigure(0, weight=1) self.scrollbar = Scrollbar(self.text_frame) self.scrollbar.grid(column=1, row=0, sticky=N + S) self.text = Text(self.text_frame, yscrollcommand=self.scrollbar.set, width=120, height=20) self.text.tag_config("file", background="lightgray", foreground="black") self.text.tag_config("search", background="lightblue", foreground="black") self.text.tag_config("replace", background="orange", foreground="black") self.text.tag_config("hollow", foreground="gray") self.text.tag_config("highlight", background="lightyellow") self.text.config(state=DISABLED) self.text.grid(column=0, row=0, sticky=N + S + W + E) self.scrollbar.config(command=self.text.yview) self.confirm_button_frame = Frame(self) self.confirm_button_frame.pack(side=BOTTOM, anchor=E) self.cancel_btn = Button(self.confirm_button_frame) self.cancel_btn["text"] = "Quit" self.cancel_btn["command"] = self.quit self.cancel_btn.grid(column=1, row=0, sticky=S, pady=8, padx=8) self.preview_btn = Button(self.confirm_button_frame) self.preview_btn["text"] = "Preview" self.preview_btn["command"] = self.do_preview self.preview_btn.grid(column=2, row=0, sticky=S, pady=8, padx=8) self.run_btn = Button(self.confirm_button_frame) self.run_btn["text"] = "Apply" self.run_btn["command"] = self.do_execute self.run_btn.grid(column=3, row=0, sticky=S, pady=8, padx=8) self.run_btn["state"] = 'disabled' def do_preview(self): directory = self.cfg.directory.get() self.text.config(state=NORMAL) self.text.delete("1.0", END) self.text.config(state=DISABLED) self.files_with_content = [] for path, dirs, files in os.walk(directory): for fname in files: filename = os.path.join(path, fname) if not self.cfg.glob.get() or fnmatch.fnmatch(fname.lower(), self.cfg.glob.get().lower()): with open(filename, 'rt', encoding='latin-1') as fin: lines = fin.read().splitlines() lines = minised_on_lines(lines, self.cfg.search.get(), self.cfg.replace.get(), self.cfg.ignore_case.get()) self.files_with_content.append((filename, lines)) self.text.config(state=NORMAL) self.text.insert(END, "%s:\n" % filename, "file") for line in lines: if isinstance(line, tuple): if self.cfg.show_original.get(): self.text.insert(END, "%s" % line[0], "hollow") self.text.insert(END, "%s" % line[1], "search") self.text.insert(END, "%s\n" % line[3], "hollow") self.text.insert(END, "%s" % line[0], "highlight") self.text.insert(END, "%s" % line[2], "replace") self.text.insert(END, "%s" % line[3], "highlight") self.text.insert(END, "\n") elif self.cfg.show_full_content.get(): self.text.insert(END, "%s\n" % line) self.text.insert(END, "\n") self.text.config(state=DISABLED) self.master.update() self.run_btn["state"] = 'normal' def do_execute(self): for filename, lines in self.files_with_content: if self.cfg.create_backups.get(): os.rename(filename, filename + "~") with open(filename, 'wt', encoding='latin-1', newline='\r\n') as fout: for line in lines: if isinstance(line, tuple): fout.write(line[0]) fout.write(line[2]) fout.write(line[3]) else: fout.write(line) fout.write("\n") self.run_btn["state"] = 'disabled' tkinter.messagebox.showinfo("Replacement successful", "Replacements have been performed successfully on the files")
def Settings(self): tl = Toplevel(root) tl.title("Global settings") frame = Frame(tl) frame.grid() machineFrame = LabelFrame(frame, text="Machine hoop workarea (mm)", relief=RIDGE) machineFrame.grid() Label(machineFrame, text="width ").grid(row=0, column=0, sticky=N) workareaWidth = Entry(machineFrame, text="1") workareaWidth.grid(row=0, column=1) Label(machineFrame, text="height ").grid(row=2, column=0, sticky=N) workareaHeight = Entry(machineFrame, text="2") workareaHeight.grid(row=2, column=1) hoopFrame = LabelFrame(frame, text="Machine hoop origin (mm)", relief=RIDGE) hoopFrame.grid() Label(hoopFrame, text="X ").grid(row=0, column=0, sticky=N) workareaOriginX = Entry(hoopFrame, text="3") workareaOriginX.grid(row=0, column=1) Label(hoopFrame, text="Y ").grid(row=2, column=0, sticky=N) workareaOriginY = Entry(hoopFrame, text="4") workareaOriginY.grid(row=2, column=1) Label(hoopFrame, text="Setup name ").grid(row=3, column=0, sticky=N) setupName = Entry(hoopFrame, text="Setup1") setupName.grid(row=3, column=1) def setupSelected(event=None): if event: selectedSetupName = setupsCombo.get() else: selectedSetupName = self.currentSetupName workareaWidth.delete(0, END) workareaWidth.insert( 0, str(self.machineSetups[selectedSetupName]["workAreaSize"][0])) workareaHeight.delete(0, END) workareaHeight.insert( 0, str(self.machineSetups[selectedSetupName]["workAreaSize"][1])) workareaOriginX.delete(0, END) workareaOriginX.insert( 0, str(self.machineSetups[selectedSetupName]["workAreaOrigin"] [0])) workareaOriginY.delete(0, END) workareaOriginY.insert( 0, str(self.machineSetups[selectedSetupName]["workAreaOrigin"] [1])) setupName.delete(0, END) setupName.insert(0, selectedSetupName) setupSelected() setupsCombo = ttk.Combobox(frame, values=list(self.machineSetups.keys()), state="readonly") setupsCombo.grid(row=2, column=0) setupsCombo.current(setupsCombo['values'].index(self.currentSetupName)) setupsCombo.bind("<<ComboboxSelected>>", setupSelected) def addSettings(): newSetupName = setupName.get() if newSetupName in self.machineSetups.keys(): if not messagebox.askyesno( "Machine setup exists", "Machine setup with this name exists. Overwrite?"): return newSetup = { "workAreaSize": (int(workareaWidth.get()), int(workareaHeight.get())), "workAreaOrigin": (int(workareaOriginX.get()), int(workareaOriginY.get())) } self.machineSetups[newSetupName] = newSetup setupsCombo['values'] = list(self.machineSetups.keys()) Button(frame, relief=RAISED, command=addSettings, text="Add setup").grid(row=2, column=1) def removeSetup(): self.machineSetups.pop(setupsCombo.get(), None) options = list(self.machineSetups.keys()) setupsCombo['values'] = options if len(options) > 0: self.currentSetupName = list(self.machineSetups.keys())[0] setupsCombo.current(0) setupSelected(1) Button(frame, relief=RAISED, command=removeSetup, text="Remove setup").grid(row=2, column=2) def saveSettings(): try: if len(setupsCombo.get()) > 0: self.workAreaSize = (int(workareaWidth.get()), int(workareaHeight.get())) self.workAreaOrigin = (int(workareaOriginX.get()), int(workareaOriginY.get())) self.currentSetupName = setupsCombo.get() except: messagebox.showerror( "Invalid numeric values", "Please provide correct workarea values!") return self.canvas.setArea(self.workAreaSize[0], self.workAreaSize[1]) self.canvas.setOrigin(self.workAreaOrigin[0], self.workAreaOrigin[1]) self.storeSettings() TmpDim = namedtuple('TmpDim', 'width height') tmp = TmpDim(self.canvas.width, self.canvas.height) self.canvas.on_resize(tmp) Button(frame, text="Save", command=saveSettings, width=10).grid(row=3, column=3) Button(frame, text="Close", command=lambda: tl.destroy(), width=10).grid(row=3, column=2)
def show_streams_mediainfo_function(x): # Stream Viewer global stream_win_text_area, exit_stream_window, stream_window video_input = pathlib.Path(x) # "x" is passed through from main GUI # Defines the path to config.ini and opens it for reading/writing config_file = 'Runtime/config.ini' # Creates (if it doesn't exist) and defines location of config.ini config = ConfigParser() config.read(config_file) detect_font = font.nametofont("TkDefaultFont") # Get default font value into Font object set_font = detect_font.actual().get("family") # set_font_size = detect_font.actual().get("size") try: stream_win_text_area.config(state=NORMAL) stream_win_text_area.delete(1.0, END) except (NameError, TclError): stream_window = Toplevel() stream_window.title("Audio Streams") stream_window.configure(background="#434547") stream_window.resizable(False, False) # Disable resize of this window if config['save_window_locations']['audio window - view streams - position'] != '' and \ config['save_window_locations']['audio window - view streams'] == 'yes': stream_window.geometry(config['save_window_locations']['audio window - view streams - position']) stream_window.protocol('WM_DELETE_WINDOW', exit_stream_window) stream_window.grid_columnconfigure(0, weight=1) stream_window.grid_rowconfigure(0, weight=1) stream_window_frame = LabelFrame(stream_window, text=' Audio Streams ', labelanchor="n") stream_window_frame.grid(column=0, row=0, columnspan=1, padx=5, pady=(0, 3), sticky=N + S + E + W) stream_window_frame.configure(fg="#3498db", bg="#434547", bd=3, font=(set_font, 10, "bold")) stream_window_frame.grid_rowconfigure(0, weight=1) stream_window_frame.grid_columnconfigure(0, weight=1) stream_win_text_area = scrolledtext.ScrolledText(stream_window_frame, width=80, height=25, tabs=10, spacing2=3, spacing1=2, spacing3=3) stream_win_text_area.config(bg='black', fg='#CFD2D1', bd=8) stream_win_text_area.grid(column=0, pady=5, padx=5, sticky=N + E + S + W) character_space = 30 # Can be changed to adjust space of all items in the list automatically media_info = MediaInfo.parse(video_input) # Uses pymediainfo to get information for track selection for track in media_info.tracks: # For loop to loop through mediainfo tracks # Formatting -------------------------------------------------------------------------------------------------- if track.track_type == 'Audio': # Only grab audio track information if str(track.stream_identifier) != 'None': # Gets stream # audio_track_id_space = 'Track#' + ' ' * int(f'{character_space - len("Track#")}') audio_track_id = audio_track_id_space + f': {str(int(track.stream_identifier) + 1)}\n' else: audio_track_id = '' if str(track.format) != 'None': # Gets format string of tracks (aac, ac3 etc...) audio_format_space = 'Codec' + ' ' * int(f'{character_space - len("Codec")}') audio_format = audio_format_space + f": {str(track.commercial_name)} - ({str(track.format).lower()})\n" else: audio_format = '' if str(track.channel_s) != 'None': # Gets audio channels of input tracks audio_channel_space = 'Channels' + ' ' * int(f'{character_space - len("Channels")}') if str(track.channel_s) == '8': show_channels = '7.1' elif str(track.channel_s) == '6': show_channels = '5.1' elif str(track.channel_s) == '3': show_channels = '2.1' else: show_channels = str(track.channel_s) audio_channels = audio_channel_space + f": {show_channels} - {str(track.channel_layout)}\n" else: audio_channels = '' if str(track.bit_rate_mode) != 'None': # Gets audio bit rate mode audio_bitrate_mode_space = 'Bit rate mode' + ' ' * int(f'{character_space - len("Bit rate mode")}') if str(track.other_bit_rate_mode) != 'None': # Get secondary string of audio bit rate mode audio_bitrate_mode = audio_bitrate_mode_space + f": {str(track.bit_rate_mode)} / " \ f"{str(track.other_bit_rate_mode[0])}\n" else: audio_bitrate_mode = audio_bitrate_mode_space + f": {str(track.bit_rate_mode)}\n" else: audio_bitrate_mode = '' if str(track.other_bit_rate) != 'None': # Gets audio bit rate of input tracks audio_bitrate_space = 'Bit rate' + ' ' * int(f'{character_space - len("Bit rate")}') audio_bitrate = audio_bitrate_space + f": {str(track.other_bit_rate[0])}\n" else: audio_bitrate = '' if str(track.other_language) != 'None': # Gets audio language of input tracks audio_language_space = 'Language' + ' ' * int(f'{character_space - len("Language")}') audio_language = audio_language_space + f": {str(track.other_language[0])}\n" else: audio_language = '' if str(track.title) != 'None': # Gets audio title of input tracks audio_title_space = 'Title' + ' ' * int(f'{character_space - len("Title")}') if len(str(track.title)) > 40: # Counts title character length audio_title = audio_title_space + f": {str(track.title)[:40]}...\n" # If title > 40 characters else: audio_title = audio_title_space + f": {str(track.title)}\n" # If title is < 40 characters else: audio_title = '' if str(track.other_sampling_rate) != 'None': # Gets audio sampling rate of input tracks audio_sampling_rate_space = 'Sampling Rate' + ' ' * int(f'{character_space - len("Sampling Rate")}') audio_sampling_rate = audio_sampling_rate_space + f": {str(track.other_sampling_rate[0])}\n" else: audio_sampling_rate = '' if str(track.other_duration) != 'None': # Gets audio duration of input tracks audio_duration_space = 'Duration' + ' ' * int(f'{character_space - len("Duration")}') audio_duration = audio_duration_space + f": {str(track.other_duration[0])}\n" else: audio_duration = '' if str(track.delay) != 'None': # Gets audio delay of input tracks if str(track.delay) == '0': audio_delay = '' else: audio_delay_space = 'Delay' + ' ' * int(f'{character_space - len("Delay")}') audio_del_to_vid_space = 'Delay to Video' + ' ' * int(f'{character_space - len("Delay to Video")}') audio_delay = audio_delay_space + f': {str(track.delay)}ms\n' \ + audio_del_to_vid_space + f': {str(track.delay_relative_to_video)}ms\n ' else: audio_delay = '' if str(track.other_stream_size) != 'None': # Get tracks stream size audio_track_size_space = 'Stream size' + ' ' * int(f'{character_space - len("Stream size")}') audio_track_stream_size = audio_track_size_space + f": {str(track.other_stream_size[4])}\n" else: audio_track_stream_size = '' if str(track.other_bit_depth) != 'None': # Get tracks bit-depth audio_track_b_depth_space = 'Bit Depth' + ' ' * int(f'{character_space - len("Bit Depth")}') audio_track_bit_depth = audio_track_b_depth_space + f": {(track.other_bit_depth[0])}\n" else: audio_track_bit_depth = '' if str(track.compression_mode) != 'None': audio_track_compression_space = 'Compression' + ' ' * int(f'{character_space - len("Compression")}') audio_track_compression = audio_track_compression_space + f": {str(track.compression_mode)}\n" else: audio_track_compression = '' if str(track.default) != 'None': # Get tracks default boolean audio_track_default_space = 'Default' + ' ' * int(f'{character_space - len("Default")}') audio_track_default = audio_track_default_space + f": {str(track.default)}\n" else: audio_track_default = '' if str(track.forced) != 'None': # Get tracks forced boolean audio_track_forced_space = 'Forced' + ' ' * int(f'{character_space - len("Forced")}') audio_track_forced = audio_track_forced_space + f": {str(track.forced)}" else: audio_track_forced = '' # ---------------------------------------------------------------------------------------------- Formatting audio_track_info = str(audio_track_id + audio_format + audio_channels + audio_bitrate_mode + audio_bitrate + audio_sampling_rate + audio_delay + audio_duration + audio_language + audio_title + audio_track_stream_size + audio_track_bit_depth + audio_track_compression + audio_track_default + audio_track_forced) # Formatting media_info_track_string = 80 * '#' + '\n' + audio_track_info + '\n' + 80 * '#' + '\n' # String to insert stream_win_text_area.configure(state=NORMAL) # Enable textbox stream_win_text_area.insert(INSERT, media_info_track_string) # Insert string stream_win_text_area.insert(INSERT, '\n') # Insert a newline stream_win_text_area.configure(state=DISABLED) # Disable textbox def right_click_menu_func(x_y_pos): # Function for mouse button 3 (right click) to pop up menu right_click_menu.tk_popup(x_y_pos.x_root, x_y_pos.y_root) # This gets the position of cursor def copy_selected_text(): # Function to copy only selected text pya_hotkey('ctrl', 'c') time_sleep(.01) # Slow program incase ctrl+c is slower right_click_menu = Menu(stream_window, tearoff=False) # This is the right click menu right_click_menu.add_command(label='Copy Selected Text', command=copy_selected_text) right_click_menu.add_command(label='Copy All Text', command=pyperclip_copy(stream_win_text_area.get(1.0, END))) stream_window.bind('<Button-3>', right_click_menu_func) # Uses mouse button 3 (right click) to pop up menu Hovertip(stream_win_text_area, 'Right click to copy', hover_delay=1200) # Hover tip tool-tip
def __init__(self, master=None): # setup tab objects self.master = master self.navigation_tabs = ttk.Notebook(self.master) self.setup = Frame(self.navigation_tabs) self.setup.pack() self.title_container = Frame(self.setup) self.title = Label(self.title_container, text="SNMP Manager") self.create_title() self.agent_container = Frame(self.setup) self.agent_label = Label(self.agent_container, text="Agent IP:", font=font, width=label_width) self.agent = Entry(self.agent_container) self.create_agent() self.community_container = Frame(self.setup) self.community_label = Label(self.community_container, text="Community:", font=font, width=label_width) self.community = Entry(self.community_container) self.create_community() self.object_container = Frame(self.setup) self.object_label = Label(self.object_container, text="Object instance:", font=font, width=label_width) self.object = Entry(self.object_container) self.create_object() self.time_container = Frame(self.setup) self.time_label = Label(self.time_container, text="Refresh time (s):", font=font, width=label_width) validation = self.time_container.register(only_numbers) self.time = Entry(self.time_container, validate="key", validatecommand=(validation, '%S')) self.create_charts = False self.create_time() self.buttons_container = Frame(self.setup) self.get_object = Button(self.buttons_container, text="Get Object", font=font, width=button_width) self.settings = Button(self.buttons_container, text="Settings", font=font, width=button_width) self.start_monitor = Button(self.buttons_container, text="Start monitor", font=font, width=button_width) self.stop_monitor = Button(self.buttons_container, text="Stop monitor", font=font, width=button_width) self.create_setup_buttons() # results frames self.result_tabs = ttk.Notebook(self.setup) self.response_label_frame = LabelFrame(self.result_tabs, font=font) self.response_value = StringVar(self.response_label_frame) self.response_text = Text(self.response_label_frame, font=font) self.warning_label_frame = LabelFrame(self.result_tabs, font=font) self.warning_value = StringVar(self.warning_label_frame) self.warning_text = Text(self.warning_label_frame, font=font) self.create_result() # charts objects self.link_chart = Frame(self.navigation_tabs) self.ip_chart = Frame(self.navigation_tabs) self.tcp_chart = Frame(self.navigation_tabs) self.udp_chart = Frame(self.navigation_tabs) self.icmp_chart = Frame(self.navigation_tabs) self.snmp_chart = Frame(self.navigation_tabs) self.create_charts_frames() self.assemble_tabs() # placeholders self.threads = None self.link = 0 self.input_octets = 0 self.output_octets = 0 self.link_list = [] self.ip_send = 0 self.ip_receive = 0 self.ip_send_list = [] self.ip_receive_list = [] self.tcp_send = 0 self.tcp_receive = 0 self.tcp_send_list = [] self.tcp_receive_list = [] self.udp_send = 0 self.udp_receive = 0 self.udp_send_list = [] self.udp_receive_list = [] self.icmp_send = 0 self.icmp_receive = 0 self.icmp_send_list = [] self.icmp_receive_list = [] self.snmp_send = 0 self.snmp_receive = 0 self.snmp_send_list = [] self.snmp_receive_list = []
class Main: def __init__(self, root): self.root = root self.root.title('计算器一代') self.center_window(self.root, 300, 240) self.root.maxsize(200, 200) self.root.minsize(200, 200) self.menuBar = Menu(self.root) self.root.config(menu=self.menuBar) aboutMenu = Menu(self.menuBar, tearoff=0) # 创建一个下拉菜单‘功能’,这个菜单是挂在menubar(顶级菜单)上的 FuncMenu = Menu(self.menuBar, tearoff=0) # 用add_cascade()将菜单添加到顶级菜单中,按添加顺序排列 self.menuBar.add_cascade(label='功能', menu=FuncMenu) self.menuBar.add_cascade(label='帮助', menu=aboutMenu) # 下拉菜单的具体项目,使用add_command()方法 aboutMenu.add_command(label='关于..', command=self.About) FuncMenu.add_command(label='小键盘计算', command=self.Fun2) FuncMenu.add_command(label='表达式计算', command=self.Fun1) self.label = Label(self.root, text='欢迎使用!', font=14).pack(side=TOP) self.group = LabelFrame(self.root, text='您想进行的操作是:', padx=5, pady=5) self.group.pack(padx=10, pady=10) self.Key = [('小键盘计算', 1), ('表达式计算', 2)] self.v = IntVar() self.v.set(1) for m, n in self.Key: b = Radiobutton(self.group, text=m, variable=self.v, value=n) b.pack(anchor=W) self.button1 = Button(self.root, text='确定', command=self.show, padx=10) self.button2 = Button(self.root, text='退出', command=self.root.quit, padx=10) self.button1.pack(side=RIGHT) self.button2.pack(side=LEFT) self.root.bind('<Return>', self.show) def center_window(self, root, width, height): screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) root.geometry(size) def show(self, event): if self.v.get() == 1: newwin = Toplevel() app = Application(newwin) # 设置窗口标题: app.master.title('计算器') # 主消息循环: app.master.mainloop() elif self.v.get() == 2: newwin = Toplevel() e = Biaodashi(newwin) e.root.mainloop() def About(self): messagebox.showinfo('关于', 'Ver 1.0 \n--------\nBy Mark\n') def Fun1(self): messagebox.showinfo('表达式计算', '输入计算的数学表达式即可\n• 请使用半角符号\n• 请注意乘方请以**表示') def Fun2(self): messagebox.showinfo('小键盘计算', '点击数字以及符号按键计算即可\n仅支持简单计算')
high_predicted_data_list = \ sorted(data_list, key=lambda x: x['evaluate'], reverse=True) high_scored_data_list = \ sorted(data_list, key=lambda x: x['score'], reverse=True) root = Tk() root.attributes('-topmost', True) disp_num = 4 target_width = 300 target_height = \ int(target_width/image_enhancer.org_width*image_enhancer.org_height) high_predict_frame = LabelFrame(root, text='predict') for predicted_data in high_predicted_data_list[:disp_num]: frame = \ EvaluatedCanvasFrame(high_predict_frame, target_width, target_height, predicted_data['score'], predicted_data['evaluate']) frame.pack(side=LEFT) frame.canvas.update_image(predicted_data['image']) high_predict_frame.pack(pady=10) high_score_frame = LabelFrame(root, text='score') for scored_data in high_scored_data_list[:disp_num]: frame = \ EvaluatedCanvasFrame(high_score_frame,
def init(): global canvas, control_frame, directory_name_frames, durationframe,\ ecg1, ecg2, root, figure, file_path, font_heading, Fs, headers,\ labels, plot, plotframe, result_frame, root, row_count SHEET_NAME, time,\ times, toolbar, toolbarframe ecg1 = list() ecg2 = list() file_path = "" font_heading = "sans-serif 12" Fs = 250 headers = 3 result_frame = "" root = Tk() root.title("HR variability") root.geometry("900x600") row_count = 0 SHEET_NAME = 'ECG' time = list() # Define frames for plot and navigation toolbar to allow grid/pack to work together plotframe = Frame(root) toolbarframe = Frame(root) # Initialize figure/plot plt.gcf().subplots_adjust(bottom=0.15) figure = plt.figure(figsize=(6, 3), dpi=100) plot = figure.add_subplot(1, 1, 1) # Set x-y plot labels plot.set_ylabel("Amplitude (mV)") plot.set_xlabel(xlabel="Time (s)") # Ensure spacing between axes and x-ylabels plt.tight_layout() # Initialize plot and toolbar widgits canvas = FigureCanvasTkAgg(figure, plotframe) toolbar = NavigationToolbar(canvas, toolbarframe) # Initialize control, duration and result frame/boxes directory_name_frames = Frame(root, pady=3) durationframe = LabelFrame(root, text="Trial duration", font=font_heading, pady=3) control_frame = LabelFrame(root, text="Plot controls", font=font_heading, pady=3) result_frame = LabelFrame(root, text="Trial detials", font=font_heading, pady=3) # Initialize times dictionary containing user input objects to pass to display times= { "start_hr" : Entry(durationframe, width=5), "start_min" : Entry(durationframe, width=5), "start_sec" : Entry(durationframe, width=5), "end_hr" : Entry(durationframe, width=5), "end_min" : Entry(durationframe, width=5), "end_sec" : Entry(durationframe, width=5), } # Initialize labels dictionary containing Label objects to pass to display labels = { "file" : Label(directory_name_frames, text="File pending selection...", font=font_heading), "hr" : Label(durationframe, text="hr", font=font_heading), "min" : Label(durationframe, text="min", font=font_heading), "sec" : Label(durationframe, text="sec", font=font_heading), "start" : Label(durationframe, text="Start time", font=font_heading), "end" : Label(durationframe, text="End time", font=font_heading), "duration_trial" : Label(result_frame, text="Selected duration: ", font=font_heading), "hr_var" : Label(result_frame, text="HR variability (s): ", font=font_heading), "duration_trial_max" : Label(result_frame, text="Max. trial duration: ", font=font_heading), }
class BornDigitalGUI(Frame): def __init__(self, master): ##### Configure Canvas ##### Frame.__init__(self, master) self.master = master self.canvas = Canvas(master, borderwidth=0) self.frame = Frame(self.canvas) self.canvas.create_window((4,4), window=self.frame, anchor='nw', tags='self.frame') self.master.title('Born Digital Accessioner 1.0') self.initmenu() self.frame.config(bg='gainsboro', highlightthickness=0) self.canvas.config(bg='gainsboro', highlightthickness=0) self.canvas.grid_rowconfigure(0, weight=1) self.canvas.grid_columnconfigure(0, weight=1) self.frame.grid_rowconfigure(0, weight=1) self.frame.grid_columnconfigure(0, weight=1) self.master.grid_rowconfigure(0, weight=1) self.master.grid_columnconfigure(0, weight=1) self.canvas.grid(row=0, column=0, sticky="nsew") self.frame.grid(row=0, column=0, sticky="nsew") ##### Execute login process by pressing Enter #### self.master.bind('<Return>', self.asloginprocess) ########### Step 1: Login to ArchivesSpace API ########### ## Set Step 1 Variable Inputs ## self.authenticate = StringVar() self.api_url = StringVar() self.username = StringVar() self.password = StringVar() self.login_confirmed = StringVar() ## Create Step 1 Widgets ## self.login_labelframe = LabelFrame(self.frame, text='Step 1: Connect to ArchivesSpace', font=('Arial', 14), bg='gainsboro', padx=1, pady=1) self.api_url_label = Label(self.login_labelframe, text='ArchivesSpace URL: ', font=('Arial', 13), bg='gainsboro') self.username_label = Label(self.login_labelframe, text='ArchivesSpace Username: '******'Arial', 13), bg='gainsboro') self.password_label = Label(self.login_labelframe, text='ArchivesSpace Password: '******'Arial', 13), bg='gainsboro') self.api_url_entry = Entry(self.login_labelframe, width=32, textvariable=self.api_url, highlightthickness=0) self.username_entry = Entry(self.login_labelframe, width=32, textvariable=self.username, highlightthickness=0) self.password_entry =Entry(self.login_labelframe, width=32, textvariable=self.password, show='*', highlightthickness=0) self.login_confirmed_variable = Label(self.login_labelframe, textvariable=self.login_confirmed, width=25, font=('Arial', 13), bg='gainsboro', highlightthickness=0, anchor='e') self.connect_button = Button(self.login_labelframe, text='Connect!',command=self.asloginprocess, width=10, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Set Step 1 Widget Layout ## self.login_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.login_labelframe.grid_rowconfigure(0, weight=1) self.login_labelframe.grid_columnconfigure(0, weight=1) self.api_url_label.grid(column=0, row=2, sticky="nw") self.api_url_entry.grid(column=0, row=3, sticky="nw") self.username_label.grid(column=0, row=4, sticky="nw") self.username_entry.grid(column=0, row=5, sticky="nw") self.password_label.grid(column=0, row=6, sticky="nw") self.password_entry.grid(column=0, row=7, sticky="nw") self.login_confirmed_variable.grid(column=1, row=6, sticky="ns") self.connect_button.grid(column=1, row=7, sticky="ne") ########### Step 2: Select Input CSV ########### ## Set Step 2 Variable Inputs ## self.csv_filename = StringVar() ## Create Step 2 Widgets ## self.fileselect_labelframe = LabelFrame(self.frame, text='Step 2: Select Input CSV', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.file_selected_label = Label(self.fileselect_labelframe, text='Selection: ', font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.selected_csv_variable = Label(self.fileselect_labelframe, textvariable=self.csv_filename, width=65, font=('Arial', 11), anchor='w', bg='gainsboro', highlightthickness=0) self.input_csv_button = Button(self.fileselect_labelframe, text='Select File', command=self.csvbutton, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 2 Layout ## self.fileselect_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.fileselect_labelframe.grid_rowconfigure(0, weight=1) self.fileselect_labelframe.grid_columnconfigure(0, weight=1) self.input_csv_button.grid(column=1, row=9, sticky='se') self.file_selected_label.grid(column=0, columnspan=1, row=10, sticky='w') self.selected_csv_variable.grid(column=0, row=11, columnspan=2, sticky='w') ## Set Step _ Variable Inputs ## self.csv_output = StringVar() ########### Step 3: Choose an Action ########### ## Create Step 3 Widgets ## self.action_labelframe = LabelFrame(self.frame, text='Step 3: Choose Action', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.create_components_button = Button(self.action_labelframe, text='Create records', width=30, command=self.run_create_script, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.update_components_button = Button(self.action_labelframe, text='Update records', width=30, command=self.run_update_script, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 3 Layout ## self.action_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.action_labelframe.grid_rowconfigure(0, weight=1) self.action_labelframe.grid_columnconfigure(0, weight=1) self.create_components_button.grid(row=12, columnspan=2) self.update_components_button.grid(row=13, columnspan=2) ########### Step 4: Review Output ########### ## Set Step 4 Variable Inputs ## self.update_attempts = StringVar() self.updates_success = StringVar() self.elapsed_time = StringVar() self.log_file = StringVar() self.error_dialog = StringVar() self.script_status = StringVar() self.parent_id = StringVar() self.resource_id = StringVar() self.repo_id_no = StringVar() ## Create Step 4 Widgets ## self.output_labelframe = LabelFrame(self.frame, text='Step 4: Review Output', font=('Arial', 14), bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.script_status_variable = Label(self.output_labelframe, textvariable=self.script_status, font=('Arial', 13), anchor='e', bg='gainsboro', highlightthickness=0) self.record_updates_attempted_label = Label(self.output_labelframe, text='Record updates attempted: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.record_updates_attempted_variable = Label(self.output_labelframe, textvariable=self.update_attempts, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.records_updated_successsfully_label = Label(self.output_labelframe, text='Records updated successfully: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.records_updated_successsfully_variable = Label(self.output_labelframe, textvariable=self.updates_success, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.elapsed_time_label = Label(self.output_labelframe, text='Elapsed time: ', width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.elapsed_time_variable = Label(self.output_labelframe, textvariable=self.elapsed_time, width=30, font=('Arial', 13), anchor='w', bg='gainsboro', highlightthickness=0) self.view_output_file_button = Button(self.output_labelframe, text='Open Output File', command=self.opencsvoutput, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.view_error_log_button = Button(self.output_labelframe, text='Open Log', command=self.openerrorlog, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") self.view_url_button = Button(self.output_labelframe, text='Open in ArchivesSpace', command=self.openparent_record, relief=RAISED, bd=1, padx=3, pady=3, highlightthickness=0, cursor="hand1") ## Set Step 5 Layout ## self.output_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.output_labelframe.grid_rowconfigure(0, weight=1) self.output_labelframe.grid_columnconfigure(0, weight=1) self.script_status_variable.grid(column=1, row=14, sticky='e') self.record_updates_attempted_label.grid(column=0, row=15) self.records_updated_successsfully_label.grid(column=0, row=16) self.elapsed_time_label.grid(column=0, row=17) self.record_updates_attempted_variable.grid(column=1, row=15, sticky='w') self.records_updated_successsfully_variable.grid(column=1, row=16, sticky='w') self.elapsed_time_variable.grid(column=1, row=17, sticky='w') self.view_output_file_button.grid(column=1, row=18, sticky="ne") self.view_error_log_button.grid(column=1, row=19, sticky="ne") self.view_url_button.grid(column=1, row=20, sticky="ne") ## Clear Inputs, Help Buttons self.clear_labelframe = LabelFrame(self.frame, text=None, bg='gainsboro', highlightthickness=0, padx=1, pady=1) self.clear_labelframe.grid(column=0, columnspan=2, sticky="nsew", padx=5, pady=5) self.clear_labelframe.grid_rowconfigure(0, weight=1) self.clear_labelframe.grid_columnconfigure(0, weight=1) self.clear_all_inputs_button = Button(self.clear_labelframe, text='Clear Inputs', command=self.clear_inputs, relief=RAISED, bd=1, padx=5, pady=5, highlightthickness=0, cursor="hand1") self.clear_all_inputs_button.grid(column=0, row=21) #Initiates error logging self.error_log() ####### Functions ######### #initializes file menu - see https://stackoverflow.com/questions/34442626/why-is-the-menu-not-showing-on-my-tkinter-gui/34442773 def initmenu(self): menubar = Menu(self.master) self.master.config(menu=menubar) filemenu = Menu(menubar) filemenu.add_command(label='Help', command=self.new_window) filemenu.add_command(label='Template', command=self.open_template) filemenu.add_command(label="Exit", command=self.client_exit) menubar.add_cascade(label="File", menu=filemenu) #Opens the help file in a new window def new_window(self): self.newwindow = Toplevel(self.master) self.newwindow.title('Born-Digital Accessioner Help') f = open('./files/bd_accessioner_help.txt', 'r', encoding='utf-8') self.textbox = Text(self.newwindow, width=115) self.textbox.pack(side='top', fill='both', expand=True) self.textbox.insert(0.0, f.read()) self.textbox.config(state=DISABLED, wrap=WORD) self.textbox.grid_rowconfigure(0, weight=1) self.textbox.grid_columnconfigure(0, weight=1) #exits program def client_exit(self): self.quit() #opens the born-dig-accessioner template in the system's default program def open_template(self): #Open template file if sys.platform == "win32": os.startfile('./files/Template_Digital_Accessioning_Service_Metadata_102017.xlsx') else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, './files/Template_Digital_Accessioning_Service_Metadata_102017.xlsx']) #logs in to ArchivesSpace API def asloginprocess(self, event=None): try: #basic/imperfect check for improperly formatted URLs urlcheck = re.compile( r'^https?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' r'localhost|' r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' r'(?::\d+)?' r'(?:/?|[/?]\S+)$', re.IGNORECASE) #if URL field is empty; missing field error checks may be obsolete now but I'm leaving it in because the URL checks may not be perfect if self.api_url.get() == '': self.login_confirmed.set('Missing value, try again') #empty username field if self.username.get() == '': self.login_confirmed.set('Missing value, try again') #empty password field if self.password.get() == '': self.login_confirmed.set('Missing value, try again') #uses reg ex above to check formulation of URL; may not be perfect but anything it misses gets caught later if not re.match(urlcheck, self.api_url.get()): self.login_confirmed.set('Invalid URL, try again') else: if self.api_url.get().endswith('/'): self.api_url.set(self.api_url.get() + 'api') else: self.api_url.set(self.api_url.get() + '/api') #self.api_url.set(self.api_url.get()) auth = requests.post(self.api_url.get()+'/users/'+self.username.get()+'/login?password='******'error' in auth.keys(): self.login_confirmed.set('Login failed, try again') elif 'session' in auth.keys(): session = auth["session"] h = {'X-ArchivesSpace-Session':session, 'Content_Type': 'application/json'} self.login_confirmed.set('Login successful!') self.authenticate.set(h) return h #this captures a URL that is valid but not correct, plus any other errors except Exception: self.login_confirmed.set('Error, check login info and try again') #gets headers without logging in to API again - a bit of a hack with the JSON loads (bc the StringVar doesn't return key/value pair), but it works for now def get_headers(self): headers_string = self.authenticate.get() if self.authenticate.get() == '': messagebox.showerror('Error!', 'Please log in to the ArchivesSpace API') return else: valid_json = headers_string.replace("'", "\"") headers_json = json.loads(valid_json) return headers_json #opens CSV def opencsv(self): filename = self.csv_filename.get() if self.csv_filename.get() == '': messagebox.showinfo('Error!', 'Please choose an input CSV') return else: try: file = open(filename, 'r', encoding='utf-8', errors='replace') csvin = csv.reader(file) #Skips first two rows next(csvin, None) next(csvin, None) return csvin except: problem = messagebox.showerror('Error', 'Could not open CSV file.') logging.exception('Error: ') return def outputcsv(self): filename = self.csv_filename.get() newname = filename.rsplit(".", 1)[0] if self.csv_filename.get() == '': messagebox.showinfo('Error!', 'Please choose an input CSV') return else: c = open(newname + '_outfile.csv', 'a', encoding='utf-8', newline='') csvoutputfile = newname + '_outfile.csv' self.csv_output.set(str(csvoutputfile)) writer = csv.writer(c) return (c, writer) def timer(self, start): elapsedTime = time.time() - start m, s = divmod(elapsedTime, 60) h, m = divmod(m, 60) self.elapsed_time.set('%d:%02d:%02d' % (h, m, s)) #gets a list of repositories def repos(self, header_value): repo_list = requests.get(self.api_url.get() + '/repositories', headers=header_value).json() repo_d = {} for repo in repo_list: if repo['repo_code'] not in repo_d: repo_d[repo['repo_code']] = repo['uri'][14:] return repo_d #the ao_id here is the parent archival object ID def create_child_component(self, header_value, repo_num, ao_id, unit_id, extent_type, ao_title, container): ''''This function creates a new archival component, based on the data in the born-digtial accessioning worksheet''' #First, check if there is a value in the top container field. There won't always be one. if container != '': try: #form a new child component using data from the DAS spreadsheet child_component = {"publish": True, "title": ao_title, "level": "item", "component_id": unit_id, "jsonmodel_type": "archival_object","linked_events": [], "extents": [{"number": '1', "portion": "whole", "extent_type": extent_type, "jsonmodel_type": "extent"}], "instances": [{"instance_type": 'mixed_materials', "jsonmodel_type": 'instance', "sub_container": {"jsonmodel_type": 'sub_container', "top_container": {"ref": container} } } ], "resource": {"ref": '/repositories/'+repo_num+'+/resources/'+self.resource_id.get()}, "parent": {"ref": '/repositories/'+repo_num+'/archival_objects/'+ao_id}} except Exception as exc: logging.exception('Error: ') #Do I want this here or do I want to continue when something goes wrong? messagebox.showerror('Error!', 'Something went wrong. Please check error log.') return #if there is no value in the top container field of the DAS spreadsheet, create a child component without a top container else: child_component = {"publish": True, "title": ao_title, "level": "item", "component_id": unit_id, "jsonmodel_type": "archival_object","linked_events": [], "extents": [{ "number": '1', "portion": "whole", "extent_type": extent_type, "jsonmodel_type": "extent"}], "resource": {"ref": '/repositories/'+repo_num+'+/resources/'+self.resource_id.get()}, "parent": {"ref": '/repositories/'+repo_num+'/archival_objects/'+ao_id}} #convert the data back into JSON child_component_data = json.dumps(child_component) #Post the child archival object child_post = requests.post(self.api_url.get()+'/repositories/'+repo_num+'/archival_objects',headers=header_value,data=child_component_data).json() return child_post #Don't use all of those arguments,but need them to make action() work - can I use ***kwargs in the action part?); or default arguments def update_child_component(self, header_value, repo_num, ao_id, unit_id, extent_type, ao_title=None, container=None): #as of right now this function leaves the ArchivesSpace title intact, but could be modified to take title from spreadsheet component_json = requests.get(self.api_url.get()+'/repositories/'+repo_num+'/archival_objects/'+ao_id,headers=header_value).json() #updates component ID component_json['component_id'] = unit_id #updates extent component_json['extents']= [{ "number": '1', "portion": "whole", "extent_type": extent_type, "jsonmodel_type": "extent"}] component_data = json.dumps(component_json) component_post = requests.post(self.api_url.get()+'/repositories/'+repo_num+'/archival_objects/'+ao_id,headers=header_value,data=component_data).json() return component_post def create_event (self, header_value, user, ao_id, repo_num, event_type, outcome_value, date_value, note_value): '''This function creates an event in ASpace, based on the four possible parameters provided in the born-digital accessioning worksheet''' agent_authorizor = user['agent_record']['ref'] # Get the event type event_type = event_type.lower() # Get the event outcome outcome_value = outcome_value.lower() # Get the event date - add a check so that if there's only 2 digits for YY make it YYYY if date_value != '': if '-' in date_value: date_value = date_value.replace('-', '/') if date_value[-4:].isdigit(): date_value = datetime.datetime.strptime(date_value, '%m/%d/%Y').strftime('%Y-%m-%d') else: date_value = datetime.datetime.strptime(date_value, '%m/%d/%y').strftime('%Y-%m-%d') event = {"event_type": event_type, "jsonmodel_type": "event", "outcome": outcome_value, "outcome_note": note_value, "linked_agents": [{ "role": "authorizer", "ref": agent_authorizor }], "linked_records": [{ "role": "source", "ref": '/repositories/'+repo_num+'/archival_objects/'+ao_id }], "date": { "begin": date_value, "date_type": "single", "label": "event", "jsonmodel_type": "date" }} # Post that event event_post = requests.post(self.api_url.get()+'/repositories/'+repo_num+'/events',headers=header_value,json=event).json() logging.debug(str(event_post)) return event_post def get_top_containers(self, csv_var, repo_dictionary, header_value): logging.debug('Setting parent ID') #takes the first parent URL and sets it as the parent self.parent_id.set(csv_var[0][2].rpartition("_")[2]) logging.debug(self.parent_id.get()) #this gets a list of top containers for the parent component - assumes there will only be one parent...is this true?? parent_component = requests.get(self.api_url.get()+'/repositories/'+repo_dictionary.get(csv_var[0][0])+'/archival_objects/'+self.parent_id.get(),headers=header_value).json() tc_list = [instance['sub_container']['top_container']['ref'] for instance in parent_component['instances']] tuplelist = [] for tc_uri in tc_list: top_container = requests.get(self.api_url.get() + tc_uri, headers=header_value).json() tuplelist.append((top_container['uri'], top_container['indicator'])) return tuplelist #this function runs when either the create or update button is pushed. When the create button is pressed, the action variable takes #on the value of the create function, and when the update button is pressed the action variable takes the value of the update function def process_file(self, action): #Initiates the confirmation dialog go = self.areyousure() if go == True: #captures start time starttime = time.time() headers = self.get_headers() if headers != None: #Gets current user - Kevin has proposed changing this to accept a user besides the current user current_user = requests.get(self.api_url.get() + '/users/current-user', headers=headers).json() repo_dict = self.repos(headers) csvfile = self.opencsv() csvlist = [row for row in csvfile] #takes the resource id and sets it as a StringVar logging.debug('Setting resource ID') if '/#' in str(csvlist[0][2]): self.resource_id.set(csvlist[0][2].partition('/#')[0].rpartition('/')[2]) else: self.resource_id.set(csvlist[0][2].partition('#')[0].rpartition('/')[2]) logging.debug(self.resource_id.get()) #see if this works - and see what happens when you set Open in ArchivesSpace URL if action == self.create_child_component: tc_indicator_list = self.get_top_containers(csvlist, repo_dict, headers) if csvlist != None: x = 0 fileobject, csvoutfile = self.outputcsv() try: for i, row in enumerate(csvlist, 1): logging.debug('Working on row ' + str(i)) #should be a better way to skip empty/invalid rows, but i've added this for now - CHANGE THIS!!!! if row[0] in repo_dict: # save the original row length - used to get event data later on original_row_length = len(row) # Getting data from CSV file repo = repo_dict.get(row[0]) parent_ao_id = str(row[2]).rpartition("_")[2] #if calling the update component script, will set the URL as the most recently updated record - #this is for the Open in ArchivesSpace button if action == self.update_child_component: self.parent_id.set(parent_ao_id) #gets the title of the ao, accounting for any HTML that might be present title = cgi.escape(row[3]) component_id = row[4] extent = row[5] top_container = row[6] if top_container != '': logging.debug('Matching top_containers') for uri, indicator in tc_indicator_list: if uri != None: if indicator == top_container: top_container = uri else: #should continue with script or no?? logging.debug('uri == None') #this runs either the create archival objects or update archival objects script, and returns the result logging.debug('Calling action function') updated_component = action(headers, repo, parent_ao_id, component_id, extent, title, top_container) logging.debug('Finishing action function') if updated_component != None: if 'uri' in updated_component: updated_component_uri = updated_component['uri'] row.append(updated_component_uri) #creating events based on the rows in the spreadsheet if original_row_length > 9 and row[8] != '': new_event = self.create_event(headers, current_user, updated_component_uri, repo, row[8], row[9], row[10], cgi.escape(row[11])) row.append(new_event['uri']) if original_row_length > 13 and row[14] != '': new_event = self.create_event(headers, current_user, updated_component_uri, repo, row[12], row[13], row[14], cgi.escape(row[15])) row.append(new_event['uri']) if original_row_length > 17 and row[16] != '': new_event = self.create_event(headers, current_user, updated_component_uri, repo, row[16], row[17], row[18], cgi.escape(row[19])) row.append(new_event['uri']) if original_row_length > 21 and row[20] != '': new_event = self.create_event(headers, current_user, updated_component_uri, repo, row[20], row[21], row[22], cgi.escape(row[23])) row.append(new_event['uri']) x = self.process_results(updated_component, x) csvoutfile.writerow(row) #this catches most errors related to failed posts. else: logging.debug('Error: ' + str(updated_component)) csvoutfile.writerow(row) elif updated_component == None: logging.debug('Component did not create/update') csvoutfile.writerow(row) except: logging.exception('Error: ') csvoutfile.writerow(row) #this will stop the script - should I have it continue instead?? #messagebox.showerror('Error!', 'Something went wrong! Check logs!') #return self.update_attempts.set(str(i)) self.updates_success.set(str(x)) self.timer(starttime) #add logging here logging.debug('Update attempts: ' + str(i)) logging.debug('Updated successfully: ' + str(x)) logging.debug('Elapsed time: ' + self.elapsed_time.get()) #change this so that it's inside the loop done = self.script_finished() fileobject.close() else: return else: return else: return #connected to "create child component" button def run_create_script(self): self.process_file(self.create_child_component) #connected to "update child component" button def run_update_script(self): self.process_file(self.update_child_component) #Initiate logging - is this all I need? See logging cookbook in Python docs def error_log(self): #make sure this works on all systems...add another temp folder for pre-Windows 10? if sys.platform == "win32": self.log_file.set('\\Windows\\Temp\\error_log.log') else: self.log_file.set('/tmp/error_log.log') #Basic logging config logging.basicConfig(filename=self.log_file.get(), level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') def process_results(self, jsonname, counter): for key, value in jsonname.items(): if key == 'status': counter +=1 return counter if key == 'error': logging.debug(str(datetime.datetime.now())) logging.debug(str(jsonname.get('error'))) ### WIDGET FILE HANDLING ### #File open dialog for input CSV button widget def csvbutton(self): filename = filedialog.askopenfilename(parent=self.frame) self.csv_filename.set(str(filename)) return filename #opens csv output file via button widget def opencsvoutput(self): filename = self.csv_output.get() if sys.platform == "win32": os.startfile(filename) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, filename]) #opens program log via button widget - will this work if there is no log? def openerrorlog(self): #filename = self.log_file.get() if sys.platform == "win32": try: os.startfile('\\Windows\\Temp\\error_log.log') except: messagebox.showerror('Error!', 'Error log does not exist') else: opener = "open" if sys.platform == "darwin" else "xdg-open" try: subprocess.call([opener, '/tmp/error_log.log']) except: messagebox.showerror('Error!', 'Error log does not exist') #Opens the parent record in ArchivesSpace staff interface via button widget def openparent_record(self): #this is where I could use the resource ID url_end = self.parent_id.get() resource = self.resource_id.get() get_api = self.api_url.get() base_url = get_api[:-3] #add something here to make sure there are enough/not to many forward slashes...still works but doesn't look right full_url = base_url + '/resources/' + resource + '#tree::archival_object_' + url_end if full_url[-1].isdigit() : try: webbrowser.open(full_url, new=2) except: messagebox.showerror('Error!', '\n Invalid URL') else: if 'https' in base_url: webbrowser.open(base_url, new=2) else: messagebox.showerror('Error!', '\n Invalid URL') #message box confirming actions, that script is about run def areyousure(self): result = messagebox.askyesno('Are you sure?', '\n Click YES to proceed, NO to cancel') if result == True: self.script_status.set('...Updates in progress...') self.script_status.get() if result == False: false = messagebox.showinfo('Updates Canceled', '\n\n Press OK to return to menu') return result #Show script finished message on frame def script_finished(self): # box = messagebox.showinfo('Done!', 'Script finished. Check outfile for details') self.script_status.set('Updates finished!') self.script_status.get() #Clear all GUI inputs - start fresh def clear_inputs(self): r = messagebox.askyesno('Are you sure?', '\nClick YES to clear inputs, NO to cancel') if r == True: self.api_url.set('') self.username.set('') self.password.set('') self.login_confirmed.set('') self.csv_filename.set('') self.update_attempts.set('') self.updates_success.set('') self.elapsed_time.set('') self.script_status.set('') self.parent_id.set('') else: return
class myFrame(Frame): def __init__(self, root): self.myFra = Frame.__init__(self, root) #--------------- System Option --------------- if (system() == "Windows"): root.geometry("232x240") root.iconbitmap("icons/ConvtISP.ico") #--------------- Elements img --------------- self.Img = PhotoImage(file="icons/select.png") self.Img_cont = PhotoImage(file="icons/convert.png") self.Img_exit = PhotoImage(file="icons/exit.png") self.Img_doc = PhotoImage(file="icons/doc.png") self.Img_about = PhotoImage(file="icons/about.png") #--------------- Elements img END --------------- else: # For Linux root.geometry("290x220") #--------------- Elements img --------------- self.Img = PhotoImage(file=dirname(abspath(__file__)) + '/icons/select.png') self.Img_cont = PhotoImage(file=dirname(abspath(__file__)) + '/icons/convert.png') self.Img_exit = PhotoImage(file=dirname(abspath(__file__)) + '/icons/exit.png') self.Img_doc = PhotoImage(file=dirname(abspath(__file__)) + '/icons/doc.png') self.Img_about = PhotoImage(file=dirname(abspath(__file__)) + '/icons/about.png') #--------------- Elements img END --------------- #--------------- System Option END --------------- #--------------- Variable --------------- self.tipe = IntVar() #--------------- Style ttk --------------- self.style = ttk.Style() self.style.configure('TRadiobutton', font=("Arial", 10)) self.style.configure('TButton', font=("Arial", 12, "bold")) #--------------- Elements Menu --------------- self.menu = Menu(root) root.config(menu=self.menu) self.Archive = Menu(self.menu, tearoff=0) self.Archive.add_command(label="Open Image", image=self.Img, compound="left", command=lambda: open_img(self.Et)) self.Archive.add_command(label="Convert", image=self.Img_cont, compound="left", command=lambda: convert_img(self.tipe)) self.Archive.add_separator() self.Archive.add_command(label="Exit", image=self.Img_exit, compound="left", command=lambda: root.destroy()) self.menu.add_cascade(label="Archive", menu=self.Archive) self.Help = Menu(self.menu, tearoff=0) self.Help.add_command(label="Documentation", image=self.Img_doc, compound="left", command=lambda: open_doc()) self.Help.add_separator() self.Help.add_command(label="About", image=self.Img_about, compound="left", command=lambda: about_info()) self.menu.add_cascade(label="Help", menu=self.Help) #--------------- Elements Menu END --------------- #--------------- Elements Option Archive --------------- #----- Elements 1 ----- self.LFrame = LabelFrame(self.myFra, text="File Options", font=("Arial", 10)) self.LFrame.grid(row=0, column=0, padx=10) self.Et = ttk.Entry(self.LFrame, width=30) self.Et.grid(row=0, column=0, padx=10, pady=5) self.Et.configure(state='readonly') self.bt1 = ttk.Button(self.LFrame, image=self.Img, text="Select Image", compound="left", command=lambda: open_img(self.Et)) self.bt1.grid(row=1, column=0) self.bt2 = ttk.Button(self.LFrame, text="Convert", image=self.Img_cont, compound="left", command=lambda: convert_img(self.tipe)) self.bt2.grid(row=2, column=0, pady=4) #----- Elements 1 END ----- #----- Elements 2 ----- self.LFrame2 = LabelFrame(self.myFra, text="Conversion Options", font=("Arial", 10)) self.LFrame2.grid(row=1, column=0, padx=10, pady=5) self.Rb1 = ttk.Radiobutton(self.LFrame2, text="Grayscale / 300dpi", value=0, variable=self.tipe) self.Rb1.grid(row=0, column=0, sticky="w", padx=20, pady=5) self.Rb2 = ttk.Radiobutton(self.LFrame2, text="Black and White / 300dpi", value=1, variable=self.tipe) self.Rb2.grid(row=1, column=0, sticky="w", padx=20, pady=4)
def creeInterface(a_largeur=500, a_hauteur=500): global Wcanvas, ValLargeur, ValHauteur, EntreeX, EntreeY, SortieX, SortieY, CoulEntreeLbl, CoulEntreeBtn, CoulSortieLbl, CoulSortieBtn # Fenêtre principale root = Tk() root.title(TITRE + VERSION) root.geometry(str(a_largeur) + "x" + str(a_hauteur + 140) + "-10+10") # Frame des données dataFrame = Frame(root) # Partie 'Labyrinthe' labyFrame = LabelFrame(dataFrame, text='LABYRINTHE') # Première ligne : largeur du labyrinthe lblLargeur = Label(labyFrame, text='Largeur') lblLargeur.grid(row=0, column=0) ValLargeur = StringVar(root) ValLargeur.set(LARGEUR_DEF) texLargeur = Entry(labyFrame, textvariable=ValLargeur, width=2) texLargeur.grid(row=0, column=1) # Deuxième ligne : hauteur du labyrinthe lblHauteur = Label(labyFrame, text='Hauteur') lblHauteur.grid(row=1, column=0) ValHauteur = StringVar(root) ValHauteur.set(HAUTEUR_DEF) texHauteur = Entry(labyFrame, textvariable=ValHauteur, width=2) texHauteur.grid(row=1, column=1) # Troisième ligne : bouton 'Créer' btnCreer = Button(labyFrame, text='Créer', command=creerLabyCmd) btnCreer.grid(row=2, column=0) # Fin de la partie labyFrame labyFrame.grid(row=0, column=0, sticky=tkinter.N + tkinter.S) # Partie 'Entrée' entreeFrame = LabelFrame(dataFrame, text='ENTREE') # Abscisse Label(entreeFrame, text="X").grid(row=0, column=0) EntreeX = Scale(entreeFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xEntreeCmd) EntreeX.grid(row=0, column=1) # Ordonnée Label(entreeFrame, text="Y").grid(row=1, column=0) EntreeY = Scale(entreeFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=yEntreeCmd) EntreeY.grid(row=1, column=1) # Label Couleur CoulEntreeLbl = Label(entreeFrame, text="Couleur", bg=CoulEntree) CoulEntreeLbl.grid(row=2, column=0) # Bouton Couleur CoulEntreeBtn = Button(entreeFrame, text=CoulEntree, bg=CoulEntree, command=coulEntreeCmd) CoulEntreeBtn.grid(row=2, column=1) # Fin de la partie entreeFrame entreeFrame.grid(row=0, column=1, sticky=tkinter.N + tkinter.S) # Partie 'Sortie' sortieFrame = LabelFrame(dataFrame, text='SORTIE') # Abscisse Label(sortieFrame, text="X").grid(row=0, column=0) SortieX = Scale(sortieFrame, to=LARGEUR_DEF - 1, showvalue=False, orient='h', command=xSortieCmd) SortieX.grid(row=0, column=1) # Ordonnée Label(sortieFrame, text="Y").grid(row=1, column=0) SortieY = Scale(sortieFrame, to=HAUTEUR_DEF - 1, showvalue=False, orient='h', command=ySortieCmd) SortieY.grid(row=1, column=1) # Label Couleur CoulSortieLbl = Label(sortieFrame, text="Couleur", bg=CoulSortie) CoulSortieLbl.grid(row=2, column=0) # Bouton Couleur CoulSortieBtn = Button(sortieFrame, text=CoulSortie, bg=CoulSortie, command=coulSortieCmd) CoulSortieBtn.grid(row=2, column=1) # Fin de la partie sortieFrame sortieFrame.grid(row=0, column=2, sticky=tkinter.N + tkinter.S) # Partie Algorithme algoFrame = LabelFrame(dataFrame, text="ALGORITHME") # Première ligne : bouton main droite btnMainDroite = Button(algoFrame, text='Main Droite') btnMainDroite.grid(row=0, column=3) # Deuxième ligne : bouton main gauche btnMainGauche = Button(algoFrame, text='Main Gauche') btnMainGauche.grid(row=2, column=3) # Fin de la partie Algorithme algoFrame.grid(row=0, column=3, sticky=tkinter.N + tkinter.S) # Partie Tracé du Labyrinthe traceFrame = LabelFrame(dataFrame, text='TRACE DU LABYRINTHE') # Slider CoulEntSlider = Label(traceFrame, text='Entrée', fg=CoulEntree) CoulEntSlider.grid(row=0, column=0) Slider = Scale(traceFrame, showvalue=False, orient='v') Slider.grid(row=1, column=0) CoulSortSlider = Label(traceFrame, text='Sortie', fg=CoulSortie) CoulSortSlider.grid(row=2, column=0) # Fin partie Tracé du Labyrinthe traceFrame.grid(row=0, column=4) # Fin de la partie dataFrame et affichage dataFrame.grid(sticky=tkinter.W) # Fenêtre graphique (canvas) Wcanvas = Canvas(root, background="white", width=a_largeur, height=a_hauteur) # Fin de la partie Wcanvas et affichage Wcanvas.grid(row=1, column=0) return
menubar.add_cascade(label='爬虫', menu=crawlerMenu) menubar.add_cascade(label='Beta', menu=betaMenu) menubar.add_cascade(label='关于', menu=aboutMenu) aboutMenu.add_command(label='小组', command=lambda: tkinter.messagebox.showinfo("测试中", "测试中")) crawlerMenu.add_command(label='修改uidlist', command = lambda: os.startfile('source'+os.sep+'uidlist.txt')) crawlerMenu.add_separator() crawlerMenu.add_command(label='运行', command=lambda: tkinter.messagebox.showinfo("测试中", "测试中")) betaMenu.add_command(label='导入语料库', command=lambda: tkinter.messagebox.showinfo("测试中", "测试中")) betaMenu.add_command(label='训练模型', command=lambda: tkinter.messagebox.showinfo("测试中", "测试中")) betaMenu.add_separator() betaMenu.add_command(label='分析', command=lambda: tkinter.messagebox.showinfo("测试中", "测试中")) ''' # left label frame leftLabelFrame = LabelFrame(mainWindow, text = "选择要查看的类别", labelanchor="nw") leftLabelFrame.place(relx=0.05, rely=0.05, relwidth=0.9, relheight=0.9) leftBg = Frame(leftLabelFrame) mapBotton1 = Button(leftBg, text = "地图", command = lambda: showWindow('map')).grid(row=1) wordBotton1 = Button(leftBg, text = "词云", command = lambda: showWindow('wordcloud')).grid(row=3) chartBotton1 = Button(leftBg, text = "图表", command = lambda: showWindow('chart')).grid(row=5) betaBotton1 = Button(leftBg, text = "NLP情绪分析(Beta)", command = lambda: showWindow('sentiment')).grid(row=7) emptyBottom1 = Frame(leftBg).grid(row=8) setGrid(leftBg, 20) leftBg.pack() # Right label frame ''' rightLabelFrame = LabelFrame(mainWindow, text = "查看现有示例", labelanchor="nw")
def create_widgets(self): # menu bar widgets self.menu = Menu(self.master) self.filemenu = Menu(self.menu, tearoff=0) self.filemenu.add_command(label="Help", command=self.helper) self.filemenu.add_command(label="Exit", command=self.master.quit) self.menu.add_cascade(label="File", menu=self.filemenu) self.about = Menu(self.menu, tearoff=0) self.about.add_command(label="Version 2") self.about.add_command(label="About...", command=self.aboutwindow) self.menu.add_cascade(label="About", menu=self.about) # string vars self.url = StringVar() self.message = StringVar() self.artist = StringVar() self.album = StringVar() self.art = None self.art_text = StringVar() # organizing frames self.frame1 = Frame(self.master) self.frame1.pack(side="bottom", fill="both", expand=True) self.frame2 = Frame(self.master) self.frame2.pack(side="top", fill="both", expand=True) self.frame3 = LabelFrame(self.frame1) self.frame3.pack(padx=5, pady=3) # user input widget self.url_label = Label(self.frame3, text="URL:").grid(row=0, column=0) self.url_entry = Entry(self.frame3, width=40, textvariable=self.url).grid(row=0, column=1) self.artist_label = Label(self.frame3, text="Artist:").grid(row=1, column=0) self.artist_entry = Entry(self.frame3, width=40, textvariable=self.artist).grid(row=1, column=1) self.album_label = Label(self.frame3, text="Album:").grid(row=2, column=0) self.album_entry = Entry(self.frame3, width=40, textvariable=self.album).grid(row=2, column=1) # choose album art widgets self.art_button = Button(self.frame3, text="Choose Album Art", command=self.getArt).grid(row=3, column=0) self.art_label = Label(self.frame3, textvariable=self.art_text).grid(row=3, column=1) # padding around each user input widget for child in self.frame3.winfo_children(): child.grid_configure(padx=5, pady=3) # status bar widget; added before download to sticky to bottom first self.statusbar = Label(self.frame1, textvariable=self.message, bd=1, relief="sunken", anchor="w") self.statusbar.pack(side="bottom", fill="x") # download button widget self.download_button = Button(self.frame2, text="Download", command=self.download) self.download_button.pack(side="bottom", padx=5, pady=3) self.master.bind('<Return>', self.download) self.master.config(menu=self.menu)
def showWindow(tag): subWindow = Tk() if tag == 'map': subWindow.title('地图') subWindow.geometry('450x400') rootpath = os.getcwd()+os.sep+'archive'+os.sep+'map' leftBg = Frame(subWindow) var = BooleanVar(leftBg) check = Checkbutton(leftBg, text = "生成HTML文件而非图片", variable=var).grid(row=0, column=1, columnspan=3) hit1 = Button(leftBg, text = "全国各地疫情关注情况热力图1", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况热力图1.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况热力图1.html')).grid(row=2, column=1) hit2 = Button(leftBg, text = "全国各地疫情关注情况热力图2", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况热力图2.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况热力图2.html')).grid(row=4, column=1) hit3 = Button(leftBg, text = "全国各地疫情关注情况热力图3", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况热力图3.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况热力图3.html')).grid(row=6, column=1) fill1 = Button(leftBg, text = "全国各地疫情关注情况填充图1", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况填充图1.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况填充图1.html')).grid(row=8 , column=1) fill2 = Button(leftBg, text = "全国各地疫情关注情况填充图2", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况填充图2.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况填充图2.html')).grid(row=10, column=1) fill3 = Button(leftBg, text = "全国各地疫情关注情况填充图3", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'全国各地疫情关注情况填充图3.png', var.get(), rootpath+os.sep+'html'+os.sep+'全国各地疫情关注情况填充图3.html')).grid(row=12, column=1) hbHit = Button(leftBg, text = "疫情期间湖北各市受关注度分布", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'疫情期间湖北各市受关注度分布.png', var.get(), rootpath+os.sep+'html'+os.sep+'疫情期间湖北各市受关注度分布.html')).grid(row=2, column=3) nationalHit = Button(leftBg, text = "疫情期间全国各地受关注度分布", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'疫情期间全国各地受关注度分布.png', var.get(), rootpath+os.sep+'html'+os.sep+'疫情期间全国各地受关注度分布.html')).grid(row=4, column=3) pst = Button(leftBg, text = "疫情期间全国各地积极度", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'疫情期间全国各地积极度.png', var.get(), rootpath+os.sep+'html'+os.sep+'疫情期间全国各地积极度.html')).grid(row=6, column=3) ngt = Button(leftBg, text = "疫情期间全国各地消极度", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'疫情期间全国各地消极度.png', var.get(), rootpath+os.sep+'html'+os.sep+'疫情期间全国各地消极度.html')).grid(row=8, column=3) stm = Button(leftBg, text = "疫情期间全国各地情绪分布", command = lambda: showImg(rootpath+os.sep+'png'+os.sep+'疫情期间全国各地情绪分布.png', var.get(), rootpath+os.sep+'html'+os.sep+'疫情期间全国各地情绪分布.html')).grid(row=10, column=3) emptyBottom = Frame(leftBg).grid(row=11, column = 4) setGrid(leftBg, 20) leftBg.pack() elif tag == 'wordcloud': subWindow.title('词云图') subWindow.geometry('400x300') rootpath = os.getcwd()+os.sep+'archive'+os.sep+'wordcloud' bg = Frame(subWindow) botton1 = Button(bg, text = "疫情", command = lambda: showImg(rootpath+os.sep+'武汉 疫情 口罩 医院 战疫 钟南山 肺炎.jpg')).grid(row=1) botton2 = Button(bg, text = "作息", command = lambda: showImg(rootpath+os.sep+'熬夜 吃饭 早饭 午饭 晚饭 夜宵 睡觉 起床.jpg')).grid(row=3) botton3 = Button(bg, text = "复工复产", command = lambda: showImg(rootpath+os.sep+'上班 办公室 复工 复产 工作.jpg')).grid(row=5) botton4 = Button(bg, text = "复学", command = lambda: showImg(rootpath+os.sep+'开学 返校 复学.jpg')).grid(row=7) emptyBottom = Frame(bg).grid(row=8) setGrid(bg, 20) bg.pack() elif tag == 'chart': subWindow.title('折线图') subWindow.geometry('400x300') rootpath = os.getcwd()+os.sep+'archive'+os.sep+'chart' # 博客数 leftBg = Frame(subWindow) leftLabelFrame = LabelFrame(subWindow, text = "媒体博客数", labelanchor="nw") leftLabelFrame.place(relx=0.02, rely=0.02, relwidth=0.47, relheight=0.96) leftBg = Frame(leftLabelFrame) mapBotton1 = Button(leftBg, text = "疫情", command = lambda: showImg(rootpath+os.sep+'media武汉 疫情 口罩 医院 战疫 钟南山 肺炎.png')).grid(row=1) wordBotton1 = Button(leftBg, text = "作息", command = lambda: showImg(rootpath+os.sep+'media熬夜 吃饭 早饭 午饭 晚饭 夜宵 睡觉 起床.png')).grid(row=3) chartBotton1 = Button(leftBg, text = "复工复产", command = lambda: showImg(rootpath+os.sep+'media上班 办公室 复工 复产 工作.png')).grid(row=5) betaBotton1 = Button(leftBg, text = "复学", command = lambda: showImg(rootpath+os.sep+'media开学 返校 复学.png')).grid(row=7) emptyBottom1 = Frame(leftBg).grid(row=8) setGrid(leftBg, 20) leftBg.pack() # 评论&转发 rightLabelFrame = LabelFrame(subWindow, text = "评论数与转发数", labelanchor="nw") rightLabelFrame.place(relx=0.51, rely=0.02, relwidth=0.47, relheight=0.96) rightBg = Frame(rightLabelFrame) mapBotton2 = Button(rightBg, text = "疫情", command = lambda: showImg(rootpath+os.sep+'武汉 疫情 口罩 医院 战疫 钟南山 肺炎.png')).grid(row=1) wordBotton2 = Button(rightBg, text = "作息", command = lambda: showImg(rootpath+os.sep+'熬夜 吃饭 早饭 午饭 晚饭 夜宵 睡觉 起床.png')).grid(row=3) chartBotton2 = Button(rightBg, text = "复工复产", command = lambda: showImg(rootpath+os.sep+'上班 办公室 复工 复产 工作.png')).grid(row=5) betaBotton2 = Button(rightBg, text = "复学", command = lambda: showImg(rootpath+os.sep+'开学 返校 复学.png')).grid(row=7) emptyBottom2 = Frame(rightBg).grid(row=8) setGrid(rightBg, 20) rightBg.pack() elif tag == 'sentiment': subWindow.title('NLP情绪分析(Beta)') subWindow.geometry('400x450') rootpath = os.getcwd()+os.sep+'archive'+os.sep+'sentimentchart (Beta)' bg = Frame(subWindow) botton1 = Button(bg, text = "分组1-数量图", command = lambda: showImg(rootpath+os.sep+'bar result1.png')).grid(row=1) botton2 = Button(bg, text = "分组2-数量图", command = lambda: showImg(rootpath+os.sep+'bar result1.png')).grid(row=3) botton3 = Button(bg, text = "分组3-数量图", command = lambda: showImg(rootpath+os.sep+'bar result1.png')).grid(row=5) botton4 = Button(bg, text = "箱型图", command = lambda: showImg(rootpath+os.sep+'box.png')).grid(row=7) botton4 = Button(bg, text = "密度图", command = lambda: showImg(rootpath+os.sep+'density.png')).grid(row=9) emptyBottom = Frame(bg).grid(row=10) setGrid(bg, 20) bg.pack() subWindow.mainloop()
class QuizMe(Frame): PROMPT = 'What testbank do you want to open?' def __init__(self, master): # Initialize the Frame object. super().__init__(master) # Create every opening widget. self.intro = Label(self, text=self.PROMPT) self.group = LabelFrame(self, text='Filename') self.entry = Entry(self.group, width=35) self.click = Button(self.group, text='Browse ...', command=self.file) self.enter = Button(self, text='Continue', command=self.start) # Make Windows entry bindings. def select_all(event): event.widget.selection_range(0, tkinter.END) return 'break' self.entry.bind('<Control-Key-a>', select_all) self.entry.bind('<Control-Key-/>', lambda event: 'break') # Position them in this frame. options = {'sticky': tkinter.NSEW, 'padx': 5, 'pady': 5} self.intro.grid(row=0, column=0, **options) self.group.grid(row=1, column=0, **options) self.entry.grid(row=0, column=0, **options) self.click.grid(row=0, column=1, **options) self.enter.grid(row=2, column=0, **options) def file(self): # Find filename for self.entry options = {'defaultextension': '.xml', 'filetypes': [('All', '*'), ('XML', '.xml')], 'initialdir': os.path.join(os.getcwd(), 'tests'), 'parent': self, 'title': 'Testbank to Open'} filename = askopenfilename(**options) if filename: self.entry.delete(0, tkinter.END) self.entry.insert(0, filename) def start(self): # Validate self.entry and begin path = self.entry.get() if os.path.exists(path): if os.path.isfile(path): try: bank = testbank.parse(path) engine = teach_me.FAQ(bank) except xml.sax._exceptions.SAXParseException as error: title = error.getMessage().title() LN = error.getLineNumber() CN = error.getColumnNumber() message = 'Line {}, Column {}'.format(LN, CN) showerror(title, message, master=self) except AssertionError as error: title = 'Validation Error' message = error.args[0] showerror(title, message, master=self) except: title = 'Error' message = 'Unknown exception was thrown!' showerror(title, message, master=self) else: self.done = False self.next_event = iter(engine).__next__ self.after_idle(self.execute_quiz) else: title = 'Warning' message = 'File does not exist.' showwarning(title, message, master=self) else: title = 'Information' message = 'Path does not exist.' showinfo(title, message, master=self) def execute_quiz(self): # Follow the logic from the last program. # This will be called to handle an event. try: event = self.next_event() except StopIteration: assert self.done, 'Final event not processed!' else: if isinstance(event, teach_me.Enter): gui_logs.ShowStatus(self, 'Entering', event, self.execute_quiz) elif isinstance(event, teach_me.Exit): gui_logs.ShowStatus(self, 'Exiting', event, self.execute_quiz) self.last_exit = event.kind elif isinstance(event, teach_me.Question): gui_logs. AskQuestion(self, event, self.execute_quiz) elif isinstance(event, teach_me.Report): flag = [True] if self.last_exit == 'Section' and event.wrong: flag[0] = False gui_logs.ReviewProblems(self, event, flag) if flag[0]: gui_logs.ShowReport(self, event, self.execute_quiz) if event.final: title = 'Congratulations!' message = 'You have finished the test.' showinfo(title, message, master=self) self.done = True else: title = 'Type Error' message = repr(event) showerror(title, message, master=self)
def lblent(txt, var, col, row) -> None: lfrm = LFrame(master=parent, text=txt, font='Ebrima 8') lfrm.grid(column=col, row=row, padx=3) ent = Entry(master=lfrm, textvariable=var) ent.pack()
def __init__(self, pokerController): super().__init__() # Name of the window. self.title("FireCashGame") # Truc pour le redimensionnement automatique des éléments de la fenêtre. self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) # Placing labels etiq = Label(self , text="BobTracker") etiq.grid() fra_stats = LabelFrame(self, text="Stats") fra_stats.grid(row=1,column=1, sticky=N+S) playerName = StringVar() playerName.set("Bobsleigh37") self.averageGain = StringVar() self.maxGain = StringVar() self.maxLoss = StringVar() self.amountOfHands = StringVar() lab_playerName = Label(fra_stats, text="Player Name", anchor=W) lab_playerName.grid(row=0,column=0,sticky=N+W+E) lab_playerNameVar = Label(fra_stats, textvariable=playerName, anchor=W) lab_playerNameVar.grid(row=0,column=1,sticky=E) lab_avg = Label(fra_stats, text = "Average gain", anchor=W) lab_avg.grid(row=1,column=0,sticky=N+W+E) self.lab_avgVar = Label(fra_stats, textvariable=self.averageGain, anchor=E) self.lab_avgVar.grid(row=1,column=1,sticky=E) lab_maxGain = Label(fra_stats, text="Maximum gain", anchor=W) lab_maxGain.grid(row=2,column=0,sticky=N+W+E) lab_maxGainVar = Label(fra_stats, textvariable=self.maxGain, anchor=E) lab_maxGainVar.grid(row=2,column=1,sticky=E) lab_maxLoss = Label(fra_stats, text="Maximum loss", anchor=W) lab_maxLoss.grid(row=3,column=0,sticky=N+W+E) lab_maxLossVar = Label(fra_stats, textvariable = self.maxLoss, anchor=E) lab_maxLossVar.grid(row=3,column=1,sticky=E) lab_amountOfHands = Label(fra_stats, text="Hands in file", anchor=W) lab_amountOfHands.grid(row=4,column=0,sticky=N+W+E) lab_amountOfHandsVar = Label(fra_stats, textvariable= self.amountOfHands, anchor=E) lab_amountOfHandsVar.grid(row=4,column=1,sticky=E) self.pokerController = pokerController self.cashGame = CashGame() f = Figure(figsize=(10,6), dpi=100) a = f.add_subplot(111) a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5]) a.set_title('Chips Tracking') a.set_xlabel('Hand number') a.set_ylabel('Chip count') # Create frame for the canvas frame = Frame(self) label = Label(frame, text="Graph Page!") frame.grid() # Create canvas to display the graph plot canvas = FigureCanvasTkAgg(f, master=self) canvas.get_tk_widget().grid(row=1, column=0,padx=20,pady=20) btn_cash_session = Button(self, text='Update Stats', command= lambda: self.updateSession(a, canvas)) btn_cash_session.grid() self.openCashSession()
class RunPage(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.reserve_time = StringVar() self.reserve_date = StringVar() self.success = StringVar() self.success.set("No") self.counter = IntVar() self.counter.set(0) self.run_flag = IntVar() self.run_flag.set(0) self.T = {} self.message_count_down = False self.show_notice = True self.successed_info = [] self.Config_Path = self.controller.Config_Path self.Cookie_Path = self.controller.Cookie_Path self.frame_1 = LabelFrame( self, text="选择预定日期与开始时间(点击自动选择并查询)", height=100, width=630 ) self.day = 0 self.days = {} self.choose_days = {} for i in range(7): _today = date.today() self.days[i] = StringVar() _day = _today + timedelta(days=i) _day = _day.strftime("%Y-%m-%d") self.days[i].set(_day) self.choose_days[i] = Radiobutton( self.frame_1, text=self.days[i].get(), variable=self.reserve_date, value=self.days[i].get(), command=partial(self.set_reserve_date, i), ) self.times = {} self.choose_times = {} for i in range(7): self.times[i] = StringVar() _time = "{0:02d}:00:00".format(8 + 2 * i) self.times[i].set(_time) self.choose_times[i] = Radiobutton( self.frame_1, text=self.times[i].get(), variable=self.reserve_time, value=self.times[i].get(), command=self.set_reserve_time, ) # ------------------- self.frame_2 = LabelFrame(self, height=150, width=630) self.label_date_1 = Label(self.frame_2, text="预定日期:", anchor=E) self.label_date_2 = Label( self.frame_2, textvariable=self.reserve_date, anchor=W ) self.label_time_1 = Label(self.frame_2, text="预定时间段(2小时):", anchor=E) self.label_time_2 = Label( self.frame_2, textvariable=self.reserve_time, anchor=W ) self.label_couner = Label(self.frame_2, text="刷新次数:", anchor=E) self.couner_num = Label(self.frame_2, textvariable=self.counter) self.label_sucessed = Label(self.frame_2, text="是否预定成功?:", anchor=E) self.is_sucessed = Label(self.frame_2, bg="Red", textvariable=self.success) self.button_start = Button( self.frame_2, text="开始监控", bg="SpringGreen", command=self.start_job ) self.button_stop = Button( self.frame_2, text="结束", state=DISABLED, bg="LightGray", command=self.stop_job, ) self.label_notice = Label(self.frame_2, text="显示警告与提示?", anchor=E) self.button_notice = Button( self.frame_2, text="是", bg="Pink", command=self.turn_on_notice ) self.label_sucessed_place = Label(self.frame_2, text="预定成功的场地:", anchor=E) self.label_successed_place_info = Label(self.frame_2) # ------------------- self.frame_3 = LabelFrame(self, text="场地状态(点击刷新)", height=600, width=630) self.courts = {} self.show_courts = {} for i in range(8): self.courts[i] = IntVar() self.courts[i].set("") self.show_courts[i] = Button( self.frame_3, font=("Helvetica 10"), text="{}号场地".format(i + 1), command=self.get_status, ) self.create_page() def create_page(self): f_x = 56 height = 28 space = 20 f1_width = 98 f3_width = 120 self.frame_1.place( x=f_x - 30, y=space, width=700, height=height * 2 + space * 3 ) for i in range(7): self.choose_days[i].place( x=5 + f1_width * i, y=10, width=f1_width, height=height ) self.choose_times[i].place( x=5 + f1_width * i, y=20 + height, width=f1_width, height=height ) if not self.reserve_date.get(): self.choose_days[2].select() self.day = 2 if not self.reserve_time.get(): self.choose_times[6].select() self.frame_2.place( x=f_x, y=space + height * 4 + space, width=630, height=height * 3 + space * 4, ) self.label_date_1.place(x=space, y=space, width=120, height=height) self.label_date_2.place(x=space + 120, y=space, width=80, height=height) self.label_time_1.place(x=space, y=space * 2 + height, width=120, height=height) self.label_time_2.place( x=space + 120, y=space * 2 + height, width=80, height=height ) self.button_start.place(x=space + 100 + 100, y=space, width=180, height=height) self.button_stop.place( x=space + 120 + 80, y=space * 2 + height, width=180, height=height ) self.label_couner.place( x=space * 2 + 100 + 100 + 180, y=space, width=100, height=height ) self.couner_num.place( x=space * 2 + 100 + 100 + 180 + 100, y=space, width=80, height=height ) self.label_sucessed.place( x=space * 2 + 100 + 100 + 180, y=space * 2 + height, width=100, height=height, ) self.is_sucessed.place( x=space * 2 + 100 + 100 + 180 + 100, y=space * 2 + height, width=80, height=height, ) self.label_notice.place( x=space, y=space * 3 + height * 2, width=120, height=height ) self.button_notice.place( x=space + 120, y=space * 3 + height * 2, width=50, height=height ) # ------------------- self.frame_3.place(x=f_x, y=150 + 100 + space * 4, width=630, height=height * 6) for i in range(8): self.show_courts[i].place( x=10 + (f3_width + 40) * (i % 4), y=10 + (height * 2 + space) * (i // 4), width=f3_width, height=height * 2, ) self.show_courts[i].configure( background="LightGray", highlightbackground="Gold", foreground="Black" ) def job(self): _st = "07:59:30" # 开始时间 _end = "22:00:00" # 结束时间 i = 1 # 刷新次数计数器 infos = backend.load_config(self.Config_Path) while True: if self.run_flag.get() == 0: break elif _st <= strftime("%H:%M:%S", localtime()) < _end: if backend.judge_time(): dt = 2 else: dt = 20 self.update_status(True, infos, dt) else: dt = 40 self.update_status(False, infos, dt) sleep(dt) self.counter.set(i) self.couner_num.configure(textvariable=self.counter) i += 1 def start_job(self): if self.run_flag.get() == 0 and self.success.get() == "No": self.run_flag.set(1) for i in range(7): self.choose_days[i].config(state=DISABLED) self.choose_times[i].config(state=DISABLED) self.button_start.configure( bg="LightGray", state=ACTIVE, text="正在运行 ...", fg="Green" ) self.button_stop.configure(bg="Tomato", state=NORMAL, text="结束", fg="Black") # sort_place_order(self.controller) ct = int(random() * 10000) self.T[ct] = Thread(target=self.job, args=()) self.T[ct].daemon = True self.T[ct].start() elif self.success.get() == "Yes": messagebox.showinfo("提示", " =_=已经预定到啦=_= \n\n 请网页上查看! \n") else: messagebox.showinfo("提示", " =_=已经在运行啦=_= \n\n 不要重复点击! \n") def stop_job(self): if self.run_flag.get() == 1: self.run_flag.set(0) for i in range(7): self.choose_days[i].config(state=NORMAL) self.choose_times[i].config(state=NORMAL) self.button_stop.configure(bg="Gray", state=ACTIVE, text="已经停止", fg="White") self.button_start.configure( bg="SpringGreen", state=NORMAL, text="开始监控", fg="Black" ) else: messagebox.showinfo("提示", " =_=当前没有后台监控任务=_= \n\n 不要重复点击! \n ") def update_status(self, doit=False, infos=None, dt=0, mark=True): """doit 预定 flag,infos 同伴信息,dt 睡眠时间,秒;mark 用于防止递归。""" _date = self.reserve_date.get() _time = self.reserve_time.get() if _date and _time: res = {} court = backend.pian_status res, _ = backend.get_status( self.Config_Path, self.Cookie_Path, (_date, _time) ) if infos and infos["place_sort"]: sorted_keys = sort_place_order(court, infos["place_sort"]) else: sorted_keys = res.keys() for key in sorted_keys: # 2:已预约;4:不开放;1:可预约;3:使用中;5:预约中,'':不可预约 ii = int(court[key]) res_status = res[key][0] res_note = res[key][1] if res_status == 1: self.try_to_reverse(doit, infos, key, ii, _date, _time, dt) elif res_status == 2: self.show_courts[ii - 1].configure( text="{}号场地\n已被预约".format(ii), background="Black", highlightbackground="Gold", foreground="Gold", font=("Helvetica 10"), ) elif res_status == 3: self.show_courts[ii - 1].configure( text="{}号场地\n使用中".format(ii), background="Yellow", highlightbackground="Gold", foreground="Gold", font=("Helvetica 10"), ) elif res_status == 4: self.show_courts[ii - 1].configure( text="{}号场地\n不开放".format(ii), background="Gray", highlightbackground="Gold", foreground="White", font=("Helvetica 10"), ) if res_note: if len(res_note) >= 10: self.show_courts[ii - 1].configure( text="{}号场地(不开放)\n{}".format(ii, res_note), font=("Helvetica 8"), ) else: self.show_courts[ii - 1].configure( text="{}号场地(不开放)\n{}".format(ii, res_note) ) elif res_status == 5: self.show_courts[ii - 1].configure( text="{}号场地\n预约中".format(ii), background="Green", highlightbackground="Gold", foreground="Cyan", font=("Helvetica 10"), ) else: self.show_courts[ii - 1].configure( text="{}号场地\n不可预约".format(ii), background="LightGray", highlightbackground="Gold", foreground="Gold", font=("Helvetica 10"), ) if mark: self.mark_successed_place(court, _date, _time) if doit and infos: # 没有可预定或正在预定的场地,则退出预定 if res and (1, "") not in res.values() and (5, "") not in res.values(): self.stop_job() # 退出线程 messagebox.showinfo( "提示", "-" * 20 + "\n =_=没有可预约的场地=_= \n\n 请选择其他时间和日期的场地预约! \n ", ) def try_to_reverse(self, doit, infos, key, ii, _date, _time, dt): """尝试预定单个场地""" _text = "{}号场地\n可预约".format(ii) if doit and infos and self.success.get() != "Yes" and self.run_flag.get() == 1: is_ok = False try: is_ok = backend.appointment( self.Config_Path, self.Cookie_Path, key, _date, _time, infos, self.day, ) except UserWarning as UW: msg = ( "-" * 20 + "\n{}\n".format(UW) + "-" * 20 + "\n{}秒后重试".format(dt), ) if not self.message_count_down and self.show_notice: mymessage.CountDownMessageBox(self, msg) except Warning as War: _text = "{}号场地\n尝试预约,已失败".format(ii) self.stop_job() # 退出线程 msg = "-" * 20 + "\n错误信息:\n{}\n".format(War) + "-" * 20 if self.show_notice: messagebox.showerror("发生错误", msg) if is_ok: self.success.set("Yes") self.successed_info = [key, _date, _time] self.stop_job() # 退出线程 self.color_target_court(ii, _text) def color_target_court(self, ii, _text): """上色 可预约场地""" self.show_courts[ii - 1].configure( text=_text, background="Green", highlightbackground="Gold", foreground="Gold", font=("Helvetica 10"), ) def mark_successed_place(self, court, _date, _time): """标记已经预定了的场地""" if ( self.successed_info and _date == self.successed_info[1] and _time == self.successed_info[2] ): # 更新场地状态,如果显示已被预定,就表示成功预定该场地。 self.update_status(mark=False) res, _ = backend.get_status( self.Config_Path, self.Cookie_Path, (_date, _time) ) key = self.successed_info[0] if res[key][0] == 2: ii = int(court[key]) # 高亮 成功 YES self.is_sucessed.configure( textvariable=self.success, bg="LightGray", fg="Magenta" ) # 显示预定信息 success_text = str(ii) + "号 " + _date + " " + _time self.label_successed_place_info.configure( fg="Magenta", text=success_text ) self.label_sucessed_place.place( x=20 + 200, y=20 * 3 + 28 * 2, width=180, height=28 ) self.label_successed_place_info.place( x=20 + 380, y=20 * 3 + 28 * 2, width=200, height=28 ) self.show_courts[ii - 1].configure( text="{}号场地\n程序预约了该场地".format(ii), background="Magenta", highlightbackground="Green", foreground="White", font=("Helvetica 10"), ) else: self.successed_info = [] self.success.set("No") def set_reserve_date(self, day): self.update_status() self.day = day def set_reserve_time(self): self.update_status() def get_status(self): if self.run_flag.get() != 1: self.update_status() def turn_on_notice(self): if self.show_notice: self.show_notice = False self.button_notice.configure(text="否", bg="LightGray") else: self.show_notice = True self.button_notice.configure(text="是", bg="Pink")