我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用tkinter.messagebox.showerror()。
def translate(self, text=None): if len(self.language_tabs) < 1: msg.showerror("No Languages", "No languages added. Please add some from the menu") return if not text: text = self.english_entry.get(1.0, tk.END).strip() url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: for language in self.language_tabs: full_url = url.format("en", language.lang_code, text) r = requests.get(full_url) r.raise_for_status() translation = r.json()[0][0][0] language.translation_var.set(translation) except Exception as e: msg.showerror("Translation Failed", str(e)) else: msg.showinfo("Translations Successful", "Text successfully translated")
def translate(self, target_languages=None, text=None, elements=None): if not text: text = self.english_entry.get(1.0, tk.END).strip() if not elements: elements = [self.italian_translation] if not target_languages: target_languages = ["it"] url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}" try: for code, element in zip(target_languages, elements): full_url = url.format("en", code, text) r = requests.get(full_url) r.raise_for_status() translation = r.json()[0][0][0] element.set(translation) except Exception as e: msg.showerror("Translation Failed", str(e)) else: msg.showinfo("Translations Successful", "Text successfully translated")
def generate(): global sound statement = coremeraco.constructRegularStatement() + os.linesep textArea.insert(Tkinter.END, statement) textArea.yview(Tkinter.END) if readOption and readOutputState.get(): if sound: sound.stop() sound = playsnd.playsnd() threading.Thread(target=sound.play, args=(procfest.text2wave(statement),)).start() if saveOutputState.get(): try: outputFileHandler = open(saveOutputDestination.get(), 'a') # 'a' means append mode outputFileHandler.write(statement) outputFileHandler.close() except IOError as Argument: tkMessageBox.showerror(productName, meracolocale.getLocalisedString(localisationFile, "ioErrorMessage") + str(Argument)) except Exception as Argument: tkMessageBox.showerror(productName, meracolocale.getLocalisedString(localisationFile, "genericErrorMessage") + str(Argument))
def install_zip(self): pack = filedialog.askopenfile("r") found_pack = False if pack: with zipfile.ZipFile(pack.name, "r") as z: for file in z.namelist(): if file == "pack.mcmeta": # messagebox.showinfo("Information", "Found 'pack.mcmeta'.") found_pack = True pack.close() if found_pack: try: shutil.move(pack.name, self.resourcepack_location) except shutil.Error: messagebox.showerror("Error", "This pack is already installed.") else: messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def writefile(self, filename): self.fixlastline() text = self.text.get("1.0", "end-1c") if self.eol_convention != "\n": text = text.replace("\n", self.eol_convention) chars = self.encode(text) try: f = open(filename, "wb") f.write(chars) f.flush() f.close() return True except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False
def NameOk(self): #simple validity check for a sensible #ConfigParser file section name nameOk=1 name=self.name.get() name.strip() if not name: #no name specified tkMessageBox.showerror(title='Name Error', message='No name specified.', parent=self) nameOk=0 elif len(name)>30: #name too long tkMessageBox.showerror(title='Name Error', message='Name too long. It should be no more than '+ '30 characters.', parent=self) nameOk=0 elif name in self.usedNames: tkMessageBox.showerror(title='Name Error', message='This name is already in use.', parent=self) nameOk=0 return nameOk
def MenuOk(self): "Simple validity check for a sensible menu item name" menuOk = True menu = self.menu.get() menu.strip() if not menu: tkMessageBox.showerror(title='Menu Item Error', message='No menu item specified', parent=self) self.entryMenu.focus_set() menuOk = False elif len(menu) > 30: tkMessageBox.showerror(title='Menu Item Error', message='Menu item too long:' '\nLimit 30 characters.', parent=self) self.entryMenu.focus_set() menuOk = False return menuOk
def PathOk(self): "Simple validity check for menu file path" pathOk = True path = self.path.get() path.strip() if not path: #no path specified tkMessageBox.showerror(title='File Path Error', message='No help file path specified.', parent=self) self.entryPath.focus_set() pathOk = False elif path.startswith(('www.', 'http')): pass else: if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): tkMessageBox.showerror(title='File Path Error', message='Help file path does not exist.', parent=self) self.entryPath.focus_set() pathOk = False return pathOk
def open(self, filename, action=None): assert filename filename = self.canonize(filename) if os.path.isdir(filename): # This can happen when bad filename is passed on command line: tkMessageBox.showerror( "File Error", "%r is a directory." % (filename,), master=self.root) return None key = os.path.normcase(filename) if key in self.dict: edit = self.dict[key] edit.top.wakeup() return edit if action: # Don't create window, perform 'action', e.g. open in same window return action(filename) else: edit = self.EditorWindow(self, filename, key) if edit.good_load: return edit else: edit._close() return None
def start(self): if not self.task_name_entry.get(): msg.showerror("No Task", "Please enter a task name") return if self.task_is_duplicate(): msg.showerror("Task Duplicate", "Please enter a different task name") return if not hasattr(self, "worker"): self.setup_worker() self.task_name_entry.configure(state="disabled") self.start_button.configure(text="Finish", command=self.finish_early) self.time_remaining_var.set("25:00") self.pause_button.configure(state="normal") self.add_new_task() self.task_finished_early = False self.worker.start()
def file_save(self, event=None): if not self.active_ini: msg.showerror("No File Open", "Please open an ini file first") return for section in self.active_ini: for key in self.active_ini[section]: try: self.active_ini[section][key] = self.ini_elements[section][key].get() except KeyError: # wasn't changed, no need to save it pass with open(self.active_ini_filename, "w") as ini_file: self.active_ini.write(ini_file) msg.showinfo("Saved", "File Saved Successfully")
def process_log_output_queue(self): try: message = self.log_output_queue.get(0) if message == "timed out running": self.stop() messagebox.showerror("Timed Out!", "WG-Gesucht website is not responding and has timed out, please try " "again later", parent=self.parent) elif message == "no connection running": self.stop() messagebox.showerror("No Connection!", "Could not connect to the internet, please check your " "connection and try again", parent=self.parent) elif isinstance(message, list): self.log_text.configure(state=tk.NORMAL) self.log_text.insert(tk.END, message[1] + '\n') self.log_text.configure(state=tk.DISABLED) self.log_text.see(tk.END) self.stop() else: self.log_text.configure(state=tk.NORMAL) self.log_text.insert(tk.END, message + '\n') self.log_text.configure(state=tk.DISABLED) self.log_text.see(tk.END) self.parent.after(100, self.process_log_output_queue) except queue.Empty: self.parent.after(100, self.process_log_output_queue)
def exportNetwork(self): export = {} export['apiConnectionData'] = self.apiConnection.data export['pool'] = [] for x in range(len(self.pool.pool)): export['pool'].append({'gene': self.pool.pool[x].gene, 'fitness': self.pool.pool[x].fitness}) export['currentGeneration'] = self.pool.currentGeneration export['averageFitness'] = self.pool.averageFitness export['bestDNAgene'] = self.pool.bestDNA.gene export['bestDNAfitness'] = self.pool.bestDNA.fitness try: filen = filedialog.asksaveasfile().name f = open(filen, 'w') f.write(json.dumps(export)) f.close() except: messagebox.showerror("Error", "Something went wrong")
def main(): # ?????????,?????Tkinter????????Tk??.??????withdraw()?????? tk = tkinter.Tk() tk.withdraw() # ????? print(dir(mb)) # ??,?????????,??ok,????????????.??????????????,??????????. # ??,???Cancel?,??????None mb.showinfo("Title", "Your message here") mb.showerror("An Error", "Oops!") mb.showwarning("Title", "This may not work...") mb.askyesno("Title", "Do you love me?") mb.askokcancel("Title", "Are you well?") mb.askquestion("Title", "How are you?") mb.askretrycancel("Title", "Go again?") mb.askyesnocancel("Title", "Are you well?")
def ev_click(row, col): global game_over if game_over: mb.showerror("Game over", "Game over!") return game = cells2game() index = (3 * row) + col result = oxo_logic.user_move(game, index) game2cells(game) if not result: result = oxo_logic.computer_move(game) game2cells(game) if result == "D": mb.showinfo("Result", "It's a Draw!") game_over = True else: if result == "X" or result == "O": mb.showinfo("Result", "The winner is: {}".format(result)) game_over = True
def ev_click(row, col): global status if status["text"] == "Game Over": mb.showerror("Game over", "Game over!") return game = cells2game() index = (3 * row) + col result = oxo_logic.user_move(game, index) game2cells(game) if not result: result = oxo_logic.computer_move(game) game2cells(game) if result == "D": mb.showinfo("Result", "It's a Draw!") status["text"] = "Game Over" elif result == "X" or result == "O": mb.showinfo("Result", "The winner is: {}".format(result)) status["text"] = "Game Over"
def name_ok(self): ''' After stripping entered name, check that it is a sensible ConfigParser file section name. Return it if it is, '' if not. ''' name = self.name.get().strip() if not name: #no name specified tkMessageBox.showerror(title='Name Error', message='No name specified.', parent=self) elif len(name)>30: #name too long tkMessageBox.showerror(title='Name Error', message='Name too long. It should be no more than '+ '30 characters.', parent=self) name = '' elif name in self.used_names: tkMessageBox.showerror(title='Name Error', message='This name is already in use.', parent=self) name = '' return name
def do_register(self): username = self.username.get() password = self.password.get() password_confirmation = self.password_confirmation.get() nickname = self.nickname.get() if not username: messagebox.showerror("???", "???????") return if not password: messagebox.showerror("???", "??????") return if not nickname: messagebox.showerror("???", "??????") return if password != password_confirmation: messagebox.showerror("???", "?????????") return self.sc.send(MessageType.register, [username, password, nickname])
def stop_server(self, event=None): """ Stops active threads. :param event: Determines if this is a user initiated stop :return: None """ if event: LoggerGui.debug("User clicked stop server button") LoggerGui.debug("Stop server called") if event and (self.label_wpa_status["text"] in (WpaSupplicant.DISCONNECTED, WpaSupplicant.TERMINATED) and self.label_backend_status["text"] == DrcSimC.STOPPED): messagebox.showerror("Stop", "Server is not running.") return if self.drc_sim_c: self.drc_sim_c.stop() self.drc_sim_c = None if self.wpa_supplicant: self.wpa_supplicant.stop() self.wpa_supplicant = None self.activate()
def start_xterm(): tab = tabs.Tab(get_tab_manager()) tab.title = "Terminal" content = tkinter.Frame(tab, container=True) content.pack(fill='both', expand=True) try: process = subprocess.Popen(['xterm', '-into', str(content.winfo_id())]) except FileNotFoundError: messagebox.showerror("xterm not found", ( "Seems like xterm is not installed. " + "Please install it and try again.")) return def close_if_not_closed(junk): if tab in get_tab_manager().tabs: get_tab_manager().close_tab(tab) # the content is destroyed when the terminal wants to exit content.bind('<Destroy>', close_if_not_closed, add=True) # the tab is destroyed when the user wants to close it tab.bind('<Destroy>', lambda event: process.terminate(), add=True) get_tab_manager().add_tab(tab)
def __init__(self, logPath, mainWindow): super().__init__(logPath, mainWindow) self.log = open(logPath, 'r', encoding="utf8") self.log.readline() self.log.readline() characterLine = self.log.readline() character = re.search("(?<=Listener: ).*", characterLine) if character: character = character.group(0) else: raise BadLogException("not character log") self.log.readline() self.log.readline() self.logLine = self.log.readline() if (self.logLine == "------------------------------------------------------------\n"): self.log.readline() collisionCharacter = re.search("(?<=Listener: ).*", self.log.readline()).group(0) messagebox.showerror("Error", "Log file collision on characters:\n\n" + character + " and " + collisionCharacter + "\n\nThis happens when both characters log in at exactly the same second.\n" + "This makes it impossible to know which character owns which log.\n\n" + "Please restart the client of the character you want to track to use this program.\n" + "If you already did, you can ignore this message, or delete this log file:\n" + logPath) raise BadLogException("log file collision") self.log.read()
def _searchCity(self): self.info.delete(u'1.0', tk.END) _cityName = self.cityName.get() if len(_cityName) == 0: messagebox.showwarning(u'Please input a city name', u'Please input a city name for search.') return cities = self.api.queryCityInfo(_cityName) # print(cities) if len(cities) == 0: messagebox.showerror(u'???????', u'??????????????') return elif len(cities) == 1: self._showWeather(cities[0]) else: self._askForSelect(cities)
def load(self): ls = LoadingScreen(self) # ls.lift() self.check_version() Thread(target=self.init_scanner, args=(ls,)).start() self.wait_window(ls) self.focus_set() self.lift() if self.init_error: title, message = self.init_error.args message += '\n{}' messagebox.showerror(title, message.format('Application will now close.'), parent=self) self.on_close() return self.init_warn() self.nb_cfg.onTabChange() self.after(100, self.handle_msgs)
def _load_run_results(self): filename = filedialog.askopenfilename() if not filename: return self.runresultsvar.set(filename) valid_parsers = importer.get_parsers(filename, self.cfg) if not valid_parsers: messagebox.showerror( 'Unknown Format', 'Unable to parse this file. ' 'View log for details.') self.choose_parser['values'] = [''] self.choose_parser.current(0) self.choose_parser.event_generate('<<ComboboxSelected>>') return self.valid_parsers = {p.__name__: p for p in valid_parsers} self.choose_parser['values'] = list(self.valid_parsers.keys()) if len(valid_parsers) > 1: self.choose_parser.config(state='enabled') self.choose_parser.current(0) self.choose_parser.event_generate('<<ComboboxSelected>>')
def _on_parser_changed(self, dummy_event=None): filepath = self.runresultsvar.get() if not filepath: self.runresultsview.clear() self.runresultsview.refresh() return parser_name = self.choose_parser.get() if not parser_name: self.runresultsview.clear() self.runresultsview.refresh() return parser = self.valid_parsers[parser_name] results = [] try: self.results = importer.parse_results(parser, filepath, self.cfg) except importer.ParserError as ex: messagebox.showerror( 'Parser Error', 'An error occurred while parsing. ' 'View log for details.') LOG.exception(ex) self.runresultsview.populate(self.results['tests'])
def login_callback(self, logincfg): """ called by login window """ use_history = self.cfg.getboolean('main', 'history') if use_history: hist = importer.load_history() importer.update_history(hist, logincfg) # pylint try: qcc = qualitycenter.connect(**logincfg) except pythoncom.com_error as ex: messagebox.showerror('Unable to Connect', 'Error Details:\n\n{}'.format(ex)) return False self.qcc = qcc self.qc_domain.set(logincfg['domain']) self.qc_project.set(logincfg['project']) self.qc_conn_status.set(True) self.refresh_qc_directories() return True
def errorBox(self, title, message): self.topLevel.update_idletasks() MessageBox.showerror(title, message) self.__bringToFront()
def send_data(self): # Build the data array num_chans = min(self.ao_props.num_chans, 4) num_points = num_chans ao_range = self.ao_props.available_ranges[0] memhandle = ul.win_buf_alloc(num_points) # Check if the buffer was successfully allocated if not memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: data_array = self.memhandle_as_ctypes_array(memhandle) full_scale_count = (2 ** self.ao_props.resolution) - 1 value_step = full_scale_count / (num_chans + 1) for point_num in range(0, num_points): raw_value = int(value_step * (point_num + 1)) data_array[point_num] = raw_value self.raw_data_labels[point_num]["text"] = str(raw_value) # ul.to_eng_units cannot be used here, as it uses the analog # input resolution. Instead, do the conversion on our own. volts = self.ao_to_eng_units( raw_value, ao_range, self.ao_props.resolution) self.volts_labels[point_num]["text"] = ( '{:.3f}'.format(volts)) ul.a_out_scan( self.board_num, 0, num_chans - 1, num_points, 100, ao_range, memhandle, 0) except ULError as e: self.show_ul_error(e) finally: ul.win_buf_free(memhandle)
def start_scan(self): rate = 100 count = 1000 # Allocate a buffer for the scan self.memhandle = ul.win_buf_alloc(count) # Check if the buffer was successfully allocated if not self.memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.set_ui_idle_state() return try: # Configure the port (if necessary) if self.port.is_port_configurable: ul.d_config_port( self.board_num, self.port.type, DigitalIODirection.IN) # Run the scan ul.d_in_scan( self.board_num, self.port.type, count, rate, self.memhandle, ScanOptions.BACKGROUND) except ULError as e: self.show_ul_error(e) self.set_ui_idle_state() return # Convert the memhandle to a ctypes array # Note: the ctypes array will no longer be valid after win_buf_free is called. # A copy of the buffer can be created using win_buf_to_array # before the memory is freed. The copy can be used at any time. self.ctypes_array = self.memhandle_as_ctypes_array(self.memhandle) # Start updating the displayed values self.update_displayed_values()
def show_ul_error(self, ul_error): message = ( "A UL Error occurred.\n\n Error Code: " + str(ul_error.errorcode) + "\nMessage: " + ul_error.message) messagebox.showerror("Error", message)
def start_scan(self): rate = 390 total_count = 100 # Allocate a buffer for the scan memhandle = ul.win_buf_alloc_32(total_count) # Check if the buffer was successfully allocated if not memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Configure the counter ul.c_config_scan( self.board_num, self.chan_num, CounterMode.DECREMENT_ON, CounterDebounceTime.DEBOUNCE_NONE, 0, CounterEdgeDetection.FALLING_EDGE, CounterTickSize.TICK20PT83ns, 1) # Run the scan ul.c_in_scan( self.board_num, self.chan_num, self.chan_num, total_count, rate, memhandle, 0) # Convert the memhandle to a ctypes array # Note: the ctypes array will only be valid until win_buf_free # is called. # A copy of the buffer can be created using win_buf_to_array_32 # before the memory is freed. The copy can be used at any time. array = self.memhandle_as_ctypes_array_32(memhandle) # Display the values self.display_values(array, total_count) except ULError as e: self.show_ul_error(e) finally: # Free the allocated memory ul.win_buf_free(memhandle) self.start_button["state"] = tk.NORMAL
def _msgBox(): # msg.showinfo('Python Message Info Box', 'A Python GUI created using tkinter:\nThe year is 2017.') # msg.showwarning('Python Message Warning Box', 'A Python GUI created using tkinter:' # '\nWarning: There might be a bug in this code.') msg.showerror('Python Message Error Box', 'A Python GUI created using tkinter:' '\nError: Houston ~ we DO have a serious PROBLEM!') # Add another Menu to the Menu Bar and an item
def open_pack(self): pack = filedialog.askdirectory(initialdir=self.resourcepack_location) if os.path.isfile(pack + "/pack.mcmeta"): # messagebox.showinfo("Information", "Found 'pack.mcmeta'.") self.parent.directory = pack self.parent.cmd.tree_refresh() self.destroy() else: messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def open_zip(self): pack = filedialog.askopenfile("r", initialdir=self.resourcepack_location) found_pack = False if pack: amount = functions.zip_files(pack.name) progress = dialog.ProgressWindow(self.parent, title="Opening Zip", maximum=amount) count = 0 with zipfile.ZipFile(pack.name, "r") as z: for file in z.namelist(): if file == "pack.mcmeta": # messagebox.showinfo("Information", "Found 'pack.mcmeta'.") found_pack = True self.destroy() if found_pack: self.parent.d = tempfile.TemporaryDirectory() for file in z.namelist(): z.extract(file, self.parent.d.name) count += 1 progress.variable_name.set("Current File: " + file) progress.variable_percent.set("{}% Complete".format(round(100 * float(count) / float(amount)))) progress.variable_progress.set(progress.variable_progress.get() + 1) self.parent.name = pack.name.split("/")[-1].split(".")[0] self.parent.directory = self.parent.d.name self.parent.directory_real = pack.name self.parent.cmd.tree_refresh() self.destroy() elif not found_pack: messagebox.showerror("Error", "Could not find 'pack.mcmeta'.") pack.close() progress.destroy()
def install_pack(self): pack = filedialog.askdirectory() if os.path.isfile(pack + "/pack.mcmeta"): # messagebox.showinfo("Information", "Found 'pack.mcmeta'.") try: shutil.move(pack, self.resourcepack_location) except shutil.Error: messagebox.showerror("Error", "This pack is already installed.") else: messagebox.showerror("Error", "Could not find 'pack.mcmeta'.")
def error(self, message): """ Shows error message """ if PY2: import tkMessageBox as messagebox else: from tkinter import messagebox messagebox.showerror('web2py start server', message)
def show_error(self, title, message): return messagebox.showerror(title, message)
def gui_twisstrack(frame, w, h, status, start, stop): def _start(): latt = latticemenu.get() if latt in closedlatts: closed = True elif latt in openlatts: closed = False else: showerror(title='ERROR', message='Please choose a lattice') return slic = int(entry_slice.get()) mode = 'trackbeta' particles = 1 rounds = 1 runthread(status, tabs, lsd, (closed, latt, slic, mode, particles, rounds)) start.configure(command=_start) tabs = cs_tabbar(frame, w, h, ['Menu', 'Radial', 'Axial', 'Dispersion', 'Overview', 'Parameters', 'Beam extents']) cs_label(tabs[0], 1, 1, 'Lattice') cs_label(tabs[0], 1, 2, 'Nr. of slices') closedlatts, openlatts = lattlist() latticemenu = cs_dropd(tabs[0], 2, 1, closedlatts + openlatts) entry_slice = cs_Intentry(tabs[0], 2, 2, 1e3) return
def readConfig(self,layout_file, layout_type="hyperion"): opc_map = {'opc_xy' : (0,1),'opc_xz' : (0,2),'opc_yz' : (1,2) } try: if layout_type == "hyperion": self.readConfig_hyperion(layout_file) elif layout_type in opc_map: self.readConfig_opc(layout_file, opc_map[layout_type][0], opc_map[layout_type][1]) else: print("unknown type of config file") exit(1) except Exception as e: tkMessageBox.showerror("Open Config File", "Failed to open '%s' file \n'%s'\n%s" % (self.layout_type, self.layout_file, e)) # ------------------------------------------------------