python类showerror()的实例源码

Chapter3-3-ttk.py 文件源码 项目:Tkinter-By-Example 作者: Dvlv 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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")
Chapter3-3.py 文件源码 项目:Tkinter-By-Example 作者: Dvlv 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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")
Chapter3-2.py 文件源码 项目:Tkinter-By-Example 作者: Dvlv 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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")
merac-o-matic-gui.py 文件源码 项目:merac-o-matic 作者: RogueAI42 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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))
start_window.py 文件源码 项目:Quiver 作者: DeflatedPickle 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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'.")
IOBinding.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
configSectionNameDialog.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
FileList.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
Chapter7-3.py 文件源码 项目:Tkinter-By-Example 作者: Dvlv 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
Chapter5-3.py 文件源码 项目:Tkinter-By-Example 作者: Dvlv 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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")
main.py 文件源码 项目:wg-gesucht-crawler 作者: grantwilliams 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
main.py 文件源码 项目:MiniProjectHU 作者: MatthiasKrijgsman 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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")
test_tkinter.py 文件源码 项目:Mac-Python-3.X 作者: L1nwatch 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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?")
oxo_gui_game.py 文件源码 项目:Mac-Python-3.X 作者: L1nwatch 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
oxo_gui_complete.py 文件源码 项目:Mac-Python-3.X 作者: L1nwatch 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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"
configSectionNameDialog.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
FileList.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
register_form.py 文件源码 项目:network-pj-chatroom 作者: KevinWang15 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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])
frame_run_server.py 文件源码 项目:drc-sim 作者: rolandoislas 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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()
terminal.py 文件源码 项目:porcupine 作者: Akuli 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
logreader.py 文件源码 项目:PyEveLiveDPS 作者: ArtificialQualia 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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()
gui.py 文件源码 项目:Weather 作者: dev4love 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
configSectionNameDialog.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
configHelpSourceEdit.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
FileList.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号