def connect_to_server(self): try: try: self.clientObj.stop_processes() del (self.clientObj) self.clientObj = Client() self.clientObj.set_values(self.ip.get(), int(self.port.get()), float(self.subrate.get()), int(self.error.get()), int(self.block_size.get()), int(self.quality.get()), str(self.authentication.get())) self.clientObj.client() except Exception as e: self.clientObj = Client() self.clientObj.set_values(self.ip.get(), int(self.port.get()), float(self.subrate.get()), int(self.error.get()), int(self.block_size.get()), int(self.quality.get()), str(self.authentication.get())) self.clientObj.client() except socket.error as serr: if serr.errno == errno.ECONNREFUSED: askretrycancel(title="Socket Error", message=serr) except Exception as e: print(e)
def choose_cdpath(self): dirname = tkFileDialog.askdirectory( parent=self.root, initialdir="/", title="Where is your Daggerfall CD?") # Cancel if dirname == () or dirname == "": return # Invalid path all together if not os.path.exists(dirname) or not os.path.isdir(dirname): again = tkMessageBox.askretrycancel( title="Invalid", message="The path you selected is invalid!") if again: return self.choose_cdpath() else: sys.exit(-1) # Not a Daggerfall CD/Install if self.valid_cdpath(dirname): again = tkMessageBox.askretrycancel( title="Data not found", message="The path entered does not seem to contain " + "the proper Data, do you want to retry and " + "select a different path?") if again: return self.choose_cdpath() else: sys.exit(-1) daggerfall.set_cdpath(dirname)
def choose_cdpath(self): dirname = tkFileDialog.askdirectory(parent=self.root, initialdir="/", title="Where is your Daggerfall CD?") # Cancel if dirname == () or dirname == "": return # Invalid path all together if not os.path.exists(dirname) or not os.path.isdir(dirname): again = tkMessageBox.askretrycancel(title="Invalid", message="The path you selected is invalid!") if again: return self.choose_cdpath() else: sys.exit(-1) # Not a Daggerfall CD/Install if self.valid_cdpath(dirname): again = tkMessageBox.askretrycancel(title="Data not found", message="The path entered does not seem to contain "+ "the proper Data, do you want to retry and "+ "select a different path?") if again: return self.choose_cdpath() else: sys.exit(-1) daggerfall.set_cdpath(dirname)
def die(): tkMessageBox.showinfo("Window", "Information") tkMessageBox.showwarning("Window","Warning") tkMessageBox.showerror("Window","Error") tkMessageBox.askokcancel("Window", "noob?") tkMessageBox.askretrycancel("Window", "retry?") exit()
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 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 setval(): right1=check[0] right2=check[1] right3=check[2] wrong1=wronglist[0] wrong2=wronglist[1] wrong3=wronglist[2] if (right1==1 and right2==1 and right3==1 and wrong1==0 and wrong2==0 and wrong3==0) : tkMessageBox.showinfo("Congratulations","Congratulations") root.destroy() else: tkMessageBox.askretrycancel("Sorry","No image or incorrect image selected") mainset() randompics()
def btt_find_note(self): note_returned = (notepad.Notepad()).find_note(self.name.get()) print(note_returned) if note_returned is not None: nn = NewNote(parent=self.parent, controller=self.controller, note=note_returned) nn.grid(row=0, column=0, sticky="nsew") self.name.delete(0, 'end') nn.tkraise() else: tkMessageBox.askretrycancel("Retry", "No note found", icon="error") self.name.delete(0, 'end') self.name.focus_force()
def save_data(): try: file_deliveries = open("deliveries.txt", "a") file_deliveries.write( "Despot: \n") file_deliveries.write("%s\n" % depot.get()) file_deliveries.write( "Description \n") file_deliveries.write( "%s \n" % description.get()) file_deliveries.write( "Address: \n") file_deliveries.write( "%s \n" % address.get("1.0", 'end')) # clear up before data depot.set(None) description.delete(0, 'end') address.delete('1.0', 'end') except Exception, e: tkMessageBox.askretrycancel ("Error!", "Can't write to the file \n %s" % e)
def putChanges(self): """Save changes to the file back to Zope""" f = open(self.body_file, 'rb') body = f.read() f.close() headers = {'Content-Type': self.metadata.get('content_type', 'text/plain')} if hasattr(self, 'lock_token'): headers['If'] = '<%s> (<%s>)' % (self.path, self.lock_token) response = self.zope_request('PUT', headers, body) del body # Don't keep the body around longer then we need to if response.status / 100 != 2: # Something went wrong sys.stderr.write('Error occurred during HTTP put:\n%d %s\n' \ % (response.status, response.reason)) sys.stderr.write('\n----\n%s\n----' % response.read()) message = response.getheader('Bobo-Exception-Type','') if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Could not save to Zope.\nError ' 'occurred during HTTP put:\n%d %s\n%s') \ % (response.status, response.reason, message)): has_tk() # ugh, keeps tk happy self.putChanges() else: has_tk() # ugh return 0 return 1
def submit(): var = mvar.get() global picflag if var == picflag[1]: tkMessageBox.showinfo("Event Triggered", "Congratulations") mvar.set('') msg() else: tkMessageBox.showinfo("Sorry", "Worng Guess") mvar.set('') num = Var1.get() Var1.set(num - 1) if num == 1: tkMessageBox.askretrycancel( "Game Over", "Game Over \n Click on retry to play again") Var1.set(3)
def unlock(self): """Remove webdav lock from edited zope object""" if not hasattr(self, 'lock_token'): return 0 headers = {'Lock-Token':self.lock_token} response = self.zope_request('UNLOCK', headers) if response.status / 100 != 2: # Captain, she's still locked! message = response.getheader('Bobo-Exception-Type','') sys.stderr.write('Error occurred during lock request:\n%d %s\n%s' \ % (response.status, response.reason, message)) sys.stderr.write('\n----\n%s\n----' % response.read()) if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Unlock request failed:\n%d %s') \ % (response.status, response.reason)): has_tk() # ugh, keeps tk happy return self.unlock(token) else: has_tk() # ugh return 0 return 1
def popup(which, message, title=None): """Displays A Pop-Up Message.""" if title is None: title = which which = superformat(which) if which == "info": return tkMessageBox.showinfo(str(title), str(message)) elif which == "warning": return tkMessageBox.showwarning(str(title), str(message)) elif which == "error": return tkMessageBox.showerror(str(title), str(message)) elif which == "question": return tkMessageBox.askquestion(str(title), str(message)) elif which == "proceed": return tkMessageBox.askokcancel(str(title), str(message)) elif which == "yesorno": return tkMessageBox.askyesno(str(title), str(message)) elif which == "retry": return tkMessageBox.askretrycancel(str(title), str(message)) elif which == "entry": return tkSimpleDialog.askstring(str(title), str(message)) elif which == "integer": return tkSimpleDialog.askinteger(str(title), str(message)) elif which == "float": return tkSimpleDialog.askfloat(str(title), str(message))
def set_orientation(self, target): rv = messagebox.askokcancel( message=("Please connect and turn on the camera for {0} pages" .format(target)), title="Configure target page") if not rv: return devs = [] while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) except plugin.DeviceException: devs = [] if not devs: errmsg = "No devices could be found." elif len(devs) > 1: errmsg = "Make sure only one device is turned on!" else: break rv = messagebox.askretrycancel(message=errmsg, title="Error") if not rv: return devs[0].set_target_page(target) messagebox.showinfo(message="Please turn off the device.")
def portScan(self): ports = enumPorts() retrying = True while retrying: for port in ports: self.searchLabel.configure( text='Scanning serial ports %d' % port) self.searchLabel.update_idletasks() if checkMsaPresent(port): self.searchLabel.configure( text='MSA connected to port %d' % port) self.searchLabel.update_idletasks() MsaOpen(port) self.msaOpened = True self.port = port self.after(100, self.displayCurrTemp) retrying = False break if self.port == -1: self.searchLabel.configure(text='MSA not connected') retrying = tkmb.askretrycancel( 'Msa test', 'Msa device not found\nCheck serial connection', parent=self) self.searchLabel.update_idletasks()
def set_orientation(self, target): """ Set target page on a device. Prompts the user to connect a device, prompts to retry or cancel on failure. If successful, updates the target page setting on the device. :param target: Target page to set on device :type target: unicode, one of "odd" or "even" """ rv = messagebox.askokcancel( message=("Please connect and turn on the camera for {0} pages". format(target)), title="Configure target page") if not rv: return devs = [] while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) except plugin.DeviceException: devs = [] if not devs: errmsg = "No devices could be found." elif len(devs) > 1: errmsg = "Make sure only one device is turned on!" else: break rv = messagebox.askretrycancel(message=errmsg, title="Error") if not rv: return devs[0].set_target_page(target) messagebox.showinfo(message="Please turn off the device.")
def configure_focus(self): """ Acquire auto-focus value from devices and update the configuration with it. Prompts the user to connect a device, asks for cancel/retry on failure. On successful connection, acquires focus and writes the value to the configuration. """ # TODO: Handle independent focus for both devices rv = messagebox.askokcancel( message="Please connect and turn on one of your cameras.", title="Configure focus") if not rv: return while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) focus = devs[0]._acquire_focus() self.spreads_config['device']['focus_distance'] = focus break except plugin.DeviceException: rv = messagebox.askretrycancel( message="No devices could be found." ) if not rv: break else: continue
def prompt_func(arg_dict): result = tkMessageBox.askretrycancel(parent=self.mygui, title="TweetSubs - Reconnect?", message="The Twitter stream you were following has disconnected.\nWithout it, you will no longer see incoming tweets.\nDo you want to reconnect?", default=tkMessageBox.RETRY, icon=tkMessageBox.ERROR) if (result is True): self.invoke_later(self.ACTION_REFOLLOW, {}) else: logging.info("Re-following declined by user.") self.mygui.invoke_later(self.mygui.ACTION_WARN, {"message":"Re-following declined by user."})
def set_orientation(self, target): """ Set target page on a device. Prompts the user to connect a device, prompts to retry or cancel on failure. If successful, updates the target page setting on the device. :param target: Target page to set on device :type target: unicode, one of "odd" or "even" """ rv = messagebox.askokcancel( message=("Please connect and turn on the camera for {0} pages" .format(target)), title="Configure target page") if not rv: return devs = [] while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) except plugin.DeviceException: devs = [] if not devs: errmsg = "No devices could be found." elif len(devs) > 1: errmsg = "Make sure only one device is turned on!" else: break rv = messagebox.askretrycancel(message=errmsg, title="Error") if not rv: return devs[0].set_target_page(target) messagebox.showinfo(message="Please turn off the device.")
def putChanges(self): """Save changes to the file back to Zope""" f = open(self.body_file, 'rb') body = f.read() f.close() headers = { 'Content-Type': self.metadata.get('content_type', 'text/plain') } if hasattr(self, 'lock_token'): headers['If'] = '<%s> (<%s>)' % (self.path, self.lock_token) response = self.zope_request('PUT', headers, body) del body # Don't keep the body around longer then we need to if response.status / 100 != 2: # Something went wrong sys.stderr.write('Error occurred during HTTP put:\n%d %s\n' \ % (response.status, response.reason)) sys.stderr.write('\n----\n%s\n----' % response.read()) message = response.getheader('Bobo-Exception-Type', '') if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Could not save to Zope.\nError ' 'occurred during HTTP put:\n%d %s\n%s') \ % (response.status, response.reason, message)): has_tk() # ugh, keeps tk happy self.putChanges() else: has_tk() # ugh return 0 return 1
def Ask_retry_or_cancel(self, msg_in_head, msg_in_body): root = guiwindow.Tk() root.withdraw() #this will return true if ans is yes ans = tkMessageBox.askretrycancel(msg_in_head, msg_in_body) root.destroy() return ans
def download(): confirm = tkmb.askyesno('Install NMS DOS', 'Are you sure you want to install NMS DOS Version 4.7.1?') if confirm == True: conf2 = tkmb.askokcancel('Install NMS DOS', 'Click continue to install NMS DOS Version 4.7.1') if conf2 == True: url = 'http://tgt-gaming.weebly.com/uploads/7/5/6/4/75640241/nms_dos_v4.7.1.py' connect = False try: response=urllib2.urlopen('http://example.com',timeout=2) connect = True except urllib2.URLError as err: pass if connect == True: print 'URL is ' + str(url) print "downloading with urllib" urllib.urlretrieve(url, "NMS DOS v4.6.py") time.sleep(4) tkmb.showinfo('Install NMS DOS', 'The install was succesful. \rClick OK to exit.') sys.exit else: conf3 = tkmb.askretrycancel('Install NMS DOS', 'The installation failed. \rError NO_INTERNET_CONNECTION.') if conf3 == True: download() else: tkmb.showerror('Install NMS DOS', 'Click OK to exit.') sys.exit else: tkmb.showerror('Install NMS DOS', 'The installation failed. \rClick OK to exit.') sys.exit else: tkmb.showerror('Install NMS DOS', 'The installation failed. \rClick OK to exit.') sys.exit
def importList(self): print "Importing palette from a Python list." done = False newlist = [] while not done: try: newlist = tkSimpleDialog.askstring("Import Python List", "Enter a Python list of (R,G,B) tuples.") if newlist == None: return newlist = eval(newlist) print "Checking if input is a list...", if type(newlist) != type([]): raise IOError("Invalid list") print "okay.\nChecking contents of list...", for l in newlist: if ( type(l) != type(()) or len(l) != 3 or (not l[0] in range(0, 256)) or (not l[1] in range(0, 256)) or (not l[2] in range(0, 256)) ): raise IOError("Invalid list") print "okay." except: print "failed." if not tkMessageBox.askretrycancel("Import Failed", "Invalid python list was entered."): return else: if not self.newPalette(): return self.populatePalette(newlist) done = True print "Import complete."
def save_data(): try: file_deliveries = open("deliveries.txt", "a") file_deliveries.write("Despot: \n") file_deliveries.write("%s\n" % depot.get()) file_deliveries.write("Description \n") file_deliveries.write("%s \n" % description.get()) file_deliveries.write("Address: \n") file_deliveries.write("%s \n" % address.get("1.0", 'end')) # clear up before data depot.set(None) description.delete(0, 'end') address.delete('1.0', 'end') except Exception, e: tkMessageBox.askretrycancel("Error!", "Can't write to the file \n %s" % e)
def send_data(*args): global callsign global last_data_sentence global logger write_log(logging.INFO, "Sending data... ") try: resp = "" while "OK" not in resp: url = 'http://habitat.habhub.org/transition/payload_telemetry' params = "callsign=" + callsign.get( ) + "&string=%24%24" + last_data_sentence + "\n&string_type=ascii&metadata={}" f = urllib.urlopen(url, params) resp = f.read() logger.info("Response: " + resp) time.sleep(0.5) write_log(logging.INFO, "Sent Data!") except: write_log(logging.ERROR, "Error sending data") if tkMessageBox.askretrycancel(title=CONNECTION_ERROR[0], message=CONNECTION_ERROR[1]): send_data() else: online = False
def get_serial_data(*args): global app global data_textbox global last_data_sentence global logger global ser data = "" if ser.is_open: try: data = ser.readline(ser.inWaiting()) except: logger.error("Error while attempting to read serial port data") if not tkMessageBox.askretrycancel( title=SERIAL_PORT_READ_ERROR[0], message=SERIAL_PORT_READ_ERROR[1], icon="error"): close_serial() if data: last_data_sentence = data parse_data() # Send data to HabHub tracker (if online and data is valid) if online.get() and len(re.split( ',|\*', data.split(";")[0])) == len(parsed_data): send_data(data.split(";")[0]) # For some reason, pySerial needs an entire second to figure out if there is new data in the buffer... # Very annoying and time consuming... app.after(1000, get_serial_data)
def configure_focus(self): """ Acquire auto-focus value from devices and update the configuration with it. Prompts the user to connect a device, asks for cancel/retry on failure. On successful connection, acquires focus and writes the value to the configuration. """ # TODO: Handle independent focus for both devices rv = messagebox.askokcancel( message="Please connect and turn on one of your cameras.", title="Configure focus") if not rv: return while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) focus = devs[0]._acquire_focus() self.spreads_config['device']['focus_distance'] = focus break except plugin.DeviceException: rv = messagebox.askretrycancel( message="No devices could be found.") if not rv: break else: continue
def unlock(self): """Remove webdav lock from edited zope object""" if not hasattr(self, 'lock_token'): return 0 headers = {'Lock-Token': self.lock_token} response = self.zope_request('UNLOCK', headers) if response.status / 100 != 2: # Captain, she's still locked! message = response.getheader('Bobo-Exception-Type', '') sys.stderr.write('Error occurred during lock request:\n%d %s\n%s' \ % (response.status, response.reason, message)) sys.stderr.write('\n----\n%s\n----' % response.read()) if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Unlock request failed:\n%d %s') \ % (response.status, response.reason)): has_tk() # ugh, keeps tk happy return self.unlock(token) else: has_tk() # ugh return 0 return 1
def MessageBox_type(title='你没给标题呀!!', message='你没给文本啊!!!!', showtype='info',**options): if showtype=='info': tkmbox.showinfo(title, message,**options) elif showtype=='waring': tkmbox.showwarning(title, message,**options) elif showtype=='error': tkmbox.showerror(title, message,**options) elif showtype=='question': tkmbox.askquestion(title, message,**options) elif showtype=='okcancel': tkmbox.askokcancel(title, message,**options) elif showtype=='yesno': tkmbox.askyesno(title, message,**options) elif showtype=='yesnocancel': tkmbox.askyesnocancel(title, message,**options) elif showtype=='retrycancel': tkmbox.askretrycancel(title, message,**options)
def authentication_err_handler(self): if tkMessageBox.askretrycancel( "Error", "Something is wrong with your user name or password"): self.auth_window.focus_set() self.username_entry.focus_set() else: self.cancel_authentication()
def update(): current_sha = repo.head.object.hexsha retry = True while retry: try: from maskgen.maskgen_loader import MaskGenLoader default_branch = MaskGenLoader().get_key("git.branch", "master") except ImportError: default_branch = "master" b = tkSimpleDialog.askstring("Select Branch", "Enter the branch of maskgen you want to use. Note: this is " "case sensitive.", initialvalue=default_branch) try: repo.remotes.origin.fetch(b) print("{0:.<64s}".format("Updating maskgen from " + b)), repo.git.reset("--hard") repo.git.checkout(b) repo.git.pull() try: remote_sha = repo.heads.__getattr__(b).object.hexsha except AttributeError: remote_sha = None if current_sha == remote_sha: # SHA before checkout and pull equals latest print("skipped") return b, True elif repo.head.object.hexsha == remote_sha: # SHA after checkout and pull equals latest print("success") return b, False else: print("failed") # SHA after checkout and pull is still not latest return b, False except git.exc.GitCommandError as e: retry = tkMessageBox.askretrycancel("Invalid Branch", "{0} is an invalid branch.".format(b)) except TypeError: # user hit cancel break # this only runs if there is never a valid branch selected try: remote_sha = repo.heads.__getattr__("master").object.hexsha except AttributeError: remote_sha = None print("{0:.<64s}".format("Updating maskgen from master")), repo.remotes.origin.fetch("master") repo.git.reset("--hard") repo.git.checkout("master") repo.git.pull() if current_sha == remote_sha: # SHA before checkout and pull equals latest print("skipped") return "master", True elif repo.head.object.hexsha == remote_sha: # SHA after checkout and pull equals latest print("success") return "master", False else: print("failed") # SHA after checkout and pull is still not latest return "master", False
def _authorize(self): """Authorize the user, allowing them to do other functions""" firmware, name = initialize_nfc_reader() if not firmware and not name: messagebox.showerror("Unable to Authorize", "The PN532 was unable to initialize") retry = 3 while retry: uid = get_uid_noblock() if not uid: # True/False are 1/0, so it works again = messagebox.askretrycancel("No UID found", ("Could not find NFC tag." "Try again?")) if again: retry -= 1 else: return else: retry = 0 if uid: verified = verify_uid(uid) if not verified: messagebox.showerror("Not Authorized", ("You do not have authorization to " "use this device.")) try: username = get_user_uid(uid) realname = get_user_realname() except BaseException as ex: messagebox.showerror("Error:", ex) current_user = is_current_user(username) if not current_user: messagebox.showerror("Incorrect user", ("The provided NFC tag is not for the " "current user.")) if current_user and uid and verified: try: board_setup = gpio_setup() except BaseException as ex: messagebox.showerror("GPIO Error:", ex) if board_setup: _ = disable_relay(OUT_PINS['laser']) _ = disable_relay(OUT_PINS['psu']) else: messagebox.showerror("Failed", "Board not setup") return # Let the buttons actually do something! self._activate_buttons() self._relay_states() logger.info("user %s authorized", username) self.var["status"].set("Authorized, not connected") messagebox.showinfo("Done", "Everything is setup, {}".format(realname)) else: messagebox.showerror("Error", "Something went wrong")
def name_entered(self, client_name): if self.validate_clientname(client_name): self._client_name = client_name self.quit() else: should_retry = tkMessageBox.askretrycancel(title="invalid name", message="The name you enterd is not valid.") if not should_retry: self._client_name = None self.quit()
def _on_send(self): try: send(self.mail, server=self.server) except Exception, e: title = 'Send failed' message = 'The email could not be sent using %s.' % self.server message += ' This was the error:\n' message += str(e) if tkMessageBox.askretrycancel(title, message): self.after(1, self._on_send) return
def _on_send(self): try: send(self.mail, server = self.server) except Exception, e: title = 'Send failed' message = 'The email could not be sent using %s.' % self.server message += ' This was the error:\n' message += str(e) if tkMessageBox.askretrycancel(title, message): self.after(1, self._on_send) return
def name_entered(self, client_name): if self.validate_clientname(client_name): self._client_name = client_name self.quit() else: should_retry = tkMessageBox.askretrycancel( title="invalid name", message="The name you enterd is not valid.") if not should_retry: self._client_name = None self.quit()
def hello(): tkMessageBox.showinfo("PowenKo.com", "showinfo") tkMessageBox.showwarning("PowenKo.com", "showwarning") tkMessageBox.showerror("PowenKo.com", "showerror") result = tkMessageBox.askquestion("PowenKo.com", "askquestion") print(result) result = tkMessageBox.askokcancel("PowenKo.com", "askokcancel") print(result) result = tkMessageBox.askyesno("PowenKo.com", "showeraskyesnoror") print(result) result = tkMessageBox.askretrycancel("PowenKo.com", "askretrycancel") print(result)
def showMsg(str): print str if str == str1[0]: messagebox.showinfo("showinfo", "信息提示框!") elif str == str1[1]: messagebox.showwarning("showwarning", "警告框!") elif str == str1[2]: messagebox.showerror("showerror", "错误信息框!") elif str == str1[3]: if messagebox.askquestion("askquestion", "askquestion提示框") == messagebox.YES: messagebox.showinfo("yes", "你点了yes!") else: messagebox.showinfo("no", "你点了no") elif str == str1[4]: if messagebox.askokcancel("askokcancel", "askokcancel提示框"): messagebox.showinfo("OK", "你点Ok") else: messagebox.showwarning("cancel", "你点了cancel") elif str == str1[5]: print messagebox.askyesno("askyesno", "askyesno提示框") elif str == str1[6]: print messagebox.askretrycancel("askretrycancel", "askretrycancel提示框")
def submit(): var = mvar.get() if var == picflag[1]: tkMessageBox.showinfo("Event Triggered", "Congratulations") mvar.set('') msg() else: tkMessageBox.showinfo("Sorry", "Worng Guess") mvar.set('') num = Var1.get() if num == 3: hang2(B1) Var1.set(num - 1) elif num == 2: hang2(B2) Var1.set(num - 1) elif num == 1: hang2(B3) Var1.set(num - 1) if num == 1: tkMessageBox.askretrycancel("Game Over", "Game Over") Var1.set(3) hang2(B4)
def directorychooser(): global count global index #count=0 directory = askdirectory() if(directory): count=0 index=0 #listbox.delete(0, END) del listofsongs[:] del realnames[:] os.chdir(directory) for files in os.listdir(directory): try: if files.endswith(".mp3"): realdir = os.path.realpath(files) audio = ID3(realdir) realnames.append(audio['TIT2'].text[0]) listofsongs.append(files) except: print(files+" is not a song") if listofsongs == [] : okay=tkMessageBox.askretrycancel("No songs found","no songs") if(okay==True): directorychooser() else: listbox.delete(0, END) realnames.reverse() for items in realnames: listbox.insert(0, items) for i in listofsongs: count = count + 1 pygame.mixer.init() pygame.mixer.music.load(listofsongs[0]) pygame.mixer.music.play() try: updatelabel() except NameError: print("") else: return 1
def choose_book(self): start = daggerfall.cdpath or "." filename = tkFileDialog.askopenfilename(parent=self.root, initialdir=start, filetypes=[ ("Daggerfall Book", "*.TXT") ], title="Select a book file (.TXT)") if filename == "": return try: self.set_book(filename) except: again = tkMessageBox.askretrycancel(title="Invalid", message="This doesn't seem to be a valid book.") if again: return self.choose_book()
def lock(self): """Apply a webdav lock to the object in Zope""" headers = {'Content-Type':'text/xml; charset="utf-8"', 'Timeout':'infinite', 'Depth':'infinity', } body = ('<?xml version="1.0" encoding="utf-8"?>\n' '<d:lockinfo xmlns:d="DAV:">\n' ' <d:lockscope><d:exclusive/></d:lockscope>\n' ' <d:locktype><d:write/></d:locktype>\n' ' <d:depth>infinity</d:depth>\n' ' <d:owner>\n' ' <d:href>Zope External Editor</d:href>\n' ' </d:owner>\n' '</d:lockinfo>' ) response = self.zope_request('LOCK', headers, body) if response.status / 100 == 2: # We got our lock, extract the lock token and return it reply = response.read() token_start = reply.find('>opaquelocktoken:') token_end = reply.find('<', token_start) if token_start > 0 and token_end > 0: self.lock_token = reply[token_start+1:token_end] else: # We can't lock her sir! if response.status == 423: message = '\n(Object already locked)' else: message = response.getheader('Bobo-Exception-Type','') sys.stderr.write('Error occurred during lock request:\n%d %s\n' \ % (response.status, response.reason)) sys.stderr.write('\n----\n%s\n----' % response.read()) if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Lock request failed:\n%d %s\n%s') \ % (response.status, response.reason, message)): has_tk() # ugh, keeps tk happy return self.lock() else: has_tk() # ugh return 0 return 1
def lock(self): """Apply a webdav lock to the object in Zope""" headers = { 'Content-Type': 'text/xml; charset="utf-8"', 'Timeout': 'infinite', 'Depth': 'infinity', } body = ('<?xml version="1.0" encoding="utf-8"?>\n' '<d:lockinfo xmlns:d="DAV:">\n' ' <d:lockscope><d:exclusive/></d:lockscope>\n' ' <d:locktype><d:write/></d:locktype>\n' ' <d:depth>infinity</d:depth>\n' ' <d:owner>\n' ' <d:href>Zope External Editor</d:href>\n' ' </d:owner>\n' '</d:lockinfo>') response = self.zope_request('LOCK', headers, body) if response.status / 100 == 2: # We got our lock, extract the lock token and return it reply = response.read() token_start = reply.find('>opaquelocktoken:') token_end = reply.find('<', token_start) if token_start > 0 and token_end > 0: self.lock_token = reply[token_start + 1:token_end] else: # We can't lock her sir! if response.status == 423: message = '\n(Object already locked)' else: message = response.getheader('Bobo-Exception-Type', '') sys.stderr.write('Error occurred during lock request:\n%d %s\n' \ % (response.status, response.reason)) sys.stderr.write('\n----\n%s\n----' % response.read()) if has_tk(): from tkMessageBox import askretrycancel if askretrycancel('Zope External Editor', ('Lock request failed:\n%d %s\n%s') \ % (response.status, response.reason, message)): has_tk() # ugh, keeps tk happy return self.lock() else: has_tk() # ugh return 0 return 1
def show_retry_cancel_dialog(master, dialog_title, dialog_message, default_button=None): ''' Show an info message dialog. "master": The tk instance that owns the dialog. "dialog_title": Title of the dialog. "dialog_message": Message to display in dialog. "default_button": Default button to be selected when dialog appears. ''' return tkMessageBox.askretrycancel(dialog_title, dialog_message, parent=master, default=default_button)
def choose_book(self): start = daggerfall.cdpath or "." filename = tkFileDialog.askopenfilename( parent=self.root, initialdir=start, filetypes=[("Daggerfall Book", "*.TXT")], title="Select a book file (.TXT)") if filename == "": return try: self.set_book(filename) except: again = tkMessageBox.askretrycancel( title="Invalid", message="This doesn't seem to be a valid book.") if again: return self.choose_book()
def zero_balance(self): retry = True while(retry == True): self.refresh() # Checking if the balance is connected temp_array = self.hardwareIO.check_sensors(self.store) # If it's NOT connected, notify the user if(temp_array[5] == 0): self.zero_window = askretrycancel("Balance Not Connected", "Please make sure the balance is plugged in and powered on,\nthen select 'retry'.") retry = self.zero_window # If it IS connected, proceed with the zeroing prompt else: self.zero_window = askokcancel("Zero Balance", "Please remove the sample before selecting 'OK'.\nIf you don't want to zero the balance, press 'cancel'.") if (self.zero_window == True): self.hardwareIO.balance.zero_balance() retry = False;
def exportImage(self): print "Exporting current palette to an image." done = False while not done: try: tbs = tkFileDialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG", "*.png")]) if tbs == None or tbs == "": return print "Exporting palette image...", paletteOps.drawPalette(tbs, self.palette.values(), self.swatchSize, self.xswatches, self.yswatches) except: print "failed." if not tkMessageBox.askretrycancel("Export Failed", "Error writing image file."): return else: print "done." self.changed = False done = True
def get_maskgen_dir(): def ask_dir(): select_message = "If you have already downloaded maskgen, select the root maskgen folder. If you have not " \ "already downloaded maskgen, select the directory you would like to install maskgen to.\n" \ "Note: A maskgen folder will automatically be created in your selected directory if maskgen " \ "has not been downloaded." if sys.platform.startswith("darwin"): tkMessageBox.showinfo("Select Directory", select_message) mdir = tkFileDialog.askdirectory(title=select_message, initialdir=os.path.join(os.path.expanduser("~"), "Documents")) return mdir try: import maskgen # returns location/maskgen/maskgen/__init__.py # we want just location d = os.path.split(os.path.dirname(maskgen.__file__))[0] return True, d except (ImportError, DistributionNotFound): d = check_frequents() if d is not None: return True, d else: retry = True while retry: d = ask_dir() if os.path.isdir(d): if os.path.isdir(os.path.join(d, "maskgen")) and not \ os.path.isdir(os.path.join(d, "maskgen", "maskgen")): return True, d elif os.path.isdir(os.path.join(d, "maskgen", "maskgen")): return True, os.path.join(d, "maskgen") else: if os.path.split(d)[1] == "maskgen": return d else: return False, os.path.join(d, "maskgen") retry = tkMessageBox.askretrycancel("Invalid Directory", "{0} is an invalid directory.".format(d)) # This only hits if the user gives up m = "Fatal Error: Failed to select a valid maskgen installation target directory." print(m) write_log(m) exit(1)
def displayMsgBox(boxtype="showinfo", title="PptxExplorer", content=None): import tkMessageBox global ToolDescription if content is None: content = ToolDescription if boxtype is "showinfo": return tkMessageBox.showinfo(title, content) elif boxtype is "showwarning": return tkMessageBox.showwarning(title, content) elif boxtype is "showerror": return tkMessageBox.showerror(title, content) elif boxtype is "askquestion": return tkMessageBox.askquestion(title, content) elif boxtype is "askokcancel": return tkMessageBox.askokcancel(title, content) elif boxtype is "askretrycancel": return tkMessageBox.askretrycancel(title, content) else: return "error"
def configure_focus(self): rv = messagebox.askokcancel( message="Please connect and turn on one of your cameras.", title="Configure focus") if not rv: return while True: try: devs = plugin.get_devices(self.spreads_config, force_reload=True) focus = devs[0]._acquire_focus() self.spreads_config['device']['focus_distance'] = focus except plugin.DeviceException: rv = messagebox.askretrycancel( message="No devices could be found." ) if not rv: break else: continue
def set_config(self, key, value): # input: a key and the desired value for that key, both of type string # output: returns nothing, modifies the config file # desc: reads in the current config file as a dict, asigns the requested value to the given key, # wipes the file, and reinserts the updated dict # notes: # make a new file if it doesn't exist if not isdir(self.configFolder): makedirs(self.configFolder) if not isfile(self.configFolder + self.configFile): f = open(self.configFolder + self.configFile, 'w') f.close() retry = True while(retry == True): try: f = open(self.configFolder + self.configFile, 'r+') # create the searchable dictionary dictionary = {} for line in f: if len(line.strip("\n")) != 0: x = line.split(": ") a = x[0] b = x[1] dictionary[a] = b # set the desired dictionary key/value pair dictionary[key] = value + "\n" # wipe the file f.seek(0) f.truncate() # re-store the dictionary for key in sorted(dictionary.keys(), reverse=False): f.write(key + ": " + dictionary[key]) f.close() retry = False return except Exception as e: retry = askretrycancel("Critical Error", "%s\nPlease close the config file and press 'ok'. In the future use a \ntext editor that doesn't lock the file (i.e. don't use Word)" %str(e)) if (retry == False): quit()
def portScan(self): ports = enumPorts() retrying = True while retrying: for port in ports: self.searchLabel.configure(text='Scanning serial ports %d' % port) self.searchLabel.update_idletasks() if checkMsaPresent(port): self.searchLabel.configure(text='MSA connected to port %d' % port) self.searchLabel.update_idletasks() MsaOpen(port); self.msaOpened = True self.port = port self.after(100,self.displayCurrTemp) retrying = False break if self.port == -1: self.searchLabel.configure(text='MSA not connected') retrying = tkmb.askretrycancel('Msa test','Msa device not found\nCheck serial connection',parent=self) self.searchLabel.update_idletasks()
def exportFile(self): print "Exporting current palette to a file." done = False while not done: try: tbs = tkFileDialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text File", "*.txt")]) if tbs == None or tbs == "": return print "Exporting palette file...", f = open(tbs, "w") for p in self.palette.values(): f.write("#%02x%02x%02x\n" % p) f.close() except: print "failed." if not tkMessageBox.askretrycancel("Export Failed", "Error writing image file."): return else: print "done." self.changed = False done = True
def importImage(self): colors = [] done = False while not done: try: tbo = tkFileDialog.askopenfilename( filetypes=[("Images", "*.png"), ("Images", "*.jpg"), ("Images", "*.gif")] ) if tbo == "": return colors = paletteOps.getColors(tbo) except: print "Failed." if not tkMessageBox.askretrycancel("Import Failed", "Error reading image file."): return else: if not self.newPalette(): return self.populatePalette(colors) done = True print "Import complete."
def importFile(self): print "Importing palette from a text file." colors = [] done = False while not done: try: tbo = tkFileDialog.askopenfilename(filetypes=[("Text", "*.txt")]) if tbo == "": return f = open(tbo, "r") for c in f.readlines(): colors.append((int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16))) except: print "Failed." if not tkMessageBox.askretrycancel("Import Failed", "Error reading image file."): return else: if not self.newPalette(): return self.populatePalette(colors) done = True print "Import complete."
def askRetryCancel(message): if has_tk(): from tkMessageBox import askretrycancel r = askretrycancel(title, message) has_tk() # ugh, keeps tk happy return r
def pop_up_msg(issue, message): if tkMessageBox.askretrycancel(issue, message, parent=root): print("RESET") reset() else: GUI.close()
def retrycancel(): tkMessageBox.askretrycancel("Retry", "Load Failed")
def retrycancel(self, title, message): if self.visual: return tkMessageBox.askretrycancel(title, message) else: return self.drawConsoleDialog("Retry/Cancel",title, message, buttons={'retry':True, 'cancel': False})