def deleteItem(self, *args): # first get confirmation if self.info.typeMarker: # user name = self.info.username.get() if name == 'admin': tkMessageBox.showinfo("Not allowed", "Deleting the admin user is not allowed!") return 0 if not tkMessageBox.askyesno(message='Are you sure you want to delete user ' + str(name) + '?',\ icon='question', title='Confirm deletion'): return 0 else: #this is a group, we need to be sure its not in use ... name = self.info.username.get() for auser in self.parent.users: if auser[2] == name: tkMessageBox.showinfo("Group is still in use!", "User " + str(auser[0]) +\ " is still a member of group " + str(name) + "!") return 0 if not tkMessageBox.askyesno(message='Are you sure you want to delete group ' + str(name) +\ '?', icon='question', title='Confirm deletion'): return 0 # now delete the item if not guifunctions.deleteData(self.parent, name, self.info.typeMarker): print "UPDATE Failed" return 0 self.parent.reloadAccounts() return 1
def update(self): com = self.comEntry.get() dir = self.fileEntry.get() user1_file = os.path.join("newest","user1.bin") files = [os.path.join(dir, "bin",file) for file in ["boot_v1.1.bin", user1_file, "esp_init_data_default.bin", "blank.bin"]] if any(not(os.path.exists(file)) for file in files): list = "\n".join(files) showerror("Fatal Error", "Did you choose the correct root directory?\nOne of these files does not exist:\n%s"%list) return commands = [] commands.append(self.format_command(com, "0x00000", files[0])) commands.append(self.format_command(com, "0x01000", files[1])) commands.append(self.format_command(com, "0x7C000", files[2])) commands.append(self.format_command(com, "0x7E000", files[3])) for i,c in enumerate(commands): success = False while not success: print("calling: "+" ".join(c)) p = subprocess.Popen(c, stdout=subprocess.PIPE, bufsize=1) for line in iter(p.stdout.readline, b''): print line, p.stdout.close() p.wait() if p.poll()!=0: if not askyesno("Warning", "Failed to connect.\nAre you sure your board is connected to the specified port?\n" "If so, try power cycling."): return else: if(i!=3): askyesno("Power Cycle", "Success. Power cycle your board to continue.") success = True showinfo("Success", "Firmware successfully updated!")
def destroy(self): """ See if we want to save before closing """ from tkMessageBox import askyesno if not self.safe_close: Toplevel.destroy(self) return if not hasattr(self, 'fname'): # No filename? We have to ask to save if askyesno('Save File?', 'Do you want to save the text in this ' 'window?', parent=self): self.saveastext() Toplevel.destroy(self) return # If we are here, we want to ask to save if self.original_state is DISABLED and self.up_to_date: # Already up-to-date Toplevel.destroy(self) elif self.original_state is NORMAL or not self.up_to_date: # Now we have to do text comparison. Yuck file_text = open(self.fname, 'r').read() window_text = str(self.text.get('0.0', END)) if file_text != window_text: if askyesno('Save File?', 'Do you want to save the text in this ' 'window?', parent=self): self.savetext() Toplevel.destroy(self) return
def OnDoubleClick(self): """Called on a double-click on the icon.""" self.status.set(self.path) # Directories: list them in window if os.path.isdir(self.path): dirmax = int(self.textbox.limits[3].get()) dirsize = os.path.getsize(self.path) if dirsize > dirmax: basename = os.path.basename(self.path) txt = "%s may contain a very large number of files.\nDisplay anyway?" % (basename) if not askyesno("Warning", txt): return cmd = "ls -lF %s " % self.path out = getoutput(cmd) filelisting = self.path + "\n" + out self.textbox.clear() self.textbox.settext(filelisting) # view text files in window (sometimes pdfs slip thru) elif self.ext != ".pdf" and Spiderutils.istextfile(self.path): # check if html files are sent to browser if self.ext == ".html" or self.ext == ".htm": browser = self.textbox.limits[4].get() if browser: webbrowser.open(self.path) return textmax = self.textbox.limits[2] tmax = int(textmax.get()) textsize = os.path.getsize(self.path) if textsize > tmax: basename = os.path.basename(self.path) txt = "%s is %d bytes.\nDisplay anyway?" % (basename, textsize) if not askyesno("Warning", txt): return try: fp = open(self.path,'r') B = fp.readlines() except: pass fp.close() self.textbox.clear() for line in B: self.textbox.component('text').insert(END, str(line)) # binaries else: spidertype = Spiderutils.isSpiderBin(self.path) if spidertype != 0: #== "image": infotxt = self.getSpiderInfo(self.path) self.textbox.clear() self.textbox.component('text').insert(END, infotxt) if spidertype == "image": self.putImage(self.path, clear=0) elif self.ext.lower() in self.imagetypes: self.putImage(self.path)
def read_config_file(self): root=Tk() root.withdraw() if not os.path.exists(self.configfile): if not tkMessageBox.askyesno('ERROR',abedocs.ErrorMessages(101)): tkMessageBox.showerror('PROGRAM EXITING', abedocs.ErrorMessages(103)) sys.exit(1) else: try: xmlroot=et.parse(self.configfile).getroot() xmlacnts=xmlroot.find('Accounts') for acnt in xmlacnts.getchildren(): acntname=acnt.attrib['email'] password=acnt.find('password').text disabled=acnt.find('disabled').text retries=acnt.find('retries').text acttype=acnt.find('type').text accountsdict[acntname]={'password':password,'disabled':disabled, 'retries':retries, 'type':acttype} xmlpreferences=xmlroot.find('Preferences') for preference in xmlpreferences.getchildren(): settingsdict[preference.tag]=preference.text except: if not tkMessageBox.askyesno('ERROR',abedocs.ErrorMessages(102)): tkMessageBox.showerror('PROGRAM EXITING', abedocs.ErrorMessages(103)) sys.exit(1)
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 = tkMessageBox.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 = tkMessageBox.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 main(): #Initiate GUI in Python. root = Tk() #Hide root window root.withdraw() #Start program called: "CCTS Demo Program". w = Label(root, text="CCTS Demo Program") w.pack() #display author tkMessageBox.showinfo("CenturyLink Cloud Application", "Author: Andrew Nielsen, Date: 10/26/2015") #call userInput() method. userInput() #Start if statement with a loop to reintiate program. question = tkMessageBox.askyesno("CenturyLink Cloud Portal", "Would you like to create another sandbox account?") while question == True: userInput() response = tkMessageBox.askyesno("CenturyLink Cloud Portal", "Would you like to create another sandbox account?") if response == False: sys.exit(0) else: sys.exit(0)
def obtenerSpinbox(): #print(valor.get()) tkMessageBox.showinfo("Mensaje","Tu seleccionaste " + valor.get()) tkMessageBox.showwarning("Advertencia","Esto es un mensaje de Advertencia") tkMessageBox.askquestion("Pregunta 1", "Cualquier cosa") tkMessageBox.askokcancel("Pregunta 2", "Cualquier cosa") tkMessageBox.askyesno("Pregunta 3", "Cualquier cosa") #Responde en boleano a diferencia del question tkMessageBox.askretrycancel("Pregunta 1", "Cualquier cosa")
def ask_quit(): status.config(text="Quiting") if tkMessageBox.askyesno("Quit", "Do you want to Quit?"): if tkMessageBox.askyesno("Delete Temporary Files", "Do you want to remove the temporary files?"): path = os.path.dirname(os.path.abspath(__file__))+'/temp/' if os.path.exists(path): shutil.rmtree(path) root.destroy()
def askYesorNo(message, title=None, parent=None): " returns True or False " if title == None: title = 'Warning' if parent != None: ret = askyesno(title, message, parent=parent) else: ret = askyesno(title, message) return ret
def __doExit(this): this.__timeLbl.set(" ") this.__msgLbl.set(" ") if this.__isChanged: if tkMessageBox.askyesno("", "Phone book has changed!\nSave it first?"): this.__doSave() if tkMessageBox.askyesno("", "Really Quit?"): this.__root.quit()
def generateImage(self): bookheight = int(self.BOOKHEIGHT.get()) booksheets = int(self.BOOKSHEETS.get()) text = str(self.RENDERTEXT.get()) font = self.SelectedFont.get() print text + " using font " + font print str(bookheight) + "mm high, " + str(booksheets) + " sheets wide" from PIL import Image, ImageFont, ImageDraw IMAGEMODE = "1" #monochrome bitmap #create monochrome bitmap image, 10*booksheets wide, bookheight high, 0=black, 1=white image = Image.new(IMAGEMODE, (booksheets*10,bookheight), 1) from tkMessageBox import showinfo #showinfo("Mode", image.mode) draw = ImageDraw.Draw(image) #fontheight = bookheight*4/5 #scale text to 80% of book height fontheight = bookheight renderfont = ImageFont.truetype(font,fontheight) print "Text Size " + str(draw.textsize(text, renderfont)) print "Image Size " + str(image.size) #offset to attempt to centre font rather than bottom aligned (upward shift by 5%) #print (bookheight/-20) draw.text((0,(bookheight/-20)), text, fill=0, font=renderfont) filename = text + " using " + font + " - " + str(bookheight) + "mm, " + str(booksheets) + "p.bmp" image.save(filename) image = image.convert("L") image = RemoveWhiteColumns(image) image = image.resize((booksheets,bookheight)) image.save(filename) image.show() from tkMessageBox import askyesno if(askyesno("Continue?", "Preview ok? Continue?")): #print px document = OpenAndInitialiseDocX(filename) print "Document opened" CalculateAndWriteDocX(document, image) document.save(filename + ".docx") #else: #filename is not defined, program should exit #print "No Filename provided to Open" #todo add exception handling and ask for filename. #print "Complete" #image.save("blahoutput.bmp") if not askyesno("Another?", "Create another from Text?"): self.quit()
def save_primer_from_edit(self, parent_window=None): """Save the primer in the DB when doing a primer Edit""" if not parent_window: parent_window = self.eval_win # Check if the primer name has been changed first, and ask for confirmation of rename if self.primername_var.get() != self.edit_primer_name or not self.edit_primer_name: import tkMessageBox ok = tkMessageBox.askyesno('Primer Name altered', 'Rename primer and save?\n', parent=parent_window) if not ok: self.primername_var.set(self.edit_primer_name) return #rename primer based on value in entry widget else: new_name=self.primername_var.get() if new_name: #only rename if there isn't already a primer with the same name if not self.data['primer_dict'].has_key(new_name): self.data['primer_dict'][new_name]=self.data['primer_dict'][self.edit_primer_name].copy() del self.data['primer_dict'][self.edit_primer_name] self.edit_primer_name = new_name self.i_parent.new_name = new_name #otherwise don't allow rename else: tkMessageBox.showwarning('Primer name already present', 'Primer name already present.\nPlease choose another name', parent=parent_window) return # Update the sequence and description fields for the primer DNA=self.eval_var.get() # Validation check if primer is changed (maybe by mistake) if not DNA: ok = tkMessageBox.askyesno('No sequence entered', 'No sequence entered.\nDo you wish to save anyway?', parent=parent_window) if not ok: return import mutation ok,DNA_sequence=mutation.check_DNA(DNA) self.data['primer_dict'][self.edit_primer_name]['sequence']=DNA_sequence self.data['primer_dict'][self.edit_primer_name]['description']=self.descr_var.get() #print 'Primer Info:',self.edit_primer_name,self.data['primer_dict'][self.edit_primer_name] # Clear all graphics if getattr(self,'pDB',None): self.pDB.clear_pDB_objects() # Close the window self.eval_win.destroy() return
def setAuthKey(self): key = self.entry_key.get() if not self.keyLooksValid(key): if not tkMessageBox.askyesno("Invalid Key", "That key looks invalid to me. Are you sure?"): return False fh = open(self.getKeyPath(), 'w+') fh.write(key) fh.close() tkMessageBox.askyesno('Saved', "AuthKey Saved!")
def continue_deployment(): host_deploy_process_map = {} global virt_g, phy_g, canvas, host_config_map # create configuration generator update_color_virtual_network(virt_g.nodes(), 'g') update_color_physical_network(phy_g.nodes(), 'r') canvas.draw() [error_msg, ret_code, dir] = generate_configuration(config_java_jar) if ret_code != 0: messagebox.showerror(title="Error From Configuration Generator", message=error_msg) sys.exit(1) host_config_ini = dir+'/host-config-exp.ini' host_config_map = read_host_config_file(host_config_ini) host_config_map_len = len(host_config_map) if host_config_map_len == 0: messagebox.showerror(title="Error From Configuration Generator", message='something went wrong with configuration generator') sys.exit(1) messagebox.showinfo(title='Physical Host', message='Establishing connection to physical hosts') for host, [ip, cfg_file] in host_config_map.iteritems(): [scp_ret_code, scp_out, scp_err] = copy_to_remote([cfg_file, create_vne_py], 'root', ip, '~/') if scp_ret_code != 0: is_exit = messagebox.askyesno(title='Physical Host', message='Error in communicating to '+ host + '\nDo you want to continue?') if is_exit == messagebox.NO: sys.exit(1) else: update_color_physical_network([host]) canvas.draw() for host_name, [ip, cfg_file] in host_config_map.iteritems(): #print 'before launch ' + host_name file_name = cfg_file.split('/')[-1] dep_process = launch_deployment_on_remote_host(ip, file_name) host_deploy_process_map[dep_process.stdout.fileno()] = [host_name, dep_process] poller.register(dep_process.stdout.fileno(), select.EPOLLHUP) i = 0 no_process = len(host_deploy_process_map) while i < no_process: complet_fds = monitor_deployment_process() print complet_fds i += len(complet_fds) for fd in complet_fds: [host_name, dep_process] = host_deploy_process_map.pop(fd) dep_process.wait() print dep_process.returncode if dep_process.returncode == 0: update_networks_according_to_mapping(host_name) else: is_exit = messagebox.askyesno(title='Physical Host', message='Error while deploying on '+ host_name + '\nDo you want to continue?') if is_exit == messagebox.YES: sys.exit(1) connect_vm_button.config(state='normal') continue_button.config(state='disabled') return
def verify_calc(self, item, item_quantity): """Подсобная функция для работы функции verify(). Проверяет наличие на складе ингредиентов, входящих в сложный товар на момент продажи. В случае недостатка предлагает совершить мгновенный приход товара. Возвращает True или False в зависимости от итогового наличия необходиомого количества товара на складе для продажи.""" result = True for calc in queries.item_calculation(item): if calc.ingredient.calculation: for calc2 in queries.item_calculation(calc.ingredient): quantity = int(queries.items_in_storage( calc2.ingredient)) need_quantity = (item_quantity * calc2.quantity * calc.quantity) if quantity < need_quantity: if tkMessageBox.askyesno(u'Внимание!', u'Вы пытаетесь продать %d единицы товара "%s".' % (need_quantity, calc2.ingredient.name) + u'\nНа складе имеется всего %d единицы!'% quantity + u'\nВыполнить мгновенную поставку товара?'): incoming = panel() if not queries.execute_incoming_express( calc2.ingredient, incoming) or (need_quantity > incoming + quantity): result = False else: result = False else: quantity = int(queries.items_in_storage(calc.ingredient)) need_quantity = item_quantity * calc.quantity if quantity < need_quantity: if tkMessageBox.askyesno(u'Внимание!', u'Вы пытаетесь продать %d единицы товара "%s".' % (need_quantity, calc.ingredient.name) + u'\nНа складе имеется всего %d единицы!'% quantity + u'\nВыполнить мгновенную поставку товара?'): incoming = panel() if not queries.execute_incoming_express( calc.ingredient, incoming) or (need_quantity > incoming + quantity): result = False else: result = False return result
def onQuitMail(): # exit mail tool, delete now if askyesno("PyMail", "Verify Quit?"): if toDelete and askyesno("PyMail", "Really Delete Mail?"): getpassword() thread.start_new_thread(deleteMailThread, (toDelete,)) busyInfoBoxWait("Deleting mail") if errInfo: showerror("PyMail", "Error while deleting:\n" + errInfo) else: showinfo("PyMail", "Mail deleted from server") rootWin.quit()
def behandla(self, value): #Koll för vilken typ av ärende det gäller. if value[1] == "DWG": for ticket in self.server.ticket.query("status=accepted&summary=%s&type=DWG"%value[0]): askBox = tkMessageBox.askyesno("Behandla", 'Vill du sätta ärende: "%s - %s" som status behandlad?' %(value[0], value[1])) if askBox: self.server.ticket.update(ticket, "%s" %user, {'status':'Behandlad', 'description':'%s' %user}) if value[1] == "Geodetisk": for ticket in self.server.ticket.query("status=accepted&summary=%s&type=Geodetisk"%value[0]): askBox = tkMessageBox.askyesno("Behandla", 'Vill du sätta ärende: "%s - %s" som status behandlad?' %(value[0], value[1])) if askBox: self.server.ticket.update(ticket, "%s" %user, {'status':'Behandlad', 'description':'%s' %user})
def cancel_task(self): if self.config_parser and tkMessageBox.askyesno('Exit WAF', 'Save changes?'): (retVal, error) = self.validate_categories() if retVal: self.waf_ctx.save_user_settings(self.config_parser) else: if not tkMessageBox.askyesno('Error on save WAF', 'Unable to save.\n\n%s\n\nExit without saving?' % error): return False self.parent.signal_task_finished(self) return True
def clickStart(self): """ Close the current setup application, then initiate the main PiPark program. """ if self.__is_verbose: print "ACTION: Clicked 'Start'" # turn off toggle buttons self.spaces_button.setOff() self.cps_button.setOff() # set initial responses response = False response1 = False response2 = False # if setup data has not been saved. Ask user if they would like to save # before continuing. if not self.__is_saved: response = tkMessageBox.askyesno( title = "Save Setup", type = tkMessageBox.YESNOCANCEL, message = "Most recent changes to setup have not been saved." + "Would you like to save before running PiPark?" ) if response: self.saveData() # data is saved, ask the user if they are sure they wish to quit. else: response = tkMessageBox.askyesno( title = "Save Setup", message = "Are you ready to leave setup and run PiPark?" ) # user wishes to quit setup and run pipark, so do it! if response: # ensure data is valid before continuing if not self.checkData(): # data invalid, so display message and return tkMessageBox.showinfo( title = "PiPark Setup", message = "Saved data is invalid. Please ensure that " + "there are 3 control points and at least 1 parking " + "space marked." ) return self.quit_button.invoke() if self.__is_verbose: print "INFO: Setup application terminated. " main.main()
def exit(self): #exit method disconnects from the SSP-4 and exits the program question1 = askyesno(title = 'Exit?', message = 'Do you really want to exit?') if question1: question2 = askyesno(title = "Save?", message = "Do you want to save your file before exiting?") ser.write('SEXIT3') if question2: self.save() sys.exit() else: sys.exit() else: pass
def main(): idir = getcwd() OOT_ROM_NAME = askopenfilename(title="OoT Debug ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir) if(not OOT_ROM_NAME): return MM_ROM_NAME = askopenfilename(title="Decompressed MM ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir) if(not MM_ROM_NAME): return mmtmp = open(MM_ROM_NAME,"rb") mmtmp.seek(0,2) if ( mmtmp.tell() == 0x2000000 ): showerror(title = "uh lol", message = "Decompressed MM ROM, dummy!\nAborting port!") sys.exit(-1) argv__ = ['z64porter.py', OOT_ROM_NAME, MM_ROM_NAME] askaddress = True port_en = None while 1: argv_ = argv__[:] argv_ .append( askstring(title = "OoT scene", prompt = "Scene to replace in OoT (use 0x if hex):" )) if(not argv_[-1]): return argv_ .append( askstring(title = "MM scene", prompt = "Scene to port from MM (use 0x if hex):" )) if(not argv_[-1]): return if (askaddress): if (askyesno(title = "Address", message = "Insert at your own address?" )): argv_.append( "-o" ) addr_msg = "Address (hex) to insert port at:" if (port_en != None): addr_msg += "\nReccomended: %08X"%( port_en ) argv_.append( "0x%s" % (askstring(title = "Address", prompt = addr_msg ))) else: askaddress = False else: argv_.append("-o") argv_.append("0x%08X" % port_en) if (askyesno(title = "Safe mode", message = "Port in safe mode?" )): argv_.append( "-s" ) if (askyesno(title = "Music", message = "Use your own music value?" )): argv_.append( "-m" ) argv_.append(askstring(title = "Music", prompt = "Music value (use 0x if hex):" )) argv_.append("-q") try: port_st,port_en = port_scene( argv_ ) showinfo(title="Success", message="Scene ported successfully\nPort offsets:\n%08X - %08X"%(port_st,port_en)) except: showerror(title="Uhoh!", message="Failure :(.\nIf you opened this from a shell,\nplease report the error message from." ) break if not (askyesno(title = "Another", message = "Port another scene?" )): break
def close(self): #close method closes the current text file question1 = askyesno(title = "Close?", message = "Do you really want to close your file?") if question1: question2 = askyesno(title = "Save?", message = "Do you want to save your file before closing?") if question2: self.save() textwindow.delete(1.0, END) textwindow.mark_set(INSERT, 1.0) else: textwindow.delete(1.0, END) textwindow.mark_set(INSERT, 1.0) else: pass
def reportConfig(*args): """submit configuration back to chimera team""" from tkMessageBox import askyesno name, save = filenames() curExists = os.path.exists(name) if curExists: os.remove(name) savExists = os.path.exists(save) if not curExists and not savExists: return curInfo = ( gi.getVendor(), gi.getRenderer(), gi.getVersion(), gi.getOS(), [gi.has(i) for i in range(gi.NumFeatures)] ) if savExists: with open(save) as f: savInfo = readGfxInfo(f) else: savInfo = None if curInfo != savInfo \ and askyesno(title="OpenGL Debug Report", default="no", message="Save current OpenGL debug configuration?"): with open(save, 'w') as f: writeGfxInfo(f, curInfo[4]) savExists = True savInfo = curInfo if not savExists or curInfo != savInfo: # if the user didn't care to save the configuration, # we don't want to know about it return if not askyesno(title="OpenGL Debug Report", default="no", message="Report successful OpenGL debug configuration to Chimera team?"): return from cStringIO import StringIO info = StringIO() print >> info, 'Results of OpenGL Debugging:\n' writeGfxInfo(info, curInfo[4]) import BugReport br_gui = BugReport.displayDialog(wait=True) if not br_gui: return br = BugReport.BugReport(info=info.getvalue(), description='Successful OpenGL debug configuration') br_gui.setBugReport(br) if not br_gui._toplevel.winfo_viewable(): br_gui._toplevel.wait_visibility() while br_gui._toplevel.winfo_viewable(): br_gui._toplevel.wait_visibility() # wait for it to disappear
def behandla(self, aerende, value): if value[1] == "DWG": for ticket in self.server.ticket.query("status=accepted&summary=%s&type=DWG" % aerende): askBox = tkMessageBox.askyesno( "Behandla", 'Vill du sätta ärende: "%s - %s" som status behandlad?' % (value[0], value[1]) ) if askBox: self.server.ticket.update(ticket, "%s" % user, {"status": "Behandlad", "description": "%s" % user}) if value[1] == "Geodetisk": for ticket in self.server.ticket.query("status=accepted&summary=%s&type=Geodetisk" % aerende): askBox = tkMessageBox.askyesno( "Behandla", 'Vill du sätta ärende: "%s - %s" som status behandlad?' % (value[0], value[1]) ) if askBox: self.server.ticket.update(ticket, "%s" % user, {"status": "Behandlad", "description": "%s" % user})
def factoryReset(self): id=self.getSelectedMotor() if id<0: tkMessageBox.showerror("Selection Error","Please select a motor first") else: answer=tkMessageBox.askyesno("Factory Reset","Warning: you are about to completely reset motor ID %d, its ID and baudrate will be changed, are you sure you want to proceed?"%(id)) if not answer: return do=True if 1 in self.chain.motors.keys(): answer=tkMessageBox.askyesno("ID Conflict","Warning: the motor ID 1 obtained after factory reset is already attributed on your chain, are you sure you want to proceed?") if not answer: do=False if do: self.chain.factory_reset(id) self.connect()
def deleteChosen(self, aerende, value): if value[1] == "DWG": for ticket in self.server.ticket.query("status=new&user=%s&summary=%s&type=DWG" % (user, aerende)): askBox = tkMessageBox.askyesno( "Ta bort", 'Är du säker på att du vill ta bort ärende: "%s - %s" ?' % (value[0], value[1]) ) if askBox: self.server.ticket.delete(ticket) for ticket in self.server.ticket.query("status=Behandlad&user=%s&summary=%s&type=DWG" % (user, aerende)): askBox = tkMessageBox.askyesno( "Ta bort", 'Är du säker på att du vill ta bort ärende: "%s - %s" ?' % (value[0], value[1]) ) if askBox: self.server.ticket.update(ticket, "borttagen av %s" % user, {"status": "Behandlad - Confirmed. "}) for ticket in self.server.ticket.query("status=accepted&user=%s&summary=%s&type=DWG" % (user, aerende)): askBox = tkMessageBox.showinfo( "Ta bort", 'Det går inte att ta bort ärende: "%s - %s". Ärendet är under behandling!' % (value[0], value[1]), ) if value[1] == "Geodetisk": for ticket in self.server.ticket.query("status=new&user=%s&summary=%s&type=Geodetisk" % (user, aerende)): askBox = tkMessageBox.askyesno( "Ta bort", 'Är du säker på att du vill ta bort ärende: "%s - %s" ?' % (value[0], value[1]) ) if askBox: self.server.ticket.delete(ticket) for ticket in self.server.ticket.query( "status=Behandlad&user=%s&summary=%s&type=Geodetisk" % (user, aerende) ): askBox = tkMessageBox.askyesno( "Ta bort", 'Är du säker på att du vill ta bort ärende: "%s - %s" ?' % (value[0], value[1]) ) if askBox: self.server.ticket.update(ticket, "borttagen av %s" % user, {"status": "Behandlad - Confirmed. "}) for ticket in self.server.ticket.query( "status=accepted&user=%s&summary=%s&type=Geodetisk" % (user, aerende) ): askBox = tkMessageBox.showinfo( "Ta bort", 'Det går inte att ta bort ärende: "%s - %s". Ärendet är under behandling!' % (value[0], value[1]), )
def Retrieve(self): confirm = tkMessageBox.askyesno("Confirm", "View student details?") if confirm is False: return else: from subprocess import call call("notepad Test.txt")
def backupdata(self): print "You requested the backup routine" self.option_add('*font', 'Helvetica -14') self.option_add("*Dialog.msg.wrapLength", "10i") # Check to see if the directories were set for something else if self.varSource.get() == "SourceDir" : tkMessageBox.showwarning("Warning!", "First set the source directory!") elif self.varDestination.get() == "DestinationDir" : tkMessageBox.showwarning("Warning!", "Also remember to set the destination directory!") # OK good to go else: result = tkMessageBox.askyesno("Ready to backup!!", "You will now synchronize your folder\n\n%s\n\ninto your backup folder:\n\n%s" %(os.path.basename(self.varSource.get()),self.varDestination.get())) if result : print "You have accepted to backup" self.DiskUsage = Tkinter.StringVar() DiskUsage = os.popen('du -hs "%s"'%(self.varSource.get())).read() tkMessageBox.showinfo("First notification", "Your job size is :\n" +DiskUsage+ "\n this could take a while, please be patient.") var_rsync_command = subprocess.Popen(["rsync", "-ahv", self.varSource.get(), self.varDestination.get()], stdout=subprocess.PIPE) # Trying to make the textbox update all the time for line in iter(var_rsync_command.stdout.readline,''): self.var_textbox.insert(Tkinter.END, line) self.var_textbox.update() self.var_textbox.yview(Tkinter.END) # tkMessageBox.showinfo("Backup complete","The rsync job has finished") else: print "You declined to backup your data"
def giveup(self, event="Bla"): t=time() if askyesno("Quit", "Do you really want to quit?"): self.given=1 self.parent.arcade() else: self.add-=time()-t
def scanFile(): filename = askopenfilename() if (filename != ""): try: output = subprocess.Popen(["./antiv", "scan", filename], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0] r = re.compile("\033\[[0-9;]+m") output = r.sub("", output) #tkMessageBox.showinfo("Scan Report", output) box = Tk() box.geometry("350x200") box.title("Sign File Report") s = Tkinter.Scrollbar(box) T = Tkinter.Text(box) T.focus_set() s.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) T.pack(side=Tkinter.LEFT, fill=Tkinter.Y) s.config(command=T.yview) T.config(yscrollcommand=s.set) T.insert('1.0', output) response = tkMessageBox.askyesno("Save", "Do you want to save report ?") if response == True: f_report = asksaveasfile(mode='w', defaultextension=".txt") if f_report is None: # asksaveasfile return `None` if dialog closed with "cancel". pass else: f_report.write(output) f_report.close() except: pass
def addRoute(self): ''' Adds a route between two cities, with option to go both directions :return: ''' # Source city source_name = tkSimpleDialog.askstring("Source name", "Please enter the source city") if source_name is None or self.g.getVertexByName(source_name) is None: if source_name is not None: tkMessageBox.showwarning("Name invalid", "City is not in current Network") return # Destination city dest_name = tkSimpleDialog.askstring( "Destination name", "Please enter the destination city") if dest_name is None or self.g.getVertexByName(dest_name) is None: if source_name is not None: tkMessageBox.showwarning("Name invalid", "City is not in current Network") return # Distance distance = tkSimpleDialog.askstring("Distance", "Please enter distance") if distance is None or distance < 0: if distance < 0: tkMessageBox.showwarning("Distance invalid", "Distance cannot be negative") return # Add reverse direction only if user says yes to both direction if tkMessageBox.askyesno("Both ways", "Do you want to add this route both ways?"): self.g.getVertexByName(dest_name).addEdge( self.g.getVertexByName(source_name).code, float(distance)) self.g.getVertexByName(source_name).addEdge( self.g.getVertexByName(dest_name).code, float(distance))
def solve(): # NOTE: Change it so that if keeps some of them as entry boxes, or just use a different color of label? ans = tkMessageBox.askyesno('Confirm', 'Are you sure you want to solve the current game?') if ans == 1: for i in range(0, 3): for j in range(len(solution[i])): if j in first: bgcolor = blueback else: bgcolor = whiteback l = Tkinter.Label(top, text=solution[i][j], width=2, background=bgcolor, borderwidth=1, font=('Helvetica', 18), justify="center") l.grid(row=i+1, column=j+1) for i in range(3, 6): for j in range(len(solution[i])): if j in second: bgcolor = blueback else: bgcolor = whiteback l = Tkinter.Label(top, text=solution[i][j], width=2, background=bgcolor, borderwidth=1, font=('Helvetica', 18), justify="center") l.grid(row=i+1, column=j+1) for i in range(6, 9): for j in range(len(solution[i])): if j in third: bgcolor = blueback else: bgcolor = whiteback l = Tkinter.Label(top, text=solution[i][j], width=2, background=bgcolor, borderwidth=1, font=('Helvetica', 18), justify="center") l.grid(row=i+1, column=j+1)
def Save(self): # Send saved delays to the SQL database and the ACC (if the data source is not 'Simulation') if self.data_source == 'Data': if (Time.now().mjd - self.time.mjd) > 1.0: question = "Warning: Data more than a day old. Are you sure you want to save delays to SQL and ACC?" else: question = "Save delays to SQL and ACC?" import cal_header as ch # Calculate delays relative to Ant 1 and tack Ant1-14 delay at end delays = self.delays[0] - self.delays delays = np.append(delays,self.delays[0]) # Have to change the sign of Ant 14 Y-X delay, hence the minus sign xydelays = np.append(self.xydelays,-float(self.dla14.get())) # Do not change delays for a missing antenna bad, = np.where(self.missing == 1) delays[bad] = 0.0 if askyesno("Write Delays",question): # All Y-X delays need a sign flip, hence the minus sign # ************ This block commented out due to loss of SQL ************** #ch.dla_update2sql(delays,-xydelays) ##ch.dla_update2sql(-delays,xydelays) # 300 MHz design uses flipped signs! #ch.dla_censql2table() # Replaced by ch.dla_update2table(delays,-xydelays)
def detect_interfence(self, image_thresh): brightness_hist = cv2.calcHist([image_thresh], [0], None, [256], [0, 255]) percent_dark = brightness_hist[0] / image_thresh.size # If 99% of thresholded image isn't dark, we probably have # a light source or glare in the image if (percent_dark < .99): # We will only warn about interference once each run self._seen_interference = True logging.warning( "Glare or light source detected. %f of the image is dark." % percent_dark) self._show_interference = tkMessageBox.askyesno( "Interference Detected", "Bright glare or a light source has been detected on the webcam feed, which will interfere with shot detection. Do you want to see a feed where the interference will be white and everything else will be black for a short period of time?" ) if self._show_interference: # calculate the number of times we should show the # interference image (this should be roughly 5 seconds) self._interference_iterations = 2500 / FEED_FPS
def delete_archive(self): """Deletes archive in archives directory.""" archive_exists = False # Reaffirms user decision and checks if archive exists. for archive in os.listdir(RELATIVE_PATH_TO_ARCHIVE_DIR): if archive[:-4] == self.archive_current.get(): if tkMessageBox.askyesno( "Archive deletion", "Are you sure you want to delete the '%s' archive?" % self.archive_current.get()): os.remove('RELATIVE_PATH_TO_ARCHIVE_DIR%s' % archive) archive_exists = True if archive_exists == False: tkMessageBox.showwarning( "No archive named '%s'" % self.archive_current.get(), "There is currently no archive named '%s'." % self.archive_current.get()) self.archive_list.activate( 'end') # Activates last item in archive_list. self.update_archive_list() self.archive_current.delete( 0, 'end') # Deletes text inside archive_current. self.archive_current.insert(0, self.archive_list.get( 'end')) # Inserts name of last archive in archive_list.
def _on_upload_btn_clicked(self): selected_rows = self.runresultsview.get_selection() if len(selected_rows) == 0: messagebox.showerror('Error', 'No tests selected.') return selected_qc_dir = self.qcdir_tree.selection() if len(selected_qc_dir) != 1: messagebox.showerror('Error', 'Destination not selected.') return qcdir = self.dir_dict[selected_qc_dir[0]] if not qcdir: messagebox.showerror('Error', 'path is blank') return assert qcdir.startswith('Root\\'), qcdir # remove "Root\" qcdir = qcdir[5:] results = self.results.copy() results['tests'] = [self.runresultsview.tests[row] for row in selected_rows] result = messagebox.askyesno( 'Confirm', ('Are you sure you want to upload to the following ' 'location?\n\n{}'.format(qcdir))) if not result: return work_in_background( self, lambda: importer.import_results( self.qcc, qcdir, results, self.attach_report.get()), lambda: messagebox.showinfo('Success', 'Import complete.'))
def cb_save(self): filename = self.prop["dump"] f = tkMessageBox.askyesno("Confirm", self.prop["message"]["save"]) if f is False: return try: yf = open(filename, "r") except: rospy.logwarn("ezui::open exception " + filename) return try: param = yaml.load(yf) except: yf.close() rospy.logwarn("ezui::parser exception") return yf.close() try: yf = open(filename, "w") dictlib.cross(param, rtkWidget.Param) yaml.dump(param, yf, default_flow_style=False) rtkWidget.Origin = param except: rospy.logwarn("ezui::dump exception") yf.close()
def cmbackup(): cmfile = tkFileDialog.askopenfilename(title='Select cmbackup', filetypes=[('Unsigned CMA Backup Files', '*.cmbackup')]) if cmfile.__contains__("Gravity Rush FULL GAME (3.61 only!).cmbackup"): print "DO WHAT YOU WANT CAZ A PIRATE IS FREE!!" zf = zipfile.ZipFile(cmfile) try: zf.extract(member="load.txt",path="temp") zf.extract(member="TitleID.txt",path="temp") except KeyError: tkMessageBox.showerror(title="Error 094",message="Invalid .cmbackup!") zf.close() load = open('temp/load.txt', 'r') loadtype = load.read() load.close() backupfile = open('temp/TitleID.txt', 'r') CMABACKUP = backupfile.read() backupfile.close() os.remove("temp/load.txt") os.remove("temp/TitleID.txt") os.removedirs("temp") print "Extracting CMBackup.." defs.extractZip(src=cmfile,dst=defs.getCmaDir() + '/EXTRACTED/'+loadtype+"/"+CMABACKUP) os.remove(defs.getCmaDir() + '/EXTRACTED/'+loadtype+"/"+CMABACKUP+"/"+"load.txt") os.remove(defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP + "/" + "TitleID.txt") if os.path.exists(defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP + '/savedata'): savedata = tkMessageBox.askyesno(title="Savedata",message="This .cmbackup contains savedata, would you like to use this savedata?\nYou may have problems with trophy eligiby if you do.") if savedata == False: shutil.rmtree(defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP + '/savedata') os.remove(defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP + '/savedata.psvmd-dec') accSelect_support.pushVars(CMABACKUP, loadtype) import sign sign.close_window(root) accSelect.vp_start_gui() print "Removing: "+defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP shutil.rmtree(defs.getCmaDir() + '/EXTRACTED/' + loadtype + "/" + CMABACKUP)
def nextCall(self): selected = '' i = 0 mtrs = [] nonActive = [] for var, value in sorted(self.cb.items()): if self.lcb[i] in self.motor_names: if value.get(): selected += self.lcb[i] selected += ' ' mtrs.append(self.lcb[i]) else: nonActive.append(self.lcb[i]) i += 1 # print mtrs # print nonActive if selected == '': # tkMessageBox.ERROR tkMessageBox.showerror( title='Warning', message='You need to select at least ONE Actor!') return None if tkMessageBox.askyesno( title='Warning', message='Warning: You selected folowing actors: ' + str(selected) + 'the rest of robot will be in mode "freeze" do you want to continue?' ): rec_fram = Toplevel() rec_fram.grab_set() rec_fram.transient(self.master) # self.master.wait_window(RECD) myRec = RECORDING_1(rec_fram, mtrs)
def generate(self): lessonInfo = readLessonFile(self.lessonFileName) examInfo = readExamFile(self.examFileName) projectInfo = readProjectFile(self.projectFileName) outputFileName = getOutputFile() if (writeCombinedFile(outputFileName, lessonInfo, examInfo, projectInfo, self.examTakeHighestAttempt.get(), self.usePctPoints.get(), self.projectTakeHighestAttempt.get(), self.missingScoreValueBox.get(), self.usePoints.get())): self.msg = Message(self, text="Finished. Output file generated OK.") #self.msg.grid() else: self.msg = Message( self, text="No output file specified. Cannot continue.") #self.msg.grid() if (not tkMessageBox.askyesno( "Finished", "Would you like to convert another file set?")): self.destroy() exit(0) else: self.reInit()
def set_variables(self, name, path, pics, cols, b, fn, d, h, f): if tkMessageBox.askyesno( "Path to save PDF?", "Would you like to save PDF\nin picture directory?"): self.filename = path + "/" + name else: temp = tkFileDialog.askdirectory(initialdir=path, title="Select Directory") if temp: self.filename = temp + "/" + name else: return 0 self.name = name self.path = path self.pics = pics self.cols = cols self.printBoard = b self.printName = fn self.printDate = d self.num_pics = len(pics) self.head = h self.foot = f self.size = (8.5 - (((cols - 1) * 0.25) + 1.0)) / cols return 1
def Save(self): # Send saved delays to the SQL database and the ACC (if the data source is not 'Simulation') if self.data_source == 'Data': if (Time.now().mjd - self.time.mjd) > 1.0: question = "Warning: Data more than a day old. Are you sure you want to save delays to SQL and ACC?" else: question = "Save delays to SQL and ACC?" import cal_header as ch # Calculate delays relative to Ant 1 and tack Ant1-14 delay at end delays = self.delays[0] - self.delays delays = np.append(delays, self.delays[0]) # Have to change the sign of Ant 14 Y-X delay, hence the minus sign xydelays = np.append(self.xydelays, -float(self.dla14.get())) # Do not change delays where both delays and xydelays are zero # which is taken as a missing antenna bad, = np.where(self.delays == 0) bad2, = np.where(self.xydelays == 0) idx1, idx2 = common_val_idx(bad, bad2) delays[bad[idx1]] = 0.0 if askyesno("Write Delays", question): # All Y-X delays need a sign flip, hence the minus sign ch.dla_update2sql(delays, -xydelays) #ch.dla_update2sql(-delays,xydelays) # 300 MHz design uses flipped signs! ch.dla_censql2table()
def recover_work(): with open(FOXDOT_TEMP_FILE) as f: text = f.read() if len(text): loading = tkMessageBox.askyesno( "Load unsaved work?", "Your code wasn't saved last time you used FoxDot, do you want to load any unsaved work?" ) self.root.update() if loading: self.set_all(text) else: self.clear_temp_file() self.text_as_string = self.get_all()
from Tkinter import * import tkMessageBox root = Tk() def callback(): print 'called the callback!' # code here filename = 'x' try: fp = open(filename) except: tkMessageBox.showwarning( 'Open file', 'Cannot open this file\n(%s)' % filename ) # return if tkMessageBox.askyesno('print', 'Print this fake report?'): #report.print() callback() mainloop()
def _send_cmd_to_thread(self, cmd=None, *args): self.logger.debug('received cmd: {}'.format(cmd)) if cmd == 'MONITOR_MODE': if self.IS_WIRESHARK_RUNNING or self.IS_SITE_SURVEY_RUNNING: self.logger.debug('Wireshark is running: {}, Site Survey is running: {}'.format(self.IS_WIRESHARK_RUNNING, self.IS_SITE_SURVEY_RUNNING)) try: #python 2.7 tkMessageBox.showerror("Error", "Other Task Running Please Wait...") except ImportError: #python 3.x messagebox.showerror("Error", "Other Task Running Please Wait...") return # Neither Wireshark nor Site Survey is running. #Now changing wifi interface to Monitor mode and set to target Frequency self.IS_FREQUENCY_SET = False channel = self.var_channel_option.get().split()[1] self.logger.debug('Chaning WiFi channel to {}'.format(channel)) mapping_cmd = self.CMD_MAPPING[cmd].substitute(channel=channel) elif cmd == 'WIFI_INFO': mapping_cmd = self.CMD_MAPPING[cmd] else: # for all other commands, wait until device is ready self.IS_DEVICE_READY = self.IS_DEVICE_CONNECTED and self.IS_WIFI_INFO_AVAILABLE and self.IS_FREQUENCY_SET self.logger.debug('device status - Conn: {}, WiFi: {}, Freq: {}'.format(self.IS_DEVICE_CONNECTED, self.IS_WIFI_INFO_AVAILABLE, self.IS_FREQUENCY_SET)) if not self.IS_DEVICE_READY: self.logger.debug('device not ready. just returning...') try: #python 2.7 tkMessageBox.showerror('Error', 'Device Not Ready Yet...') except ImportError: #python 3.x messagebox.showerror('Error', 'Device Not Ready Yet...') return if cmd == 'START_WIRESHARK': if self.IS_SITE_SURVEY_RUNNING: self.logger.debug('site survey is running. do not start wireshark') try: tkMessageBox.showerror('Error', 'Site Survey is running. Please Wait...') except ImportError: messagebox.showerror('Error', 'Site Survey is running. Please Wait...') return filter_expression = self.ent_set_filter.get() if filter_expression and not 'xx:xx:xx:xx:xx:xx' in filter_expression: # this means user entered capture filter option. if not re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', filter_expression, re.I): try: tkMessageBox.showerror('Error', 'Invalid capture filter') except ImportError: messagebox.showerror('Error', 'Invalid capture filter') return else: filter_expression = '"wlan.addr==' + filter_expression + '"' filter_option='"-f"' else: # this means no capture filter set filter_expression = '' filter_option='' self.logger.debug('filter option: {}, filter expression: {}'.format(filter_option, filter_expression)) if not self.IS_WIRESHARK_RUNNING and self.IS_WIRESHARK_INSTALLED: self.IS_WIRESHARK_RUNNING = True mapping_cmd = self.CMD_MAPPING[cmd].substitute(filter_option=filter_option, filter_expression=filter_expression) else: #prevent double-click in short period of time which causes double wireshark launching return elif cmd == 'STOP_WIRESHARK': mapping_cmd = 'taskkill /IM wireshark.exe' from subprocess import call, Popen, PIPE, STDOUT p = Popen(mapping_cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) stdout, stderr = p.communicate() return elif cmd == 'STOP_PLINK': mapping_cmd = 'taskkill /IM plink.exe /F /T' from subprocess import call, Popen, PIPE, STDOUT p = Popen(mapping_cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) stdout, stderr = p.communicate() return elif cmd == 'SITE_SURVEY': if self.IS_WIRESHARK_RUNNING: self.logger.debug('wireshark is running. do not start site survey') try: tkMessageBox.showerror('Error', 'Wireshark is running. Please Wait...') except ImportError: messagebox.showerror.showerror('Error', 'Wireshark is running. Please Wait...') return if not self.IS_SITE_SURVEY_RUNNING: self.IS_SITE_SURVEY_RUNNING = True mapping_cmd = self.CMD_MAPPING[cmd].substitute(timeout=args[0]) else: return elif cmd == 'STOP_DEVICE': # double-confirm try: yes = tkMessageBox.askyesno('Exit', 'Do you really want to shutdown device?') except: yes = messagebox.askyesno('Exit', 'Do you really want to shutdown device??') if not yes: return mapping_cmd = self.CMD_MAPPING[cmd] else: mapping_cmd = self.CMD_MAPPING[cmd] # now send cmd to ExeCmdThread self.logger.debug('send cmd to ExeCmdThread: cmd:{}, mapping_cmd:{}'.format(cmd, mapping_cmd)) self.queue_cmd_request.put((cmd, mapping_cmd))
def askYesNo(self, msg, title='Query'): return askyesno(title, msg, parent=self.parent)
def show_warning_dialog(self): if tkMessageBox.askyesno('Info', 'Open warning box?', default=tkMessageBox.NO): tkMessageBox.showwarning('Warning Box', 'This is a warning.')
def end_tournament(): if tkMessageBox.askyesno("End Tournament", "Are you sure you want to end this tournament?"): console.insert(END, "The tournament has been stopped\n")
def init_gui(self, parent): self.parent = parent parentwidth = parent.winfo_width() self.frame = tk.Frame(parent, borderwidth=2) self.frame.grid(sticky=tk.NSEW, columnspan=2) # Route info self.waypoint_prev_btn = tk.Button(self.frame, text="^", command=self.goto_prev_waypoint) self.waypoint_btn = tk.Button(self.frame, text=self.next_wp_label + self.next_stop, command=self.copy_waypoint) self.waypoint_next_btn = tk.Button(self.frame, text="v", command=self.goto_next_waypoint) self.jumpcounttxt_lbl = tk.Label(self.frame, text=self.jumpcountlbl_txt + str(self.jumps_left)) self.error_lbl = tk.Label(self.frame, textvariable=self.error_txt) # Plotting GUI self.source_ac = AutoCompleter(self.frame, "Source System", width=30) self.dest_ac = AutoCompleter(self.frame, "Destination System", width=30) self.range_entry = PlaceHolderEntry(self.frame, "Range (LY)", width=10) self.efficiency_slider = tk.Scale(self.frame, from_=1, to=100, orient=tk.HORIZONTAL, label="Efficiency (%)") self.efficiency_slider.set(60) self.plot_gui_btn = tk.Button(self.frame, text="Plot route", command=self.show_plot_gui) self.plot_route_btn = tk.Button(self.frame, text="Calculate", command=self.plot_route) self.cancel_plot = tk.Button(self.frame, text="Cancel", command=lambda: self.show_plot_gui(False)) self.csv_route_btn = tk.Button(self.frame, text="Import file", command=self.plot_file) self.clear_route_btn = tk.Button(self.frame, text="Clear route", command=self.clear_route) row = 0 self.waypoint_prev_btn.grid(row=row, columnspan=2) row += 1 self.waypoint_btn.grid(row=row, columnspan=2) row += 1 self.waypoint_next_btn.grid(row=row, columnspan=2) row += 1 self.source_ac.grid( row=row, columnspan=2, pady=(10, 0) ) # The AutoCompleter takes two rows to show the list when needed, so we skip one row += 2 self.dest_ac.grid(row=row, columnspan=2, pady=(10, 0)) row += 2 self.range_entry.grid(row=row, pady=10, sticky=tk.W) row += 1 self.efficiency_slider.grid(row=row, pady=10, columnspan=2, sticky=tk.EW) row += 1 self.csv_route_btn.grid(row=row, pady=10, padx=0) self.plot_route_btn.grid(row=row, pady=10, padx=0) self.plot_gui_btn.grid(row=row, column=1, pady=10, padx=5, sticky=tk.W) self.cancel_plot.grid(row=row, column=1, pady=10, padx=5, sticky=tk.E) row += 1 self.clear_route_btn.grid(row=row, column=1) row += 1 self.jumpcounttxt_lbl.grid(row=row, pady=5, sticky=tk.W) row += 1 self.error_lbl.grid(row=row, columnspan=2) self.error_lbl.grid_remove() row += 1 # Check if we're having a valid range on the fly self.range_entry.var.trace('w', self.check_range) self.show_plot_gui(False) if not self.route.__len__() > 0: self.waypoint_prev_btn.grid_remove() self.waypoint_btn.grid_remove() self.waypoint_next_btn.grid_remove() self.jumpcounttxt_lbl.grid_remove() self.clear_route_btn.grid_remove() if self.update_available: update_txt = "New Spansh update available!\n" update_txt += "If you choose to install it, you will have to restart EDMC for it to take effect.\n\n" update_txt += self.spansh_updater.changelogs update_txt += "\n\nInstall?" install_update = confirmDialog.askyesno("SpanshRouter", update_txt) if install_update: confirmDialog.showinfo( "SpanshRouter", "The update will be installed as soon as you quit EDMC.") else: self.update_available = False self.update_gui() return self.frame
# elif flagrun == 1 and arrived_flag == 0: # # button_text(event,'cancel',315,350,600,150,green,display_surface,image) # print('status : robot canceled !') # Tk().wm_withdraw() #to hide the main window # MsgBox = tkMessageBox.askyesno('Cancel?') # if MsgBox == TRUE: # pub.publish('cancel') ### SEND CANCEL DATA # print('published : cancel') # flagrun = 0 # else: # pass elif flagrun == 1 and arrived_flag == 1: print('status : robot arrvied !') Tk().wm_withdraw() #to hide the main window MsgBox = tkMessageBox.askyesno('Arrived') if MsgBox == TRUE: flagrun = 0 else: pass # capture user # if target != '': # print(target) # if target == 'cancel': # user = target # pub_user.publish(user) # print("published : '" + str(target) + "' and '" + str(user) + "'") # target = '' # user = '' # else:
def root_fermer(): # Prompt confirmation fermeture de la fenêtre if askyesno('Confirmer la fermeture', 'Êtes-vous sûr de vouloir quitter?'): root.quit()
def OnDoubleClick(self): """Called on a double-click on the icon.""" self.status.set(self.path) # Directories: list them in window if os.path.isdir(self.path): dirmax = int(self.textbox.limits[3].get()) dirsize = os.path.getsize(self.path) if dirsize > dirmax: basename = os.path.basename(self.path) txt = "%s may contain a very large number of files.\nDisplay anyway?" % ( basename) if not askyesno("Warning", txt): return cmd = "ls -lF %s " % self.path out = getoutput(cmd) filelisting = self.path + "\n" + out self.textbox.clear() self.textbox.settext(filelisting) # view text files in window (sometimes pdfs slip thru) elif self.ext != ".pdf" and Spiderutils.istextfile(self.path): # check if html files are sent to browser if self.ext == ".html" or self.ext == ".htm": browser = self.textbox.limits[4].get() if browser: webbrowser.open(self.path) return textmax = self.textbox.limits[2] tmax = int(textmax.get()) textsize = os.path.getsize(self.path) if textsize > tmax: basename = os.path.basename(self.path) txt = "%s is %d bytes.\nDisplay anyway?" % (basename, textsize) if not askyesno("Warning", txt): return try: fp = open(self.path, 'r') B = fp.readlines() except: pass fp.close() self.textbox.clear() for line in B: self.textbox.component('text').insert(END, str(line)) # binaries else: spidertype = Spiderutils.isSpiderBin(self.path) if spidertype != 0: #== "image": infotxt = self.getSpiderInfo(self.path) self.textbox.clear() self.textbox.component('text').insert(END, infotxt) if spidertype == "image": self.putImage(self.path, clear=0) elif self.ext.lower() in self.imagetypes: self.putImage(self.path)
xAxLine.set_data([-2 * PI, 2 * PI], [0, 0]) refLine.set_data(x, yRef) measLine.set_data(x, yMeas) outputLine.set_data(x, yOut) phaseShift.set_text('angular location = %.1f' % i) return xAxLine, refLine, measLine, outputLine, phaseShift #------------------------------------------------------------ # call FuncAnimation and save it ani = animation.FuncAnimation(fig, animate, frames=314, interval=30, blit=True, init_func=init) #------------------------------------------------------------ # ask user if they would like to save files filename = 'reference measured and output waveforms 001.mp4' saveChoice = tkMessageBox.askyesno( 'Save animation?', 'Would you like to save the animation as ' + filename + '?') if saveChoice: ani.save(filename, fps=30, extra_args=['-vcodec', 'libx264']) print('results have been saved as ' + filename) else: print('You have chosen not to save the animation')
def askYesNo(message): if has_tk(): from tkMessageBox import askyesno r = askyesno(title, message) has_tk() # must...make...tk...happy return r
import tkSimpleDialog from datetime import datetime from influxdb import InfluxDBClient import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(('192.168.0.7', 1113)) while True: server_socket.listen(0) client_socket, addr = server_socket.accept() data = client_socket.recv(65535) print("receive data from pi: " + data) application_window = Tkinter.Tk() result = tkMessageBox.askyesno( "POSTBOX", "Delivery has arrived.\n Do you confirm?\n You can watch CCTV at 192.168.1.12/zm \n", parent=application_window) if result is True: answer = 'Open' send_data = 'True' else: answer = 'refused' send_data = 'False' current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ') json_body = [{ "measurement": "Delivery", "time": current_time, "fields": { "Status": answer } }]
def yesno(self, title="Info", msg=""): return tkMessageBox.askyesno(title, msg)
# # print ("One lat, one long\n\n") # # print oneLat # # print oneLong #print "\nCalc for GE: " + finalLongCoordToDecimal #print "####################" #print "# End of debugging #" #print "####################" print "\nMD5 Hash: " + md5Val # The stuff below is just for debugging. It shows what I ripped from the array # print '\n\n\n' + str(rippedLatitude) # print '\n' + str(rippedLongitude) if tkMessageBox.askyesno("SPIES, 2014", "Do you want to locate on Google Maps now?"): webbrowser.open("https://maps.google.co.uk/maps?q=%s,%s" % (declat,declon)) print a print b print c print d print e print f else: print a print b print c print d print e
def askyesno(question): root = Tkinter.Tk() root.withdraw() answer = tkMessageBox.askyesno('Query', question) root.destroy() return answer
SongOrVideoLocation = SongOrVideoLocationSystem else: SongOrVideoLocationInternet = raw_input('\n' + name + ' Please enter song' 's url \n') SongOrVideoLocation = SongOrVideoLocationInternet while count < 4: print('\n Current working session: ' + time.ctime()) #prints current date and time time.sleep( work_time ) # pauses the program for given number of seconds ,here it's 10 sec root = Tk().withdraw() # hiding the main window var1 = tkMessageBox.askyesno( "Break Time", ('Hi ' + name + " would you like to take a break? ")) if (var1 == True) & (SongOrVideoLocation == SongOrVideoLocationInternet): webbrowser.open(SongOrVideoLocation) count += 1 time.sleep(break_time) var3 = tkMessageBox.askyesno( "Back to work", "Hi " + name + " your break session is over,would you like to go back to work?") if var3 == True: continue else: break elif (var1 == True) & (SongOrVideoLocation == SongOrVideoLocationSystem): try: #code to play song mixer.init()