def listFiles(self): request = False # Inventory is only created around 1 day after first file is upload if (self.Glacier.vault.last_inventory_date == None): request = messagebox.askyesno("No Inventory Found","Request Inventory from AWS Glacier?\nJob will take around 4-5 hours to complete.") else: d = dateutil.parser.parse( self.Glacier.vault.last_inventory_date ) d.replace(tzinfo=None) days = (datetime.datetime.utcnow() - d.replace(tzinfo=None)).days hours = (datetime.datetime.utcnow() - d.replace(tzinfo=None)).seconds/3600.0 hours = floor(hours*100)/100; # Amazon Glacier prepares an inventory for each vault periodically, every 24 hours. # When you initiate a job for a vault inventory, Amazon Glacier returns the last # inventory for the vault. The inventory data you get might be up to a day or # two days old. # # - So, we only request a new list if our current list is more than 2 days older # TODO: Here we need to check if we already have a inventory_retrieval job if (days >= 2): request = messagebox.askyesno("Inventory is " + str(days) + " days old","Request Inventory from AWS Glacier?\nJob will take around 4-5 hours to complete.") else: request = messagebox.askyesno("Inventory is " + str(hours) + " hours old","Request Inventory from AWS Glacier?\nJob will take around 4-5 hours to complete.") if (request): self.Glacier.initListFiles() #TODO: Add Message/Feedback else: # Use old data #TODO: Here, update self.inventory with archives information # Havent find a way to get old inventory data yet.. so will keep it locally print(self.Glacier.vault.number_of_archives) print(self.Glacier.vault.size_in_bytes)
def dump(element): path_ = path.get() if path_ == '': return file_type = os.path.splitext(path_)[1] call = callable_arr.get(file_type) try: arr = call(path_) except Exception as e: print(e) messagebox.askokcancel('error', '不支持该文件类型') return if element == 'json': content = json.dumps(arr, sort_keys=True) with open(os.path.dirname(path_)+r'\target.json', 'w+') as f: f.write(content) messagebox.askyesno('成功', '转换成功!请查找target文件') elif element == 'php': php_str = '<?php \n' \ 'return ' php_str = php_str + dump_php(arr) + ';' with open(os.path.dirname(path_)+r'\target.php', 'wb') as f: f.write(php_str.encode()) messagebox.askyesno('成功', '转换成功!请查找target文件')
def onRemove(self): """ Checks whether one or more queries is selected, and then asks for confirmation before removing them from the database. """ to_remove = self.paned_window.notebook_selection() # returns indices #print(to_remove) rlen = len(to_remove) remove = False if rlen == 1: if messagebox.askyesno( message = "Delete {} query?".format(rlen), icon='question', title='Remove query'): remove = True elif rlen > 1: if messagebox.askyesno( message = "Delete {} queries?".format(rlen), icon='question', title='Remove queries'): remove = True if remove: for index in to_remove: qid = self.paned_window.notebook_item(index) self.qdb.remove_entry(qid) self.qsdb.remove_from_all(qid) # remove from listbox and internal data structures self.paned_window.remove_items(to_remove)
def FileDelete(self): """ Delete the working database """ # Do we have a DB open? if self.DBHandle.DBConnection == None: # No DB to close self.WindowInfoMesg(1, "No open database") else: # Warn the user if messagebox.askyesno("WARNING", "This will delete the database file, proceed?"): # Ask again if messagebox.askyesno("Final Warning", "Are you sure you would like to delete the DB?"): # Delete the database if self.DBHandle.DBDestroy() == False: # Error Occured self.WindowInfoMesg(2, self.DBHandle.ErrorMsg) else: # DB deleted double check if ops.path.isfile(self.DBFileName): # File shouldn't exist! self.WindowInfoMesg(2, "File didn't delete!") else: # File is gone self.WindowInfoMesg(0, "Database Deleted") else: # Do nothing pass else: # Do nothing pass
def sd_button_add_source(self): """This method will take the data fields for a source and add it. If the feed already exists, an offer to modify it will be made.""" #lets gather the settings for the new source. name = self.sdo_name.get() url = self.sdo_url.get() source_time = self.sdo_time.get() #lets make sure we have both name and an address. if not url or not name: messagebox.showinfo(message=self._('To add a new source, you must give it a name and a URL.')) else: #now lets validate the time that was given. if source_time: source_time = self.__time_to_string__(self.__calculate_time__(source_time)) else: source_time = '00:00:00 01/01/2000' reply = self.sd.add_source(name, url, source_time) if not reply[0] and reply[1] == 1: if messagebox.askyesno(message=self._('A feed with the name "{}" already exists, do you want to edit it ?').format(name), icon='question', title='Edit Feed'): if not self.sd.modify_source(name, url, source_time, by = 0)[0]: #that means that the given URL already exists in another feed. messagebox.showinfo(message=self._('The given URL already exists in another feed. No changes were made.')) elif not reply[0] and reply[1] == 0: if messagebox.askyesno(message=self._('A feed with the URL "{}" already exists, do you want to edit it ?').format(url), icon='question', title='Edit Feed'): if not self.sd.modify_source(name, url, source_time, by = 1)[0]: #that means that the given name already exists in another feed. messagebox.showinfo(message=self._('The given name already exists in another feed. No changes were made.')) else: self.__load_sd_feeds_list__() else: self.__load_sd_feeds_list__() self.stts_print() self.sd_clear()
def update_db(self, old=None, new=None, content=None, askoverwrite=True): if old is None: old = self.db_container.selected_file.get() if new is None: new = self.db_container.selected_file.get().strip('*') if content is None: content = self.db_container.editor.get("1.0", END).strip() if old == new and askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[old] = content else: logger.error('no name specified!') return -1 elif old == new and not askoverwrite: self.project.dbs[old] = content else: if new in self.project.dbs: if askoverwrite: savechanges = messagebox.askyesno("Save changes", "A file '{}' already exists. Overwrite?".format(new)) if savechanges: self.project.dbs[new] = content else: logger.error('no name specified!') return -1 else: self.project.dbs[new] = content return 1
def check_deb(sl, at): global Broll, counter, tcol, deb_low, deb_con, sum_per Broll=cur_parti_Atte(sl) if ws.cell(row=sl+5, column=5).value==1: deb_con[counter]=1 deb_lab2.configure(style='sl.TLabel') elif sum(Broll[1:5])+at==0: q=messagebox.askyesno(message='ALERT!!! Absent for 5 days Continuosly\nWant to DEBAR?', icon='question', title='DEBAR ALERT') deb_con[counter]=int(q)#Add 2 for today debarred student if q: deb_lab2.configure(style='sl.TLabel') else: deb_lab2.configure(style='un.TLabel') else: deb_con[counter]=0 deb_lab2.configure(style='un.TLabel') if ws.cell(row=sl+5, column=4 ).value==1: if (ws.cell(row=sl+5, column=6).value+at)/(tcol-6)*100>75: messagebox.showinfo(message='CONGO!!! Your Attendance > 75% now\nYou have been cleared from DEBAR LIST') deb_low[counter]=0 else: deb_low[counter]=1 deb_lab1.configure(style='sl.TLabel') else: if (ws.cell(row=sl+5, column=6).value+at)/(tcol-6)*100<75: p=messagebox.askyesno(message='ALERT!!! Attendance < 75%\nWant to DEBAR?', icon='question', title='DEBAR ALERT') deb_low[counter]=int(p)#Add 2 for today debarred student if p: deb_lab1.configure(style='sl.TLabel') else: deb_lab1.configure(style='un.TLabel') else: deb_low[counter]=0 deb_lab1.configure(style='un.TLabel') sum_per[counter] = str(round((ws.cell(row=sl+5, column=6).value+at)/(tcol-6)*100, 2))+'%' per.set(sum_per[counter]) if sum(Broll)+at==0: warn3.set('ABSENT FOR MORE THAN 5 DAYS') war_lab1.configure(style='slw.TLabel') war_3[counter]=3 elif sum(Broll[2:5])+at==0: warn3.set('WARNING!!! ABSENT FOR 4 DAYS') war_lab1.configure(style='slw.TLabel') war_3[counter]=2 elif sum(Broll[3:5])+at==0: warn3.set('WARNING!!! ABSENT FOR 3 DAYS') war_lab1.configure(style='slw.TLabel') war_3[counter]=1 else: warn3.set('----------------------------------') war_lab1.configure(style='warel.TLabel') war_3[counter]=0 if 75<(ws.cell(row=sl+5, column=6).value+at)/(tcol-6)*100<80: warn75.set('WARNING!!! 75% < ATTENDANCE < 80%') war_lab2.configure(style='slw.TLabel') war_75[counter]=1 else: warn75.set('----------------------------------') war_lab2.configure(style='warel.TLabel') war_75[counter]=0
def submitViolation( self ): # Checks that user wants to submit with or without a description. askMsg = "Are you sure you want to submit the " +\ "violation with no description?" if not self.descOpen: if not tm.askyesno( "No Description?", askMsg ): self.addTextWidget() return else: getDesc = None elif len( self.descBox.get( 1.0, END ).strip() ) == 0: if not tm.askyesno( "No Description?", askMsg ): return else: getDesc = None else: getDesc = self.descBox.get( 1.0, END ).strip() # create the entry dictionary for the statement self.entries = { "ticketNo": self.ticketNo_entry.get().strip(), "violatorNo": self.violator_entry.get().strip(), "vehicle_id": self.vin_entry.get().strip(), "officerNo": self.officerNo_entry.get().strip(), "vtype": self.vType_entry.get().strip(), "vdate": self.vDate_entry.get().strip(), "place": self.loc_entry.get().strip(), "descr": getDesc } if not self.validateEntries(): return askMsg = "Are you sure you want to submit?" if not tm.askyesno( "Submit Confirmation", askMsg ): return cursor = self.userCx.cursor() statement = "INSERT INTO ticket VALUES ( :ticketNo, :violatorNo, " +\ ":vehicle_id, :officerNo, :vtype, " +\ "TO_DATE( :vdate, 'dd-Mon-yyyy hh24:mi:ss' ), " +\ ":place, :descr )" cursor.execute( "SAVEPOINT Violation" ) try: cursor.execute( statement, self.entries ) cursor.execute( "COMMIT" ) except cx_Oracle.DatabaseError as exc: cursor.execute( "ROLLBACK to Violation" ) cursor.close() error, = exc.args self.recoverError( error ) return cursor.close() infoMsg = "Ticket Number " + str( self.entries["ticketNo"] ) +\ " has been recorded." tm.showinfo( "Success!", infoMsg ) self.destroy()
def _maybeMigrateFromFGoConfig_dialogs(self, parent): message = _("Initialize {prg}'s configuration from your existing " \ "FGo! configuration?").format(prg=PROGNAME) detail = (_("""\ You have no {cfgfile} file but you do have a {fgo_cfgfile} file, which normally belongs to FGo!. Except in rare circumstances (such as using braces or backslashes, or opening brackets at the beginning of a config line), a configuration file from FGo! 1.5.5 or earlier should be usable as is by {prg}.""") .replace('\n', ' ') + "\n\n" + _("""\ If {fgo_cfgfile} was written by FGo! 1.5.5 or earlier, you should probably say “Yes” here in order to initialize {prg}'s configuration based on your FGo! config file (precisely: copy {fgo_cfgfile} to {cfgfile}).""") .replace('\n', ' ') + "\n\n" + _("""\ If {fgo_cfgfile} was written by a version of FGo! that is greater than 1.5.5, it is advised to say “No” here.""") .replace('\n', ' ') ).format(prg=PROGNAME, cfgfile=CONFIG, fgo_cfgfile=FGO_CONFIG) if askyesno(PROGNAME, message, detail=detail, parent=parent): choice = "migrate from FGo!" else: message = _("Create a default {prg} configuration?").format( prg=PROGNAME) detail = _("""\ Choose “Yes” to create a basic {prg} configuration now. If you choose “No”, {prg} will exit and you'll have to create {cfgfile} yourself, or restart {prg} to see the same questions again.""") \ .replace('\n', ' ').format(prg=PROGNAME, cfgfile=CONFIG) if askyesno(PROGNAME, message, detail=detail, parent=parent): choice = "create default cfg" message = _("Creating a default {prg} configuration.").format( prg=PROGNAME) detail = (_("""\ It is suggested that you go to the Settings menu and choose Preferences to review your newly-created configuration.""") .replace('\n', ' ') + "\n\n" + _("""\ You can also reuse most, if not all FlightGear options you had in FGo!'s main text box (the “options window”). Just copy them to the corresponding {prg} text box.""") .replace('\n', ' ') + "\n\n" + _("""\ Note: you may run both FGo! and {prg} simultaneously, as their configurations are kept separate.""") .replace('\n', ' ') ).format(prg=PROGNAME) showinfo(PROGNAME, message, detail=detail, parent=parent) else: choice = "abort" return choice
def onQuit(self): # on a Quit request in the GUI close = not self.text_edit_modified() # check self, ask?, check others if not close: close = askyesno('SimpleEditor', 'Text changed: quit and discard changes?') if close: windows = TextEditor.editwindows changed = [w for w in windows if w != self and w.text_edit_modified()] if not changed: GuiMaker.quit(self) else: numchange = len(changed) verify = '%s other edit window%s changed: quit and discard anyhow?' verify = verify % (numchange, 's' if numchange > 1 else '') if askyesno('SimpleEditor', verify): GuiMaker.quit(self)
def onQuit(self): close = not self.text.edit_modified() if not close: close = askyesno('PyEdit', 'Text changed: quit and discard changes?') if close: windows = TextEditor.editwindows changed = [w for w in windows if w != self and w.text.edit_modified()] if not changed: GuiMaker.quit(self) else: numchange = len(changed) verify = '%s other edit window%s changed: quit and discard anyhow?' verify = verify % (numchange, 's' if numchange > 1 else '') if askyesno('PyEdit', verify): GuiMaker.quit(self)
def onQuit(self): # on a Quit request in the GUI close = not self.text_edit_modified() # check self, ask?, check others if not close: close = askyesno("PyEdit", "Text changed: quit and discard changes?") if close: windows = TextEditor.editwindows changed = [w for w in windows if w != self and w.text_edit_modified()] if not changed: GuiMaker.quit(self) # quit ends entire app regardless of widget type else: numchange = len(changed) verify = "%s other edit window%s changed: quit and discard anyhow?" verify = verify % (numchange, "s" if numchange > 1 else "") if askyesno("PyEdit", verify): GuiMaker.quit(self)
def ok(self, event=None): if self.pluginConfigChanged: PluginManager.pluginConfig = self.pluginConfig PluginManager.pluginConfigChanged = True PluginManager.reset() # force reloading of modules if self.uiClassMethodsChanged or self.modelClassesChanged or self.disclosureSystemTypesChanged or self.hostSystemFeaturesChanged: # may require reloading UI affectedItems = "" if self.uiClassMethodsChanged: affectedItems += _("menus of the user interface") if self.modelClassesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("model objects of the processor") if self.disclosureSystemTypesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("disclosure system types") if self.hostSystemFeaturesChanged: if affectedItems: affectedItems += _(" and ") affectedItems += _("host system features") if messagebox.askyesno(_("User interface plug-in change"), _("A change in plug-in class methods may have affected {0}. " "Please restart Arelle to due to these changes. \n\n" "Should Arelle restart itself now " "(if there are any unsaved changes they would be lost!)?" ).format(affectedItems), parent=self): self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True])) self.close()
def exit(self): if messagebox.askyesno("","Do you wish to save before quitting?"): self.save() self.move() else: self.save() self.move()
def mem_new(self, c=[0]): from my_class import Member new = self.name.get(), self.abbr.get(), self.level.get(), self.rank.get() if not new[0]: return flag = not new[1] kw = {} kw['name'], kw['abbr'], kw['level'], kw['rank'] = new kw['abbr'] = ( kw['abbr'] or '%d'%c[0] ).rjust(3,'_') kw['level'] = int (kw['level'] or 1) kw['rank'] = kw['rank'] or kw['level'] * 100 title = "添加成员" message = "新成员信息:\n Name: %s\n Abbr: %s\n Town Hall Lv: %s\n Rank: %s"\ ""%(kw['name'], kw['abbr'], kw['level'], kw['rank']) if kw['abbr'] in self.clan.member: messagebox.showwarning("错误!","该缩写已存在,如需帮助请联系Ceilopty") return if not messagebox.askyesno(title, message): return try: new = Member(self.clan, **kw) self.clan[kw['abbr']] = new except BaseException as e: messagebox.showwarning("成员创建失败","错误:%s\n如有疑问请咨询Ceilopty"%e) else: self.unsaved = True if flag: c[0] += 1 messagebox.showinfo("成员创建成功","即日起成员%s可以参战!"%kw['name']) self.flash()
def reset() : rmFilesFailed = False question = "The following files will be deleted:\n\n ~/.gtkrc-2.0\n ~/.config/gtk-3.0/settings.ini\n ~/.icons/default/index.theme\n\nDo you want to continue?" choice = messagebox.askyesno(title = "Reset", message = question) if choice : homeDir = os.path.expanduser('~') try : os.remove(homeDir + "/.gtkrc-2.0") except FileNotFoundError : pass except IOError : rmFilesFailed = True try : os.remove(homeDir + "/.config/gtk-3.0/settings.ini") except FileNotFoundError : pass except IOError : rmFilesFailed = True try : os.remove(homeDir + "/.icons/default/index.theme") except FileNotFoundError : pass except IOError : rmFilesFailed = True if rmFilesFailed : messagebox.showerror(title = "Error", message = "Errors occured whilst removing the settings files.") ui.varOpG2.set(getResource("gtk2", "gtk-theme-name")) ui.varOpG3.set(getResource("gtk3", "gtk-theme-name")) ui.varOpFont.delete(0, len(ui.varOpFont.get())) ui.varOpFont.insert(0, getResource("gtk2", "gtk-font-name")) ui.varOpIcons.set(getResource("gtk2", "gtk-icon-theme-name")) ui.varOpCursors.set(getResource("xdg_cursor", "Inherits")) ui.varOpButtonImages.set(getResource("gtk2", "gtk-button-images")) ui.varOpMenuImages.set(getResource("gtk2", "gtk-menu-images")) ui.varOpDarkTheme.set(getResource("gtk3", "gtk-application-prefer-dark-theme"))
def install_graphics(self, listbox): """ Installs a graphics pack. Params: listbox Listbox containing the list of graphics packs. """ if len(listbox.curselection()) != 0: gfx_dir = listbox.get(listbox.curselection()[0]) if messagebox.askokcancel( message='Your graphics, settings and raws will be changed.', title='Are you sure?'): result = self.lnp.install_graphics(gfx_dir) if result is False: messagebox.showerror( title='Error occurred', message='Something went wrong: ' 'the graphics folder may be missing important files. ' 'Graphics may not be installed correctly.\n' 'See the output log for error details.') elif result: if messagebox.askyesno( 'Update Savegames?', 'Graphics and settings installed!\n' 'Would you like to update your savegames to ' 'properly use the new graphics?'): self.update_savegames() else: messagebox.showerror( title='Error occurred', message='Nothing was installed.\n' 'Folder does not exist or does not have required files ' 'or folders:\n'+str(gfx_dir)) binding.update()
def apply(self): """Apply operation""" kwds = {} method = self.opvar.get() for i in self.opts: if i not in self.grps[method]: continue if self.opts[i]['type'] == 'listbox': val = self.tkvars[i].getSelectedItem() else: val = self.tkvars[i].get() if val == '': val=None kwds[i] = val print (kwds) if method == 'merge': s=(kwds['suffix1'],kwds['suffix2']) del kwds['suffix1'] del kwds['suffix2'] m = pd.merge(self.df1,self.df2,on=None,suffixes=s, **kwds) elif method == 'concat': m = pd.concat([self.df1,self.df2], **kwds) print (m) #if successful ask user to replace table and close if len(m) > 0: n = messagebox.askyesno("Join done", "Merge/concat success.\nReplace table with new data?", parent=self.parent) if n == True: self.merged = m self.quit() else: self.merged = None return
def playGame(game): result = '' while not result: printGame(game) choice = input('Cell[1-9 or q to quit]: ') if choice.lower()[0] == 'q': save = mb.askyesno("Save game", "Save game before quitting?") if save: oxo_logic.saveGame(game) quit() else: try: cell = int(choice) - 1 if not (0 <= cell <= 8): raise ValueError except ValueError: print('Choose a number between 1 and 9 or q to quit') continue try: result = oxo_logic.userMove(game, cell) except ValueError: mb.showerror("Invalid cell", "Choose an empty cell") continue if not result: result = oxo_logic.computerMove(game) if not result: continue elif result == 'D': printGame(game) mb.showinfo("Result", "It's a draw") print("It's a draw") else: printGame(game) mb.showinfo("Result", "Winner is {}".format(result))
def remove_game(_=None): """Remove the currently-chosen game from the game list.""" global selected_game lastgame_mess = ( "\n (BEE2 will quit, this is the last game set!)" if len(all_games) == 1 else "" ) confirm = messagebox.askyesno( title="BEE2", message='Are you sure you want to delete "' + selected_game.name + '"?' + lastgame_mess, ) if confirm: selected_game.edit_gameinfo(add_line=False) all_games.remove(selected_game) config.remove_section(selected_game.name) config.save() if not all_games: UI.quit_application() # If we have no games, nothing can be done selected_game = all_games[0] selectedGame_radio.set(0) add_menu_opts(game_menu)
def ImportPortfolio(): """File -> Portfolio Read the portfolio from a file""" with open(PORTFOLIO, 'w') as f: portfolio = GetPortfolio() keys = portfolio.keys() count = 1 for stock in sorted(keys): if portfolio[stock]['units'] > 0.1: found = False while not found: symbol = askstring('Symbols', '(%d/%d) Enter symbol for:\n%s' % \ (count, len(keys), stock)) if symbol != None: price = GetPriceForSymbol(symbol) if price > 0.0: if askyesno(symbol, 'Is %.2f correct?' % (price * 0.01)): scaling = 0.01 else: scaling = 1.0 f.write(Stock(symbol, stock, 'TICKER', 0.01, 0.00, '20130811202000', scaling ).ToCSV()) found = True else: if not askretrycancel('Symbols', 'Cannot find symbol %s' % \ symbol): found = False else: found = True count += 1
def pesquisar_atribuir_conta_destino(self): if self.edt_transferencia.get() != self.desc_transf: dado = self.pesquisar(self.contas, 'id', 'descricao', filtro="descricao ILIKE '%%%s%%' and id <> '%s'" % (self.edt_transferencia.get(), self.id_conta), quantidade=(1,)) # print(bd_contas.dml) if dado: if self.id_conta == int(dado[0][0]): showinfo("Atenção", "Conta %s já está sendo usada como conta origem" % self.edt_conta.get()) self.edt_transferencia.delete(0, 'end') self.edt_transferencia.insert(0, self.desc_transf) else: self.id_transf = int(dado[0][0]) self.edt_transferencia.delete(0, 'end') self.edt_transferencia.insert(0, dado[0][1]) else: self.id_transf = 0 if askyesno("Atenção", "Deseja cadastrar a conta %s" % self.edt_transferencia.get()): contas = FrmContas(self, self.contas) contas.edt_descricao.insert(0, self.edt_conta.get()) # Se não fechar o form. FrmContas if not self.wait_window(contas): self.pesquisar_atribuir_conta_destino() else: self.edt_transferencia.delete(0, 'end') self.edt_transferencia.insert(0, self.desc_transf)
def save(self, *tab): """Save the contents of the textbox""" if tab is int(): tabToSave = tab else: tabToSave = self.selectedTab self.updateFilename() if (self.tabs[tabToSave].changed or self.master.master.textFrame.changed): yesno = messagebox.askyesno( title="Save note?", message="The tab has been changed. Would you like to save?") if yesno: a = self.master.master.saveFile(1) b = self.master.master.saveFile(4) if a == 1 or b == 1: return 1 else: return 0 else: return 0 else: return 0
def game_over(self): self.is_game_over = True from tkinter import messagebox if messagebox.askyesno('GAME OVER', 'Restart ?'): self.restart() else: self.add_high_score()
def excluir(self, event): if self.id_lanc == 0: showinfo("Atenção", "Consulte um registro para excluir") elif askyesno("Atenção", "Deseja realmente excluir %s" % self.edt_descricao.get()): self.lancamentos.excluir("id = %s" % self.id_lanc) self.limpar_campos()
def deleteExistingContact(self): global namereal confirm = messagebox.askyesno(title = 'Please Confirm', message = 'Are you sure you want to delete {} from your contacts'.format(namereal)) if confirm == True: deleteContact(namereal) self.refreshContactList() messagebox.showinfo(title = 'Confirmed!', message = 'Your contact {} has successfully been deleted from your address book!'.format(namereal))
def clearLogs() : choice = messagebox.askyesno(title = "Clear Logs?", message = "Would you like to delete the application's logs?") if choice == True : try : os.remove('ERROR_LOG.txt') except IOError : pass
def play_game(game): result = "" while not result: print_game(game) choice = input("Cell[1-9 or q to quit]: ") if choice.lower()[0] == "q": save = mb.askyesno("Save game", "Save game before quitting?") if save: oxo_logic.save_game(game) quit_game() else: try: cell = int(choice) - 1 if not (0 <= cell <= 8): # check range raise ValueError except ValueError: print("Choose a number between 1 and 9 or 'q' to quit ") continue try: result = oxo_logic.user_move(game, cell) except ValueError: mb.showerror("Invalid cell", "Choose an empty cell") continue if not result: result = oxo_logic.computer_move(game) if not result: continue elif result == "D": print_game(game) mb.showinfo("Result", "It's a draw") else: print_game(game) mb.showinfo("Result", "Winner is {}".format(result))
def pesquisar_atribuir_pessoa(self): if self.edt_pessoa.get() != self.desc_pessoa: dado = self.pesquisar(self.pessoas, 'cpf', 'nome', filtro="cpf ILIKE '%%%s%%' OR nome ILIKE '%%%s%%'" % (self.edt_pessoa.get(), self.edt_pessoa.get()), quantidade=(1,)) if dado: self.cpf_pessoa = dado[0][0] self.edt_pessoa.delete(0, 'end') self.edt_pessoa.insert(0, dado[0][1]) else: self.cpf_pessoa = "" if askyesno("Atenção", "Deseja cadastrar a pessoa %s" % self.edt_pessoa.get()): pessoas = FrmPessoas(self, self.pessoas) if self.edt_pessoa.get()[0] in string.digits: pessoas.edt_cpf.delete(0, 'end') pessoas.edt_cpf.insert(0, self.edt_pessoa.get()) else: pessoas.edt_nome.insert(0, self.edt_pessoa.get()) # Se não fechar o form. FrmContas if not self.wait_window(pessoas): self.pesquisar_atribuir_pessoa() else: self.edt_pessoa.delete(0, 'end') self.edt_pessoa.insert(0, self.desc_pessoa)
def fechar(): titulo = 'Fechar a aplicação' msg = 'Você realmente deseja fechar o aplicativo' if messagebox.askyesno(titulo, msg): exit() else: pass
import tkinter as tk from tkinter import messagebox from tkinter import simpledialog root = tk.Tk() root.withdraw() answer = True while (answer): name = simpledialog.askstring("Type your full name", "Enter your name") result = "Your name is: " + name idNumber = simpledialog.askinteger("Input four digit ID number", "Enter ID#") result = result + "\n" + "Your ID# is: " + str(idNumber) + "\n" cost = simpledialog.askfloat("Input cost per credit hour", "Enter cost per credit") result = result + "Cost per credit hour is: " + str(cost) + "\n" messagebox.showinfo("Display Results", result) answer = messagebox.askyesno("Ask Again", "Do you want to re-type the input")
def quit(): e=messagebox.askyesno("Billing System","Do you want to exit") if e>0: billing.destroy()
def dialog(): var = box.askyesno('Message Box', 'Proceed?') if var == 1: box.showinfo('Yes Box', 'Proceeding...') else: box.showwarning('No Box', 'Cancelling...')
def salir(): a = messagebox.askyesno(title="Cerrar", message="Confirma salir de la aplicación?") if a == TRUE: root.destroy()
def exitQuestions(self): result = tm.askyesno("", "Test unfinished, are you want to exit?") if result == True: root.destroy() else: return """Security measure that backs up a copy of the test results by creating a text file"""
def prediction_and_comparison(model, sequence, labels_ids, labels, h, l, input_vocab_size): """ Prediction function Creating dictionaries for converting keys from string to int and back. Chosing seed for prediction. New token prediction in loop for l, comparison of predicted value and real, asking user "if this anomaly?". If it is not anomaly, adding this case to labels_accordance_dict dictionary. After all doing shift on by one element by adding to seed predicted value and popping out first element. Args: model: all of model information, such as layers, batch_size, nodes. sequence: string sequence needed for seed for prediction. labels_ids: list of strings of keys ids workflow for prediction. labels: list of strings of keys for prediction. l: int length of predicted sequence. h: int length of token sequence for training and prediction. input_vocab_size: prediction keys count. labels_dict: dictionary of keys, for converting string keys to int. inverted_labels_dict: dictionary for inverse keys converting. labels_accordance_dict: dictionary for accordance between predicted and real values of workflow keys. seed: string seed for prediction. res_seq: result string sequence. Return: List of string, which contains started seed and subsequent predicted values. """ labels_dict = dict(zip(labels, [i for i in range(0, len(labels))])) inverted_labels_dict = {v: k for k, v in labels_dict.items()} labels_accordance_dict = dict(zip(labels, [[] for i in labels])) sequence = [labels_dict[item] for item in sequence] seed = sequence[0:h] sequence = [inverted_labels_dict[item] for item in sequence] res_seq = [] * len(sequence) * l res_seq.extend([inverted_labels_dict[item] for item in seed]) for i in range(0, l): seq = np.reshape(seed, (1, len(seed), 1)) seq = seq / float(input_vocab_size) pr = model.predict(seq, verbose=0) index = np.argmax(pr) pred = inverted_labels_dict[index] if sequence[h + i] != pred: if pred not in labels_accordance_dict[sequence[h + i]]: user_answer = messagebox.askyesno( "Warning!", f"Anomaly detected, is it okay?\n {sequence[h + i]} == {pred}" ) if user_answer: labels_accordance_dict[sequence[h + i]].append(pred) else: messagebox.showerror("Warning!", "Need to fix!!!") res_seq.append(pred) seed.append(labels_dict[pred]) seed.pop(0) return res_seq
def patch(self): log.info(f"Input iso: {self.input_iso_path.path.get()}") log.info(f"Input track: {self.input_mod_path.path.get()}") log.info(f"Output iso: {self.output_iso_path.path.get()}") # If ISO or mod zip aren't provided, raise error if not self.input_iso_path.path.get(): messagebox.showerror("Error", "You need to choose a MKDD ISO or GCM.") return if not self.input_mod_path.get_paths(): messagebox.showerror( "Error", "You need to choose a MKDD Track/Mod zip file.") return # Open iso and get first four bytes # Expected: GM4E / GM4P / GM4J with open(self.input_iso_path.path.get(), "rb") as f: gameid = f.read(4) # Display error if not a valid gameid if gameid not in GAMEID_TO_REGION: messagebox.showerror( "Error", "Unknown Game ID: {}. Probably not a MKDD ISO.".format(gameid)) return # Get gameid region = GAMEID_TO_REGION[gameid] # Create GCM object with the ISO log.info("Patching now") isopath = self.input_iso_path.path.get() iso = GCM(isopath) iso.read_entire_disc() # Create ZipToIsoPatcher object patcher = ZipToIsoPatcher(None, iso) at_least_1_track = False conflicts = Conflicts() skipped = 0 code_patches = [] for mod in self.input_mod_path.get_paths(): log.info(mod) patcher.set_zip(mod) if patcher.is_code_patch(): log.info("Found code patch") code_patches.append(mod) if len(code_patches) > 1: messagebox.showerror( "Error", "More than one code patch selected:\n{}\nPlease only select one code patch." .format("\n".join(os.path.basename(x) for x in code_patches))) return elif len(code_patches) == 1: patcher.set_zip(code_patches[0]) patch_name = "codepatch_" + region + ".bin" log.info("{0} exists? {1}".format( patch_name, patcher.src_file_exists(patch_name))) if patcher.src_file_exists(patch_name): patchfile = patcher.zip_open(patch_name) patch = DiffPatch.from_patch(patchfile) dol = patcher.get_iso_file("sys/main.dol") src = dol.read() dol.seek(0) try: patch.apply(src, dol) dol.seek(0) patcher.change_file("sys/main.dol", dol) log.info("Applied patch") except WrongSourceFile: do_continue = messagebox.askyesno( "Warning", "The game executable has already been patched or is different than expected. " "Patching it again may have unintended side effects (e.g. crashing) " "so it is recommended to cancel patching and try again " "on an unpatched, vanilla game ISO. \n\n" "Do you want to continue?") if not do_continue: return else: patch.apply(src, dol, ignore_hash_mismatch=True) dol.seek(0) patcher.change_file("sys/main.dol", dol) log.info("Applied patch, there may be side effects.") # Go through each mod path for mod in self.input_mod_path.get_paths(): # Get mod zip log.info(mod) mod_name = os.path.basename(mod) patcher.set_zip(mod) if patcher.is_code_patch(): continue config = configparser.ConfigParser() #log.info(trackzip.namelist()) if patcher.src_file_exists("modinfo.ini"): modinfo = patcher.zip_open("modinfo.ini") config.read_string(str(modinfo.read(), encoding="utf-8")) log.info( f"Mod {config['Config']['modname']} by {config['Config']['author']}" ) log.info(f"Description: {config['Config']['description']}") # patch files #log.info(trackzip.namelist()) arcs, files = patcher.get_file_changes("files/") for filepath in files: patcher.copy_file("files/" + filepath, "files/" + filepath) conflicts.add_conflict(filepath, mod_name) for arc, arcfiles in arcs.items(): if arc == "race2d.arc": continue srcarcpath = "files/" + arc if not iso.file_exists(srcarcpath): continue #log.info("Loaded arc:", arc) destination_arc = Archive.from_file( patcher.get_iso_file(srcarcpath)) for file in arcfiles: #log.info("files/"+file) patcher.copy_file_into_arc("files/" + arc + "/" + file, destination_arc, file, missing_ok=False) conflicts.add_conflict(arc + "/" + file, mod_name) newarc = BytesIO() destination_arc.write_arc_uncompressed(newarc) newarc.seek(0) patcher.change_file(srcarcpath, newarc) if "race2d.arc" in arcs: arcfiles = arcs["race2d.arc"] #log.info("Loaded race2d arc") mram_arc = Archive.from_file( patcher.get_iso_file("files/MRAM.arc")) race2d_arc = Archive.from_file(mram_arc["mram/race2d.arc"]) for file in arcfiles: patcher.copy_file_into_arc("files/race2d.arc/" + file, race2d_arc, file, missing_ok=False) conflicts.add_conflict("race2d.arc/" + file, mod_name) race2d_arc_file = mram_arc["mram/race2d.arc"] race2d_arc_file.seek(0) race2d_arc.write_arc_uncompressed(race2d_arc_file) #race2d_arc_file.truncate() newarc = BytesIO() mram_arc.write_arc_uncompressed(newarc) newarc.seek(0) patcher.change_file("files/MRAM.arc", newarc) elif patcher.src_file_exists("trackinfo.ini"): at_least_1_track = True trackinfo = patcher.zip_open("trackinfo.ini") config.read_string(str(trackinfo.read(), encoding="utf-8")) #use_extended_music = config.getboolean("Config", "extended_music_slots") replace = config["Config"]["replaces"].strip() replace_music = config["Config"]["replaces_music"].strip() log.info("Imported Track Info:") log.info( f"Track '{config['Config']['trackname']}' created by " f"{config['Config']['author']} replaces {config['Config']['replaces']}" ) minimap_settings = json.load(patcher.zip_open("minimap.json")) conflicts.add_conflict(replace, mod_name) bigname, smallname = arc_mapping[replace] if replace in file_mapping: _, _, bigbanner, smallbanner, trackname, trackimage = file_mapping[ replace] else: _, trackimage, trackname = battle_mapping[replace] # Copy staff ghost patcher.copy_file("staffghost.ght", "files/StaffGhosts/{}.ght".format(bigname)) # Copy track arc track_arc = Archive.from_file(patcher.zip_open("track.arc")) if patcher.src_file_exists("track_mp.arc"): track_mp_arc = Archive.from_file( patcher.zip_open("track_mp.arc")) else: track_mp_arc = Archive.from_file( patcher.zip_open("track.arc")) # Patch minimap settings in dol dol = DolFile(patcher.get_iso_file("sys/main.dol")) patch_minimap_dol( dol, replace, region, minimap_settings, intended_track=(track_arc.root.name == smallname)) dol._rawdata.seek(0) patcher.change_file("sys/main.dol", dol._rawdata) patch_musicid(track_arc, replace_music) patch_musicid(track_mp_arc, replace_music) rename_archive(track_arc, smallname, False) rename_archive(track_mp_arc, smallname, True) newarc = BytesIO() track_arc.write_arc_uncompressed(newarc) newarc_mp = BytesIO() track_mp_arc.write_arc_uncompressed(newarc_mp) patcher.change_file("files/Course/{}.arc".format(bigname), newarc) patcher.change_file("files/Course/{}L.arc".format(bigname), newarc_mp) log.info(f"replacing files/Course/{bigname}.arc") if replace == "Luigi Circuit": if patcher.src_file_exists("track_50cc.arc"): patcher.copy_file("track_50cc.arc", "files/Course/Luigi.arc") else: rename_archive(track_arc, "luigi", False) newarc = BytesIO() track_arc.write_arc_uncompressed(newarc) patcher.change_file("files/Course/Luigi.arc", newarc) if patcher.src_file_exists("track_mp_50cc.arc"): patcher.copy_file("track_mp_50cc.arc", "files/Course/LuigiL.arc") else: rename_archive(track_mp_arc, "luigi", True) newarc = BytesIO() track_mp_arc.write_arc_uncompressed(newarc) patcher.change_file("files/Course/LuigiL.arc", newarc) if bigname == "Luigi2": bigname = "Luigi" if smallname == "luigi2": smallname = "luigi" # Copy language images missing_languages = [] main_language = config["Config"]["main_language"] for srclanguage in LANGUAGES: dstlanguage = srclanguage if not patcher.src_file_exists( "course_images/{}/".format(srclanguage)): #missing_languages.append(srclanguage) #continue srclanguage = main_language coursename_arc_path = "files/SceneData/{}/coursename.arc".format( dstlanguage) courseselect_arc_path = "files/SceneData/{}/courseselect.arc".format( dstlanguage) lanplay_arc_path = "files/SceneData/{}/LANPlay.arc".format( dstlanguage) mapselect_arc_path = "files/SceneData/{}/mapselect.arc".format( dstlanguage) if not iso.file_exists(coursename_arc_path): continue #log.info("Found language", language) patcher.copy_file( "course_images/{}/track_big_logo.bti".format( srclanguage), "files/CourseName/{}/{}_name.bti".format( dstlanguage, bigname)) if replace not in battle_mapping: coursename_arc = Archive.from_file( patcher.get_iso_file(coursename_arc_path)) courseselect_arc = Archive.from_file( patcher.get_iso_file(courseselect_arc_path)) patcher.copy_file_into_arc( "course_images/{}/track_small_logo.bti".format( srclanguage), coursename_arc, "coursename/timg/{}_names.bti".format(smallname)) patcher.copy_file_into_arc( "course_images/{}/track_name.bti".format( srclanguage), courseselect_arc, "courseselect/timg/{}".format(trackname)) patcher.copy_file_into_arc( "course_images/{}/track_image.bti".format( srclanguage), courseselect_arc, "courseselect/timg/{}".format(trackimage)) newarc = BytesIO() coursename_arc.write_arc_uncompressed(newarc) newarc.seek(0) newarc_mp = BytesIO() courseselect_arc.write_arc_uncompressed(newarc_mp) newarc_mp.seek(0) patcher.change_file(coursename_arc_path, newarc) patcher.change_file(courseselect_arc_path, newarc_mp) else: mapselect_arc = Archive.from_file( patcher.get_iso_file(mapselect_arc_path)) patcher.copy_file_into_arc( "course_images/{}/track_name.bti".format( srclanguage), mapselect_arc, "mapselect/timg/{}".format(trackname)) patcher.copy_file_into_arc( "course_images/{}/track_image.bti".format( srclanguage), mapselect_arc, "mapselect/timg/{}".format(trackimage)) newarc_mapselect = BytesIO() mapselect_arc.write_arc_uncompressed(newarc_mapselect) newarc_mapselect.seek(0) patcher.change_file(mapselect_arc_path, newarc_mapselect) lanplay_arc = Archive.from_file( patcher.get_iso_file(lanplay_arc_path)) patcher.copy_file_into_arc( "course_images/{}/track_name.bti".format(srclanguage), lanplay_arc, "lanplay/timg/{}".format(trackname)) newarc_lan = BytesIO() lanplay_arc.write_arc_uncompressed(newarc_lan) newarc_lan.seek(0) patcher.change_file(lanplay_arc_path, newarc_lan) # Copy over the normal and fast music # Note: if the fast music is missing, the normal music is used as fast music # and vice versa. If both are missing, no copying is happening due to behaviour of # copy_or_add_file function if replace in file_mapping: normal_music, fast_music = file_mapping[replace_music][0:2] patcher.copy_or_add_file( "lap_music_normal.ast", "files/AudioRes/Stream/{}".format(normal_music), missing_ok=True) patcher.copy_or_add_file( "lap_music_fast.ast", "files/AudioRes/Stream/{}".format(fast_music), missing_ok=True) if not patcher.src_file_exists("lap_music_normal.ast"): patcher.copy_or_add_file( "lap_music_fast.ast", "files/AudioRes/Stream/{}".format(normal_music), missing_ok=True) if not patcher.src_file_exists("lap_music_fast.ast"): patcher.copy_or_add_file( "lap_music_normal.ast", "files/AudioRes/Stream/{}".format(fast_music), missing_ok=True) conflicts.add_conflict("music_" + replace_music, mod_name) else: log.warning("not a race track or mod, skipping...") skipped += 1 if at_least_1_track: patch_baa(iso) log.info("patches applied") #log.info("all changed files:", iso.changed_files.keys()) if conflicts.conflict_appeared: resulting_conflicts = conflicts.get_conflicts() warn_text = ( "File change conflicts between mods were encountered.\n" "Conflicts between the following mods exist:\n\n") for i in range(min(len(resulting_conflicts), 5)): warn_text += "{0}. ".format(i + 1) + ", ".join( resulting_conflicts[i]) warn_text += "\n" if len(resulting_conflicts) > 5: warn_text += "And {} more".format(len(resulting_conflicts) - 5) warn_text += ( "\nIf you continue patching, the new ISO might be inconsistent. \n" "Do you want to continue patching? \n") do_continue = messagebox.askyesno("Warning", warn_text) if not do_continue: messagebox.showinfo("Info", "ISO patching cancelled.") return log.info(f"writing iso to {self.output_iso_path.path.get()}") try: iso.export_disc_to_iso_with_changed_files( self.output_iso_path.path.get()) except Exception as error: messagebox.showerror( "Error", "Error while writing ISO: {0}".format(str(error))) raise else: if skipped == 0: messagebox.showinfo("Info", "New ISO successfully created!") else: messagebox.showinfo("Info", ( "New ISO successfully created!\n" "{0} zip file(s) skipped due to not being race tracks or mods." .format(skipped))) log.info("finished writing iso, you are good to go!")
def ex(): '''Asks the user if they would like to leave the app. If true closes the app.''' confirm = messagebox.askyesno("Exit", "Do you want to exit") if confirm: root.destroy()
def get(Nompatient, entree, Birthvalue, Birthentree): """ Test at first time and after when file was earased """ MsgBox = messagebox.askyesno('Save data', 'Do you want to save ?') if MsgBox == 1: """ mot = "-" mot2 = "--" mot3 = "---" mot4 = "----" mot5 = "-----" mot6 = "------" mot7 = "-------" """ Nompatient = entree.get() Birthvalue = Birthentree.get() print(Nompatient) print(Birthvalue) try: if os.path.getsize('./newpatient/entryfile.txt'): print("+ File 'entryfile.txt' exist !") #searchLine1(Nompatient, Birthvalue) try: if os.path.getsize('./newpatient/entryfile2.txt'): print("+ File 'entryfile2.txt' exist !") #searchLine2(Nompatient, Birthvalue) try: if os.path.getsize('./newpatient/entryfile3.txt'): print("+ File 'entryfile3.txt' exist !") #searchLine3(Nompatient, Birthvalue) try: if os.path.getsize( './newpatient/entryfile4.txt'): print( "+ File 'entryfile4.txt' exist !") #searchLine4(Nompatient, Birthvalue) try: if os.path.getsize( './newpatient/entryfile5.txt' ): print( "+ File 'entryfile5.txt' exist !" ) #searchLine5(Nompatient, Birthvalue) try: if os.path.getsize( './newpatient/entryfile6.txt' ): print( "+ File 'entryfile6.txt' exist !" ) #searchLine6(Nompatient, Birthvalue) try: if os.path.getsize( './newpatient/entryfile7.txt' ): print( "+ File 'entryfile7.txt' exist !" ) #searchLine7(Nompatient, Birthvalue) except FileNotFoundError as outcom: print( "+ Sorry, file 'entryfile7.txt' not exist !" ) print(str(outcom)) print( "+ File 'entryfile7.txt' created !" ) with open( './newpatient/entryfile7.txt', 'w' ) as namefile: namefile.write( Nompatient + '\n') namefile.write( Birthvalue + '\n') except FileNotFoundError as outcom1: print( "+ Sorry, file 'entryfile.txt6' not exist !" ) print(str(outcom1)) print( "+ File 'entryfile.txt6' created !" ) with open( './newpatient/entryfile6.txt', 'w') as namefile: namefile.write( Nompatient + '\n') namefile.write( Birthvalue + '\n') except FileNotFoundError as outcom2: print( "+ Sorry, file 'entryfile5.txt' not exist !" ) print(str(outcom2)) print( "+ File 'entryfile5.txt' created !" ) with open( './newpatient/entryfile5.txt', 'w') as namefile: namefile.write(Nompatient + '\n') namefile.write(Birthvalue + '\n') except FileNotFoundError as outcom3: print( "+ Sorry, file 'entryfile4.txt' not exist !" ) print(str(outcom3)) print("+ File 'entryfile4.txt' created !") with open('./newpatient/entryfile4.txt', 'w') as namefile: namefile.write(Nompatient + '\n') namefile.write(Birthvalue + '\n') except FileNotFoundError as outcom4: print("+ Sorry, file 'entryfile3.txt' not exist !") print(str(outcom4)) print("+ File 'entryfile3.txt' created !") with open('./newpatient/entryfile3.txt', 'w') as namefile: namefile.write(Nompatient + '\n') namefile.write(Birthvalue + '\n') except FileNotFoundError as outcom5: print("+ Sorry, file 'entryfile2.txt' not exist !") print(str(outcom5)) print("+ File 'entryfile2.txt' created !") with open('./newpatient/entryfile2.txt', 'w') as namefile: namefile.write(Nompatient + '\n') namefile.write(Birthvalue + '\n') except FileNotFoundError as outcom6: print("+ Sorry, file 'entryfile.txt' not exist !") print(str(outcom6)) print("+ File 'entryfile.txt' created !") with open('./newpatient/entryfile.txt', 'w') as namefile: namefile.write(Nompatient + '\n') namefile.write(Birthvalue + '\n') gui.destroy()
def exit(self): key = messagebox.askyesno("Clear", "Do you want to exit?") if key > 0: self.screen.destroy() else: return
# ダイアログを表示するために必要なモジュール import tkinter.messagebox as mb import tkinter as tk # tkinterのウィンドウを非表示にする root = tk.Tk() root.withdraw() # ダイアログを表示 ans = mb.askyesno("質問", "ラーメンは好きですか?") if ans == True: # OKボタンがあるだけのダイアログを表示 mb.showinfo("同意", "僕も好きです") else: mb.showinfo("本当?", "まさか、ラーメンが嫌いだなんて")
def confirm_close(): return messagebox.askyesno( message="You have unsaved changes. Are you sure you want to close?", icon="question", title="Unsaved changes", )
def conversion(self, fen): '''Convert the directory to Iso ''' try: if self.size != "Trop volumineux": # if self.files != "": if self.savefiles != "": loop = self.lookingfor() annuler = "no" if self.choice_iso.get() == "1": if loop == "": #Decide to create iso, we find etfsboot, we ask if we want to use this file reponse = askyesno( "Erreur etfsboot", "Vous avez choisi de faire un iso systeme bootable,qui est indisponible dans le fichier\n\ Voulez-vous le compresser tout de meme?" ) if reponse == False: annuler = "yes" else: loop = "" else: #if not if loop != "": reponse = askyesno( "etfsboot trouve", "Vous avez choisi de compresser\n\ Voulez-vous le compresser en un systeme bootable?" ) if reponse == False: loop = "" else: pass if annuler == "no": #if cancel == no #The progess bar window progress = tkinter.Toplevel() progress.geometry("380x70+{0}+{1}".format( str(fen.winfo_x()), str(int(fen.winfo_y() + 220)))) progress.title("Conversion...") progress.minsize(380, 70) progress.maxsize(380, 70) progress.iconbitmap("bmp.ico") progress.grab_set() self.progress = tkinter.ttk.Progressbar( progress, orient="horizontal", length=361, mode="determinate") self.progress.place(x=10, y=35) self.cancel = tkinter.ttk.Button( progress, image=self.image_clean, command=progress.destroy) self.cancel.place(x=340, y=5) cmd = self.configuration() self.label_purcent = tkinter.Label(progress, text="") self.label_purcent.place(x=175, y=10) start = 0 niveau = 0 if loop != "": cmd.append(loop) cmd.append(self.files) self.name_control = self.code_name() Name = self.get_Name.get() + self.name_control if Name == self.name_control: Name = os.getlogin() + self.name_control full_name = os.path.basename( self.files) + "_" + Name + ".iso" #if self.if_iso_already_exist(full_name,os.path.dirname(self.files)): #full_name = os.path.basename(self.files)+"_"+Name+"@.iso" cmd.append(self.savefiles + "/" + full_name) dude = threading.Thread(target=self.ProgressBar, args=(niveau, cmd, Name, progress)) dude.start() else: # that's mean the directory is not define, it's empty question = askyesno( 'Emplacement non defini', "Voulez-vous enregistrer l'ISO au meme endroit ?") if question == False: self.saveas() else: # wants to create the iso file to the same directory self.savefiles = os.path.dirname(self.files) self.conversion(fen) else: # Didn't choice folder to compress showwarning("ERREUR", "Dossier non defini") else: # Folder is too big , max 15 Gb showwarning("ERREUR", "Le dossier est trop volumineux") except AttributeError as Error: showerror("ERREUR", "Verifiez si c'est bien fait") except OSError: #Something wrong is happened showinfo("ERREUR", "Quelque chose de mal s'est passe !!!")
def deleteRecord(): prompt = messagebox.askyesno("delete file?", "Are you sure you want to delete this file?") if prompt == True: con, cursor = db_con() cursor = con.cursor( buffered=True) # added for mitigating against PREVIOUS error selected = listbox.curselection()[0] # grab index of selected element fileIDStore = show() # print(fileIDStore[selected]) global selectedFileID selectedFileID = (fileIDStore[selected]) cursor.execute("""SELECT l.Location_Description, Fragment_id FROM filefrag.files as f INNER JOIN filefrag.fragments as g on f.File_id = g.File_id INNER JOIN filefrag.location l on g.Location_id = l.Location_id WHERE f.File_id = '""" + str(selectedFileID) + """'ORDER BY Index_ ASC;""") rows = cursor.fetchall() global fragmentName_One, fragmentName_Two, fragmentName_Three, fragmentName_Four # fragment locations fragmentLoc_One = rows[0][0] fragmentLoc_Two = rows[1][0] fragmentLoc_Three = rows[2][0] fragmentLoc_Four = rows[3][0] # fragment ids fragmentName_One = rows[0][1] fragmentName_Two = rows[1][1] fragmentName_Three = rows[2][1] fragmentName_Four = rows[3][1] # check the encryption type or lack there of by fetching the encryption id of the file cursor.execute( "SELECT Encryption_id from filefrag.fragments where File_id='" + str(selectedFileID) + "';") encryptionID = cursor.fetchone() encryptionID = encryptionID[0] print(encryptionID) #delete all fragment records from database cursor.execute( "DELETE FROM `filefrag`.`fragments` WHERE (`File_id` = '%s');" % (selectedFileID)) #delete all encryption records from database cursor.execute( "DELETE FROM `filefrag`.`encryption` WHERE (`Encryption_id` = '%s');" % (encryptionID)) #delete all file detail records from database cursor.execute( "DELETE FROM `filefrag`.`files` WHERE (`File_id` = '%s');" % (selectedFileID)) con.commit() con.close() show() #Delete fragments from providers delete_provider(fragmentLoc_One, fragmentName_One) delete_provider(fragmentLoc_Two, fragmentName_Two) delete_provider(fragmentLoc_Three, fragmentName_Three) delete_provider(fragmentLoc_Four, fragmentName_Four) outputLogbox.insert( INSERT, '\n File deleted at: ' + str(dateTimeNow)[:-7] + '\n') else: infoMessageBox('delete file?', 'No changes made')
def on_closing(root): if messagebox.askyesno("Quit", "Do you really wish to quit?"): plt.close('all') root.destroy()
def quit(self): end = messagebox.askyesno('Zavřít', 'Opravdu?') if end: self.root.quit()
def exitApp(e=None): ask = messagebox.askyesno("Exit", "Do You really want to exit the app?") if ask: sys.exit(root.destroy()) else: pass
def exit(self): response = messagebox.askyesno('TK Retail Store', 'Do you want to exit?') if response == True: self.root.destroy()
def exit(self, *args): op = messagebox.askyesno("WARNING", "Your Unsaved Data May be Lost!!") if op > 0: self.root.destroy() else: return
def window_end_game(): answer = mb.askyesno(title="end game", message="restart?") return answer
def on_quit(self): if messagebox.askyesno("Quit", "Do you want to quit?"): self.quit()
def i_exit(): m_exit = messagebox.askyesno("Exit System", " Do you want to quit?") if m_exit > 0: space.destroy() return
# Yes_No.py from tkinter import * from tkinter import messagebox top = Tk() top.title("Messagebox") top.geometry("100x100") messagebox.askyesno("Ask", "This is Yes/No!") top.mainloop()
def quit(self): really_quit = messagebox.askyesno("Quiting?", "Do you really want to quit?") if really_quit: self.window.destroy()
def clear_chat(): if messagebox.askyesno("PyBot Says", "Do you really want ot delete recent Chats"): self.text_area.delete(0.0, END)
def byebye(): exit = messagebox.askyesno("exit", "Quit?") if exit == True: window.destroy() else: pass
# askyesno() # askokcancel() # askretrycancel() # askyesnocancel() # askquestion() # Filedialog types: # askdirectory() # asksaveasfile(mode) # asksaveasfilename() # askopenfile(mode) # askopenfiles(mode) # askopenfilename() # askopenfilenames() # askyesno message: messagebox.askyesno(title='Hungry?', message='Have you eaten?') # prompt the user to browse for a file or dialogue path filename = filedialog.askopenfile() # retrieve name of selected file: # print(filename.name) ''' when you set off a Markdown section sith triple quotes, it will exist as a multiline comment and won't run as code ''' # open the colorchooser colorchooser.askcolor(initialcolor='#FFFFFF') # after the user makes a selection in the colorchooser, it returns # a list with two items:
def exit(): e=messagebox.askyesno('Exit','Do you want to exit') if e>0: root.destroy()
def checkbeforeleaving(): if messagebox.askyesno("Overwrite annotation file ?"): app.saveAnnotations() root.destroy()
def _exit(self) -> None: """Destory window and exit game""" if msgbox.askyesno("Confirm", "Do you really want exit this game?"): self._root.destroy() __import__("sys").exit(0)