Example #1
0
 def on_file_menuitem_clicked(self, itemid):
     if itemid == 'file_new':
         new = True
         if self.is_changed:
             new = openfile = messagebox.askokcancel( _('File changed'),
                 _('Changes not saved. Discard Changes?') )
         if new:
             self.previewer.remove_all()
             self.tree_editor.remove_all()
             self.properties_editor.hide_all()
             self.currentfile = None
             self.is_changed = False
             self.project_name.configure(text=_('<None>'))
     elif  itemid == 'file_open':
         openfile = True
         if self.is_changed:
             openfile = messagebox.askokcancel(_('File changed'),
                 _('Changes not saved. Open new file anyway?'))
         if openfile:
             options = { 'defaultextension': '.ui',
                 'filetypes':((_('pygubu ui'), '*.ui'), (_('All'), '*.*')) }
             fname = filedialog.askopenfilename(**options)
             if fname:
                 self.load_file(fname)
     elif  itemid == 'file_save':
         if self.currentfile:
             if self.is_changed:
                 self.do_save(self.currentfile)
         else:
             self.do_save_as()
     elif  itemid == 'file_saveas':
         self.do_save_as()
     elif  itemid == 'file_quit':
         self.quit()
Example #2
0
def dump(element):
    path_ = path.get()
    if path_ == '':
        return
    file_type = os.path.splitext(path_)[1]
    call = callable_arr.get(file_type)
    try:
        arr = call(path_)
    except Exception as e:
        print(e)
        messagebox.askokcancel('error', '不支持该文件类型')
        return
    if element == 'json':
        content = json.dumps(arr, sort_keys=True)

        with open(os.path.dirname(path_)+r'\target.json', 'w+') as f:
            f.write(content)
            messagebox.askyesno('成功', '转换成功!请查找target文件')
    elif element == 'php':
        php_str = '<?php \n' \
                  'return '
        php_str = php_str + dump_php(arr) + ';'
        with open(os.path.dirname(path_)+r'\target.php', 'wb') as f:
            f.write(php_str.encode())
            messagebox.askyesno('成功', '转换成功!请查找target文件')
Example #3
0
def toggleContestant(contestantClass):
  global socket, voteTopLevel
  disableButton() #disable all button presses
  if contestantClass.uuid in [contestant.uuid for contestant in contestantList]: #if the given contestant class is in the list of contestants (ie if they are in the game) send a message to the server to remove the contestant from the game
    if messagebox.askokcancel("Confirm", "Remove " + contestantClass.name + " from the Game?", parent=voteTopLevel): #confirm the user wants to remove the contetant from the game
      network.sendMessage("removeContestant", contestantClass.uuid, socket)
  else: #if the given contestantClass is not in the game send a message to the server to add the contestant to the game
    if messagebox.askokcancel("Confirm", "Re-add " + contestantClass.name + " to the Game?", parent=voteTopLevel): #confirm the user wants to re-add the contestnt to the game
      network.sendMessage("addContestant", contestantClass.uuid, socket)
Example #4
0
def sort():

    logging.info("=============Sort job go!=================")
    logText.delete(1.0, END)
    logText.insert(END, '================go!====================\n')
    sort_files(srcPath.get())
    logging.info("=============Sort job done!=================\n")
    logText.insert(END, '================done!====================\n')
    logText.see(END)
    messagebox.askokcancel('结果提示', '整理完毕')
Example #5
0
 def removeLine(self,event):
     index = self.listbox.curselection()[0]
     selection = self.listbox.get(index)
     if (index > 0):
         confirmed =  messagebox.askokcancel("Confirm","Remove Run %s?"%selection)
         if confirmed:
             self.listbox.delete(index)
     else:
         confirmed =  messagebox.askokcancel("Halt Run While In Process?","Halt Run %s?"%selection)
         if confirmed:
             self.listbox.delete(index)
             self.abort()
def close_display():
    global signal_complete
    global crawl_flag
    if not signal_complete:

            print('close')
            choice=messagebox.askokcancel(title='Crawler Interrupt',message='This will disconnect current query retrieval, query database will may not be complete! .')
            print(choice)
            if choice:
                global signal
                signal=False
               # global crawl_flag
                if crawl_flag:
                    crawl_topics.signal=False
                top_root.state('withdrawn')
                root.state('normal')
                if not crawl_topics.crawl_complete_flag:
                    messagebox.showinfo(title='Corrupt Database',message='You just interrupted the Dataset creation. We recomend not to use this dataset, this package may not work properly.')
                #crawl_topics.signal=True
                crawl_flag=True
                #signal=True
    else:
        top_root.state('withdrawn')
        root.state('normal')
        messagebox.showinfo(title='Crawling Complete!',message='Crawling is complete, now you may use this dataset to create a new database!')
        signal_complete=False
Example #7
0
 def ask_save_dialog(self):
     msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
     confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
                                        message=msg,
                                        default=tkMessageBox.OK,
                                        parent=self.editwin.text)
     return confirm
def selectDisclosureSystem(parent, disclosureSystem):

    disclosureSystemSelections = disclosureSystem.dir

    # if no disclosure system to select, user may need to enable applicable plugin(s)
    if not disclosureSystemSelections and messagebox.askokcancel(
        _("Load disclosure systems"),
        _(
            "Disclosure systems are provided by plug-ins, no applicable plug-in(s) have been enabled. \n\n"
            "Press OK to open the plug-in manager and select plug-in(s) (e.g., validate or EdgarRenderer)."
        ),
    ):
        from arelle import DialogPluginManager

        DialogPluginManager.dialogPluginManager(parent)
        return None

    dialog = DialogOpenArchive(
        parent,
        DISCLOSURE_SYSTEM,
        disclosureSystem,
        disclosureSystemSelections,
        _("Select Disclosure System"),
        _("Disclosure System"),
    )
    if dialog and dialog.accepted:
        return disclosureSystem.selection
    return None
Example #9
0
    def install_graphics(self, listbox):
        """
        Installs a graphics pack.

        Params:
            listbox
                Listbox containing the list of graphics packs.
        """
        if len(listbox.curselection()) != 0:
            gfx_dir = listbox.get(listbox.curselection()[0])
            if messagebox.askokcancel(
                    message='Your graphics, settings and raws will be changed.',
                    title='Are you sure?'):
                result = self.lnp.install_graphics(gfx_dir)
                if result is False:
                    messagebox.showerror(
                        title='Error occurred', message='Something went wrong: '
                        'the graphics folder may be missing important files. '
                        'Graphics may not be installed correctly.\n'
                        'See the output log for error details.')
                elif result:
                    if messagebox.askyesno(
                            'Update Savegames?',
                            'Graphics and settings installed!\n'
                            'Would you like to update your savegames to '
                            'properly use the new graphics?'):
                        self.update_savegames()
                else:
                    messagebox.showerror(
                        title='Error occurred',
                        message='Nothing was installed.\n'
                        'Folder does not exist or does not have required files '
                        'or folders:\n'+str(gfx_dir))
            binding.update()
Example #10
0
def apply_changes():
    values_changed = any(
        item.package.enabled != item.state
        for item in
        pack_items.values()
    )
    if not values_changed:
        # We don't need to do anything!
        window.withdraw()
        window.grab_release()
        return

    if messagebox.askokcancel(
            title=_('BEE2 - Restart Required!'),
            message=_('Changing enabled packages requires a restart.\nContinue?'),
            master=window,
            ):
        window.withdraw()
        window.grab_release()
        for item in UI['details'].items:
            pack = item.package
            if pack.id != packageLoader.CLEAN_PACKAGE:
                pack.enabled = item.state
        PACK_CONFIG.save_check()
        utils.restart_app()
Example #11
0
def clear_caches():
    """Wipe the cache times in configs.

     This will force package resources to be extracted again.
     """
    import gameMan
    import packageLoader

    restart_ok = messagebox.askokcancel(
        title='Allow Restart?',
        message='Restart the BEE2 to re-extract packages?',
    )

    if not restart_ok:
        return

    for game in gameMan.all_games:
        game.mod_time = 0
        game.save()
    GEN_OPTS['General']['cache_time'] = '0'

    for pack_id in packageLoader.packages:
        packageLoader.PACK_CONFIG[pack_id]['ModTime'] = '0'

    save()  # Save any option changes..

    gameMan.CONFIG.save_check()
    GEN_OPTS.save_check()
    packageLoader.PACK_CONFIG.save_check()

    utils.restart_app()
Example #12
0
 def delete_inst(self):
     setup_from_none()
     instance_name = self.get_selected_instance_name()
     if askokcancel(None, ugettext("Do you want to delete '%s'?") % instance_name):
         self.delete_inst_name(instance_name)
     else:
         self.refresh()
Example #13
0
    def expand(self, event=None):
        """expand event handler

        This inserts the original text in place of the button in the Text
        widget, removes the button and updates the Squeezer instance.

        If the original text is dangerously long, i.e. expanding it could
        cause a performance degradation, ask the user for confirmation.
        """
        if self.is_dangerous is None:
            self.set_is_dangerous()
        if self.is_dangerous:
            confirm = tkMessageBox.askokcancel(
                title="Expand huge output?",
                message="\n\n".join([
                    "The squeezed output is very long: %d lines, %d chars.",
                    "Expanding it could make IDLE slow or unresponsive.",
                    "It is recommended to view or copy the output instead.",
                    "Really expand?"
                ]) % (self.numoflines, len(self.s)),
                default=tkMessageBox.CANCEL,
                parent=self.text)
            if not confirm:
                return "break"

        self.base_text.insert(self.text.index(self), self.s, self.tags)
        self.base_text.delete(self)
        self.squeezer.expandingbuttons.remove(self)
Example #14
0
def on_closing():
	global running
	running = False
	if messagebox.askokcancel("Quit", "Do you want to quit?"):
		root.destroy()
	else:
		running = True
Example #15
0
 def pull_answers(self):
     msg = """This will disconnect all manual answers from the controller
              They will have to be readded in order to select them"""
     if messagebox.askokcancel("Pull Answers?", msg):
         self.answers = get_answers.pull()
         self.root_frame.destroy()
         self.add_root_widgets()
Example #16
0
 def askroot(self):
   dir=filedialog.askdirectory(title="Select Comcraft Source Directory",mustexist=True, initialdir=self.ccdir)
   if dir and os.path.exists(os.path.join(dir,"net\\comcraft\\src")):
     self.config.merge('settings',{'comcraft_root':dir.replace('/','\\')})
   else:
     if messagebox.askokcancel("Not found","Could not locate source, reselect folder?"):
       self.askroot()
Example #17
0
File: main.py Project: DaZhu/pygubu
 def on_edit_menuitem_clicked(self, itemid):
     if itemid == 'edit_item_up':
         self.tree_editor.on_item_move_up(None)
     elif itemid == 'edit_item_down':
         self.tree_editor.on_item_move_down(None)
     elif itemid == 'edit_item_delete':
         do_delete = messagebox.askokcancel(_('Delete items'),
                                            _('Delete selected items?'))
         if do_delete:
             self.tree_editor.on_treeview_delete_selection(None)
     elif itemid == 'edit_copy':
         self.tree_editor.copy_to_clipboard()
     elif itemid == 'edit_paste':
         self.tree_editor.paste_from_clipboard()
     elif itemid == 'edit_cut':
         self.tree_editor.cut_to_clipboard()
     elif itemid == 'grid_up':
         self.tree_editor.on_item_grid_move(WidgetsTreeEditor.GRID_UP)
     elif itemid == 'grid_down':
         self.tree_editor.on_item_grid_move(WidgetsTreeEditor.GRID_DOWN)
     elif itemid == 'grid_left':
         self.tree_editor.on_item_grid_move(WidgetsTreeEditor.GRID_LEFT)
     elif itemid == 'grid_right':
         self.tree_editor.on_item_grid_move(WidgetsTreeEditor.GRID_RIGHT)
     elif itemid == 'edit_preferences':
         self._edit_preferences()
Example #18
0
def uninstall():
    Tk().withdraw()
    if messagebox.askokcancel("No Going Back!", "Uninstalling will remove the program "
                                                "and all files from your computer!"):
        try:
            os.remove(path + "\DiscRead\Temp.txt")
        except FileNotFoundError:
            pass
        try:
            os.remove(path + "\DiscRead\Results.txt")
        except FileNotFoundError:
            pass
        try:
            os.remove(path + "\DiscRead\Info.txt")
        except FileNotFoundError:
            pass
        try:
            shutil.rmtree(path + "\DiscRead")
        except FileNotFoundError:
            pass
        try:
            shutil.move("DiscipleReading.exe", path + "\DiscipleReading.exe")
            sys.exit(0)
        except FileNotFoundError:
            Tk().withdraw()
            messagebox.showerror("Sorry!", "We are still working on finding a solution to uninstallation, but you'll"
                                           "have to delete it manually in the meantime!. Please refer to 'Help'")
Example #19
0
File: tk.py Project: seventh/duo
    def _on_menu_quit_cb(self):
        """Callback invoked to quit the game.

        This method asks for confirmation before the program is really
        stopped."""
        if tk_msg.askokcancel(_("Quit"), _("Do you want to quit this program?")):
            self.leave()
Example #20
0
 def callback(e):
     if askokcancel(
         title='BEE2 - Open URL?',
         message=_('Open "{}" in the default browser?').format(url),
         parent=self,
     ):
         webbrowser.open(url)
    def delProj(self, idProj, nomeProj):
        confirmar = messagebox.askokcancel('Deletar Projeto', 'Tem certeza que deseja deletar o projeto "' + nomeProj + '" ?')
        if confirmar:
            ########  SCRIPT PARA DELETAR O PROJETO  #########
            lerPort = open(self.portfolio, 'r')
            listPort = lerPort.readlines()
            lerPort.close()
            lerPort = open(self.portfolio, 'w')
            for linhasPort in listPort:
                if linhasPort != '\n':
                    dictLinhasPort = ast.literal_eval(linhasPort)
                    if dictLinhasPort['id'] != idProj:
                        lerPort.write(linhasPort)

            ########  SCRIPT PARA DELETAR A AVALIAÇÃO CORRESPONDENTE AO PROJETO  #########
            lerAval = open(self.aval, 'r')
            listAval = lerAval.readlines()
            lerPort.close()
            lerAval = open(self.aval, 'w')
            for linhasAval in listAval:
                if linhasAval != '\n':
                    dictLinhasAval = ast.literal_eval(linhasAval)
                    if dictLinhasAval['id'] != idProj:
                        lerAval.write(linhasAval)
            messagebox.showinfo('Deletar Projeto', 'O projeto "' + nomeProj + '" foi deletado!')
            lerPort.close()
Example #22
0
def timer_event():
    global scores_value, scores_text, number_of_shots, shoots, best_scores, gun

    # проверяем на столкновение снаряда с каждым шариком
    for shell in shells_on_fly:
        for ball in balls:
            # d1 - расстояние между центром снаряда и шарика
            d1 = sqrt((shell._x + shell._R - ball._x - ball._R)**2 + (shell._y + shell._R - ball._y - ball._R)**2)
            d2 = shell._R + ball._R
            if d1 <= d2:
                ball.explode()
                shell.explode()
                scores_value.set(scores_value.get()-1)
    scores_text["textvariable"]=scores_value
    number_of_shots["text"] = 'Выстрелов: '+str(shoots)

    if scores_value.get() == 0:
        scores_value.set(Ball.initial_number)
        if best_scores > shoots:
            best_scores = shoots
        canvas.delete(gun._avatar)
        if messagebox.askokcancel("Итоги игры", 'Потрачено снарядов:'+str(shoots)+'\nЛучший результат:'+str(best_scores)+'\nСыграем ещё?'):
            reset_game()
        else:
            root.destroy()

    for ball in balls:
        ball.fly()
    for shell in shells_on_fly:
        shell.fly()

    canvas.after(timer_delay, timer_event)
    def removeComponent(_id):
        if MyInventory.component_items[_id][0] != None:
            uses_left = int(MyInventory.component_items[_id][1].uses)
            item_name = MyInventory.component_items[_id][1].name
            
            msg = 'Move "' + item_name + '" to your inventory?'
            if uses_left == 0:
                msg = 'WARNING: 0 uses are left for "' + item_name + \
                      '", this item will be deleted.' 
            answer = messagebox.askokcancel("Remove Active Component Item", msg)

            if answer:
                MyInventory.component_effects.pop(MyInventory.component_items[_id][1].item_type, None)
                MyInventory.api.unequip_item(MyInventory.component_items[_id][1])
                MyInventory.component_items[_id][0].destroy()
                MyInventory.component_items[_id][0] = None

                MyInventory.my_inventory.addItem(MyInventory.component_items[_id][1])
                MyInventory.api.set_active(MyInventory.component_items[_id][1], 'False')
 
                # shift all items to the left on the gui if any visual node gaps
                for i in range(_id+1, MyInventory.max_components, 1):
                    if MyInventory.component_items[i][0] != None:
                        MyInventory.resetComponent(MyInventory.component_items[i][1], i)
                        MyInventory.component_items[i][0].destroy()
                        MyInventory.component_items[i][0] = None
                        
                if MyInventory.components_count > 0:
                    MyInventory.components_count -= 1
Example #24
0
def maybe_first_time_setup():
    """
    Set up the user's notes directory/folder the first time they run
    NoteBag.

    Returns False if it failed, or needs to try again; returns True if
    it succeeds, or doesn't need to happen at all.
    """

    if not os.path.isfile(get_config_path(CONFIG_FILENAME)):
        shutil.copy2(get_config_path(TEMPLATE_CONFIG_FILENAME),
                     get_config_path(CONFIG_FILENAME))

    config = read_config(CONFIG_FILENAME)
    if config.get("NoteBag", "Notes Directory"):
       return True

    if not messagebox.askokcancel(
            "NoteBag Setup",
            "Hi! It looks like this is your first time running NoteBag!\n"
            "Please choose the folder where you would like NoteBag to keep your notes."
            ):
        return False

    notes_dir = filedialog.askdirectory(title="Notes Folder")
    print(notes_dir)
    if not notes_dir:
        return False

    config.set("NoteBag", "Notes Directory", notes_dir)
    save_config(config, CONFIG_FILENAME)
    return True
Example #25
0
    def clear(self):
        m = _('Está seguro de que quiere eliminar el diccionario?')
        t = _('Eliminar Diccionario')
        if messagebox.askokcancel(t, m, default='cancel', parent=self):
            self.word_list.clear()

        self.practice()
Example #26
0
 def exitAll(self):
     mExit = messagebox.askokcancel(title="Exit", message="pyBristol will exit now...")
     if mExit > 0:
         self.stopBristol()
         self.bGui.destroy()
         sys.exit()
     return
Example #27
0
def mhello(dst, src):

    name = mdst.get()
    for i in range(len(illegalchars)):
        name = name.replace(illegalchars[i],"_")
    print(name)
    if len(dst) <= 0 or len(name) <=0:
        messagebox.showwarning("YO YOU MADE A MISTAKE $$$", "Your destination folder has to have a path and name!")
    
    elif os.path.exists(dst + "\\" + name):
        e = True
        i = 1
        while e:
            if os.path.exists(dst+ "\\" +name+ str(i)):
                i = i + 1
            else:
                e = False
        if messagebox.askokcancel("Ya dingus!", "That folder already exists! \nRename to " + name + "("+ str(i) +")?"):
            name = name + str(i)
            print(name)
            #e = None
    #else:
        #print("Copying from: "+ src + " To: "+ dst+ "\\" + name)
    dst = dst + "\\" + name
    print(dst)
    try:
        shutil.copytree(src, dst)
        messagebox.showwarning("Alert", "Your backup has completed")
    except:
        messagebox.showwarning("Lazy error message", """Your folder name was invalid idk why lol,
try avoiding \"/ \ * ? : < > | \" ya dingus """)
    return
    def import_csv(self):
        OpenFilename = filedialog.askopenfilename(initialdir='./csv',
                                                  filetypes=[('CSV Datenbank', '.csv'), ('all files', '.*')])

        if len(OpenFilename) == 0:
            return
        try:
            main_auftragkonto_load = sd.get_main_auftragskonto(OpenFilename)
        except Exception as ex1:
            messagebox.showerror('Fehler beim Importieren',
                                 'Importieren ist mit Fehler ' + repr(ex1) + ' fehlgeschlagen')

        if main_auftragkonto_load != self.main_auftragskonto and self.main_auftragskonto is not None:
            if not messagebox.askokcancel('Sicherheitsabfrage',
                                          'Kontonummer des CSVs stimmt nicht mit bestehenden Daten überein. Trotzdem fortfahren?'):
                return
        try:
            info = sd.load_data(OpenFilename)
        except Exception as ex1:
            messagebox.showerror('Fehler beim Importieren',
                                 'Importieren ist mit Fehler ' + repr(ex1) + ' fehlgeschlagen')

        self.EF1.first_plot_bool = True
        q1.put('Update Plot')
        messagebox.showinfo('Import Bericht',
                            'Eine csv Datei mit {Csv size} Einträgen wurde geladen. {#Duplicate} davon waren schon vorhanden und {#Imported} neue Einträge wurden importiert. Die Datenbank enthält nun {New size} Einträge'.format(
                                **info))
Example #29
0
 def confirm_quit(self):
     winsound.PlaySound("SystemQuestion", winsound.SND_ASYNC)
     if messagebox.askokcancel("Quit", "Do you want to quit?"):
         # Prevents an exception if the boaster window has already been closed.
         try:
             self.hist_score_window.destroy_me()
         except:
             pass
         if int(self.user_score.get()) > 0 or int(self.machine_score.get()) > 0:
             empty = False
             historic_score = open("histcore.dat", "rb")
             try:
                 score = pickle.load(historic_score)
             except EOFError:
                 empty = True
             historic_score.close()             
             historic_score = open("histcore.dat", "wb")
             if not empty:
                 pickle.dump([int(self.user_score.get()) + score[0],
                              int(self.machine_score.get()) + score[1]], historic_score)
             else:
                 score = open("histcore.dat", "wb")
                 pickle.dump([int(self.user_score.get()), int(self.machine_score.get())], score)
             historic_score.close()
             
             file_name = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0) +\
                         "\Tic Tac Toe Score " + datetime.datetime.now().strftime\
                 ("%Y-%m-%d_%H.%M.%d") + ".txt"
             score_file = open(file_name, "w")
             score_file.writelines(self.user_name + ": " + self.user_score.get() +
                                   "\nMACHINE: " + self.machine_score.get())
             score_file.close()
             tkinter.messagebox.showinfo("Score", "Current score was saved to your Desktop")
         self.main_window.destroy()
Example #30
0
    def onClosing(self):
        
        if messagebox.askokcancel("Quit", "Do you want to quit?"):
            #self.SyntaxCheckProc.terminate()

            self.Parent.destroy()
            self.Parent.quit()
Example #31
0
def clicked():
    res = messagebox.askokcancel('Message title', 'Message content')
Example #32
0
def main():
    end.show((255, 8, 127), 0)
    start.show((255, 8, 127), 0)
    if len(openSet) > 0:
        lowestIndex = 0
        for i in range(len(openSet)):
            if openSet[i].f < openSet[lowestIndex].f:
                lowestIndex = i

        current = openSet[lowestIndex]
        if current == end:
            print('done', current.f)
            start.show((255, 8, 127), 0)
            temp = current.f
            for i in range(round(current.f)):
                current.closed = False
                current.show((0, 0, 255), 0)
                current = current.previous
            end.show((255, 8, 127), 0)

            Tk().wm_withdraw()
            result = messagebox.askokcancel('Program Finished', (
                'The program finished, the shortest distance \n to the path is '
                + str(temp) +
                ' blocks away, \n would you like to re run the program?'))
            if result == True:
                os.execl(sys.executable, sys.executable, *sys.argv)
            else:
                ag = True
                while ag:
                    ev = pygame.event.get()
                    for event in ev:
                        if event.type == pygame.KEYDOWN:
                            ag = False
                            break
            pygame.quit()

        openSet.pop(lowestIndex)
        closedSet.append(current)

        neighbors = current.neighbors
        for i in range(len(neighbors)):
            neighbor = neighbors[i]
            if neighbor not in closedSet:
                tempG = current.g + current.value
                if neighbor in openSet:
                    if neighbor.g > tempG:
                        neighbor.g = tempG
                else:
                    neighbor.g = tempG
                    openSet.append(neighbor)

            neighbor.h = heurisitic(neighbor, end)
            neighbor.f = neighbor.g + neighbor.h

            if neighbor.previous == None:
                neighbor.previous = current
    if var.get():
        for i in range(len(openSet)):
            openSet[i].show(green, 0)

        for i in range(len(closedSet)):
            if closedSet[i] != start:
                closedSet[i].show(red, 0)
    current.closed = True
Example #33
0
    def assist(self):
        global content  # global case_name

        if self.top_window.winfo_exists():
            messagebox.showinfo(message="please first enter your name!")
        else:
            # if self.suggested_maneuver.cget("text") != "N/A":
            if self.video_lbl:
                self.video_lbl.place_forget(
                )  # if the video was playing in the previous assist just remove it.
            elif self.suggeste_img_lbl:
                self.suggeste_img_lbl.place_forget(
                )  # if the picture was shown in the previous assist just remove it.

            # Removing the suggested solution attributes at getting  each assistance!
            if self.log_objects:
                self.suggested_speed.config(text="")
                self.suggested_distance_target.config(text="")
                self.suggested_heading.config(text="")
                self.suggested_area_focus.config(text="")
                self.suggested_aspect.config(text="")
                self.suggested_maneuver.config(text="")
                self.suggested_orientation.config(text="")

            # Resetting output image
            # if self.video_lbl:
            # self.canvas.delete(self.video_lbl)

            if not self.isRealTime:
                self.log_objects = [
                ]  # if the DSS is not recieving data from simulator, Every time it needs to make the log object list empty
                i = 0
                well_formed_filename = self.log_reader()

                try:
                    xml_file = ET.parse(well_formed_filename).getroot()
                except IOError:
                    # except FileNotFoundError as fnf_error:
                    self.logger.info(
                        "The well_formed_TraceData.log cannot be parsed! it seems there is no such a file!"
                    )

                for log_entity in xml_file.iter("log_entity"):
                    if log_entity.attrib["SimTime"] == "0":
                        continue
                    if float(log_entity.attrib["SimTime"]) > i:
                        for index, element in enumerate(log_entity):
                            for item in element.items():
                                if item:
                                    if index == 0:
                                        engine_dic.update(
                                            {item[0]: float(item[1])})
                                    elif index == 1:
                                        rudder_dic.update(
                                            {item[0]: float(item[1])})
                        aftthruster = engine_dic["aTunnelThruster"]
                        forethruster = engine_dic["fTunnelThruster"]
                        portengine = engine_dic["pEngine"]
                        stbdengine = engine_dic["sEngine"]
                        portrudder = rudder_dic["pRudder"]
                        stbdrudder = rudder_dic["sRudder"]
                        # in the tarceData file the longitude and lattitude was wirten visa verca, So their placed were changed to save them correct.
                        csv_obj = CsvFile(
                            int(float(log_entity.attrib["SimTime"])),
                            abs(float(log_entity.attrib["Longitude"])),
                            abs(float(log_entity.attrib["Latitude"])),
                            float(log_entity.attrib["SOG"]),
                            float(log_entity.attrib["COG"]),
                            float(log_entity.attrib["Heading"]),
                            float(aftthruster), float(forethruster),
                            float(portengine), float(stbdengine),
                            float(portrudder), float(stbdrudder))
                        self.log_objects.append(csv_obj)
                        if (self.scenario in ["emergency", "emergency_4tens"]
                                and i == 1800) or (self.scenario
                                                   in ["pushing", "leeway"]
                                                   and i == 900):
                            break
                        else:
                            i += 1
            # Either the log file was empty or we haven't received any network data yet
            if not self.log_objects:
                messagebox.askokcancel(
                    title="No Data!",
                    message=
                    "There is no data to use for assistance! Is the simulator running? Was the logfile valid?"
                )
                return

            instant_second = self.log_objects[
                -1].simtime  # this line get the last second when the user needs an assist
            if self.log_objects[0].simtime == 0 and self.log_objects[
                    1].simtime == 0:
                self.log_objects.pop(0)

            if instant_second < 120:  ###### Here we want to have 3 options for the best cases showing to the user#####
                self.features = Features(self.log_objects, self.scenario,
                                         self.logger, instant_second)
                #### Once the user ask for assistance at the first 2 minutes these cases will be shown
                if self.features.aspect == "direct":
                    self.suggested_speed.config(text="0.73")
                    self.suggested_heading.config(text="102.54")
                    self.suggested_area_focus.config(text="Zone")
                    self.suggested_aspect.config(text="Direct")
                    self.suggested_orientation.config(text="Bow")
                    self.suggested_distance_target.config(text="33.75")
                    self.suggested_maneuver.config(text="Pushing + PropWash")
                    self.load_image(25, "G54-3")
                    self.show_instruction("G54-3")

                elif self.features.aspect == "J_approach":
                    self.suggested_speed.config(text="1")
                    self.suggested_heading.config(text="45.2")
                    self.suggested_area_focus.config(text="Above Vessel")
                    self.suggested_aspect.config(text="J_Approach")
                    self.suggested_orientation.config(text="Bow")
                    self.suggested_distance_target.config(text="22.5")
                    self.suggested_maneuver.config(text="Pushing")
                    self.load_image(25, "NR49-3")
                    self.show_instruction("NR49-3")
                else:
                    self.suggested_speed.config(text="0.8")
                    self.suggested_heading.config(text="270")
                    self.suggested_area_focus.config(text="Above Zone")
                    self.suggested_aspect.config(text="Up_Current")
                    self.suggested_orientation.config(text="Stern")
                    self.suggested_distance_target.config(text="70")
                    self.suggested_maneuver.config(text="Pushing + Leeway")
                    self.load_image(25, "J95-3")
                    self.show_instruction("J95-3")

            else:
                self.generate_csv_file(
                    self.log_objects
                )  # This will generate a csv file based on self.log_objects list.
                self.features = Features(
                    self.log_objects, self.scenario, self.logger,
                    instant_second
                )  # This line will create the features once the user asks asssistance

                # filling the own vessel properties attributes
                # self.scale_speed.set(self.features.speed[1])
                # self.scale_instant_speed.set(self.features.speed[2])
                # self.scale_heading_avg.set(self.features.heading[1])
                # self.scale_instant_heading.set(self.features.heading[2])
                # self.scale_ice_load.set(10)
                # self.scale_distance_target_avg.set(round(self.features.distance_from_target[0], 4))
                # self.scale_instant_distance.set(round(self.features.distance_from_target[1], 4))
                '''creating and passing the feature_array to the classifier for classification'''
                feature_array = feature_array_convertor(
                    True, self.features.speed[1],
                    self.features.distance_from_target,
                    self.features.heading[1], self.features.aspect,
                    self.features.area_of_focus, self.features.orientation,
                    self.features.maneuver)

                suggested_case, case_ID, case_name, suggested_technique = self.decision_tree_classifier(
                    feature_array, self.scenario)

                self.user_logger.info(
                    f"{self.username if self.username else 'Unknown'} user requested assistance at time={instant_second}s in the {self.scenario} scenario and the suggested approach was case {case_name}"
                )

                suggested_approach_dict = feature_array_convertor(
                    False, suggested_case[0], suggested_case[1],
                    suggested_case[2], suggested_case[4], suggested_case[5],
                    suggested_case[6], suggested_technique)

                # filling the suggested ownship status variables
                self.suggested_speed.config(
                    text=suggested_approach_dict["speed"])
                self.suggested_heading.config(
                    text=suggested_approach_dict["heading"])
                if suggested_approach_dict["area_of_focus"] == "av":
                    area_of_focus = "Above Vessel"

                elif suggested_approach_dict["area_of_focus"] == "z":
                    area_of_focus = "Zone"

                elif suggested_approach_dict["area_of_focus"] == "az":
                    area_of_focus = "Above Zone"
                elif suggested_approach_dict["area_of_focus"] == "along_zone":
                    area_of_focus = "Along_Zone"
                else:
                    area_of_focus = "Unknown"

                self.suggested_area_focus.config(text=area_of_focus)
                self.suggested_aspect.config(
                    text=suggested_approach_dict["aspect"])
                self.suggested_orientation.config(
                    text=suggested_approach_dict["orientation"])
                self.suggested_distance_target.config(
                    text=suggested_approach_dict["distance"])
                self.suggested_maneuver.config(text=suggested_technique)

                ####### Find the description file for the predicted case and show up the information to the user!
                self.show_instruction(case_name)
                self.load_image(case_ID, case_name)
Example #34
0
 def on_closing(self):
     if messagebox.askokcancel("Quit", "Do you want to quit?"):
         self.master.destroy()
Example #35
0
def program_exit():
    answer = messagebox.askokcancel(title='Exit', message='Close the program?')
    if answer:
        root.destroy()
Example #36
0
def exit_():
    msg_box = messagebox.askokcancel("Exit Thesaurus",
                                     "Are you sure you want to EXIT?")
    if msg_box:
        window.destroy()
Example #37
0
def main():

    from tkinter import messagebox
    import turtle
    from turtle import Turtle, Screen
    import random
    from coolname import generate_slug
    turtle.colormode(255)
    screen = Screen()
    screen.title("Let's race! ")
    screen.bgcolor('lavenderblush')
    screen.setup(width=.75, height=0.75, startx=None, starty=None)

    def create(num):
        colors = [(255, 51, 192), (223, 45, 168),
                  (191, 38, 144), (159, 32, 120), (128, 26, 96), (96, 19, 72),
                  (64, 13, 48), (32, 6, 24), (156, 208, 216), (154, 213, 175),
                  (241, 171, 151), (229, 212, 16), (125, 115, 160)]
        x = -450
        y = -150
        players = []
        for turtles in range(num):
            name = Turtle()
            name.name = generate_slug(2)
            name.shape('turtle')
            name.penup()
            name.color(random.choice(colors))
            name.setx(x)
            name.sety(y)
            name.write(f'  {name.name}\n', True, align="right")
            name.pendown()
            name.pensize(2)
            y += 50
            players.append(name)
        return players

    def finish_line():
        line_dude = Turtle()
        line_dude.hideturtle()
        line_dude.shape('turtle')
        line_dude.color((241, 13, 77))
        line_dude.penup()
        line_dude.setheading(90)
        line_dude.speed(0)
        line_dude.setpos(400, -200)
        line_dude.showturtle()
        line_dude.pendown()
        line_dude.speed(1)
        line_dude.forward(50 * num + 50)
        line_dude.hideturtle()

    num = int(
        screen.numinput("Number of Players",
                        "How many players in the race?:",
                        3,
                        minval=0,
                        maxval=10))

    players = create(num)
    finish_line()
    finish = 400
    messagebox.askquestion(title="Let's play!", message="ready to play?")
    if 'yes':
        game_on = True
        while game_on:
            for turtl in players:
                if turtl.xcor() >= finish - 1:
                    game_on = False
                    messagebox.askokcancel('winner', f'{turtl.name} won! yes!')
                    print(f'{turtl.name}')
                    break
                else:
                    rand_distance = random.randint(1, 10)
                    turtl.forward(rand_distance)

    if messagebox.askyesno(title="again?", message="Want to play again?"):
        turtle.clearscreen()
        main()
    else:
        turtle.clearscreen()

    screen.listen()
    screen.exitonclick()
def exit():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()
def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        stop_btn()
        root.destroy()
Example #40
0
def callback():
    if messagebox.askokcancel('Quit', 'Do you really wish to quit?'):
        plt.close(1)
        root.destroy()
Example #41
0
def on_closing():
    print("closing")
    if messagebox.askokcancel("Quit", "Do you want to quit?"):

        root.destroy()
Example #42
0
def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        win.root.destroy()
        win.rt.stop()
Example #43
0
def cancel_script(self):
    if messagebox.askokcancel("Quit", "Do you really wish to cancel?"):
        self.master.destroy()
Example #44
0
 def __call__(self, *args, **kwargs):
     #sys.exit()
     ans = askokcancel('Realy Exit!!!', 'Yes Exit!!!')
     if ans:
         self.quit()
Example #45
0
# @Author: yuan.jiang
# @Date:   2018-12-29 13:20:15
# @Last Modified by:   yuan.jiang
# @Last Modified time: 2018-12-29 13:20:40

from tkinter import *
from tkinter import messagebox  #messagebox()需要单独导入
from tkinter import filedialog  #filedialog()需要单独导入
from tkinter import colorchooser  #colorchooser()需要单独导入
from tkinter.messagebox import *  #用户使用showinfo()

#警告对话框
showinfo(title='test', message='警告')

#消息对话框
result = messagebox.askokcancel('demo', '发射核弹?')  #返回值是True或False
print(result)  #根据用户按下了确定还是取消做进一步的操作

#文件对话框
root = Tk()


def callback1():
    filename = filedialog.askopenfilename(defaultextension='.py')  #指定文件后缀
    print(filename)  #返回的是文件的完整路径


Button(root, text='打开文件', command=callback1).pack()


#颜色选择对话框
Example #46
0
	def on_closing():
		if messagebox.askokcancel("Quit", "Do you want to quit?"):
			main_screen.destroy()
			client.sock.sendall(client.aes.encrypt('exit'))
			listen_if_ok()
Example #47
0
def exitc():
    if messagebox.askokcancel("Quit", "Are you sure?"):
        root.destroy()

def clicked():
    messagebox.showinfo(title='Error',
                        message='you need to insert only numbers')


def clicked_error():
    messagebox.showerror(title='Error', message='you cant do it')


def clicked_warning():
    messagebox.showwarning(title='Error',
                           message='you need to insert only letter')


bu = tk.Button(window, text='Click me', command=clicked)
bu1 = tk.Button(window, text='Hello', command=clicked_error)
bu2 = tk.Button(window, text='What', command=clicked_warning)

bu.grid(column=0, row=0)
bu1.grid(column=1, row=0)
bu2.grid(column=2, row=0)
window.mainloop()

res = messagebox.askquestion('Message title', 'Message content')
res = messagebox.askyesno('Message title', 'Message content')
res = messagebox.askyesnocancel('Message title', 'Message content')
res = messagebox.askokcancel('Message title', 'Message content')
res = messagebox.askretrycancel('Message title', 'Message content')
Example #49
0

# Prompt user to choose
print("Which one do you want to run :")
print('\nInput 1 to run "greeting to world" function, \n\
Input 2 to run "greeting to you" function,\n\
Input 3 to run "temperature transformation" function,\n\
Input 0 to exit this program.')

# Run the chosen sub-program
# and go back to the stage where user is prompted to choose
while True:
    n = int(input("\nPlease enter your number: "))
    if n == 1:
        gtw()
        continue
    elif n == 2:
        gty()
        continue
    elif n == 3:
        tt()
        continue
    elif n == 0:
        from tkinter import messagebox
        messagebox.askokcancel("Exit?", "Are you going to leave me? (ToT)")
        messagebox.showinfo("Info", "Thank you for using this program :)")
        exit()
    else:
        print("Please enter the correct number!")
        continue
 def destroy(self):
     if messagebox.askokcancel('confirmação', 'Deseja sair?'):
         super().destroy()
Example #51
0
 def del_epg():
     messagebox.askokcancel(title='Confirm Deletion',
                            message='Are you sure you want to delete this?')
     with conn:
         c.execute("DELETE FROM epginfo WHERE asset_id= " +
                   asset_id_epg.get())
Example #52
0
def ask_quit(self):
    if messagebox.askokcancel("Exit program", "Okay to exit application?"):
        self.master.destroy()
        os._exit(0)
Example #53
0
def chkQuit(self):
    if messagebox.askokcancel(
            'Quit Program', 'Would you really like to quit the application?'):
        # Close app
        self.master.destroy()
        os._exit(0)
Example #54
0
    def handleButtonPress(self, input):
        self.RefreshEmailGroups()         
        
        if self.Backup_EmailFile(self.datafilename):
            print("Automatically saving a backup of last: " + self.datafilename)
        else: 
            print("Error saving a backup of file: " + self.datafilename)
        
        if USE_ENCODED_DATA: 
            if self.Backup_EmailFile(self.lookuptablefilename):
                print("Automatically saving a backup of last: " + self.lookuptablefilename)
            else: 
                print("Error saving a backup of file: " + self.lookuptablefilename)
        
        if input == '__selected_save_changes__':
            updated_addr = self.text_Addresses.get(1.0, 'end-1c').split("\n")
            updated_addr = [x for x in updated_addr if x !=''] # remove empty strings. 

            # Update the record. 
            choice_email_group = self.combobox_box_EmailAddress.get()

            # 2. Create new Dict Entry for Manufacturer & Replace dictionary entry with new version
            # Verify if user choice already exists if so continue otherwise, 
            # Present an option to create a new Email Group
            
            hashed_addr_list = list() 
            for address in updated_addr: 
                # clean email address: 
                address = re.sub(';', '', address.lower()) # remove semicolons and tolower() 
                # filter out just email address
                # match = re.findall(r'[\w\.-]+@[\w\.-]+', address)        
                match = re.findall(r'[^@]+@[^@]+\.[^@]+', address)                        
                # match = re.findall(r'''\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\z''', address)                          
                # match = re.findall()
                if USE_ENCODED_DATA:           
                    hashed_email_address = hashlib.sha256(str(match[0]).encode('utf-8')).hexdigest() # use SHA1 hashes and save this 
                    print(match[0], hashed_email_address)
                    hashed_addr_list.append(hashed_email_address)
                    
                    # Update lookup table. 
                    self.email_lookup_table[hashed_email_address] = match[0]

                    # remove duplicate email addresses          
                    self.data[choice_email_group] = list(set(hashed_addr_list))
                else: 
                    self.data[choice_email_group] = list(set(updated_addr))
                            
            # 4. Save to disk. 
            self.SaveDatatoDisk()         
                
            # Update the Email Signature JSON file
            # Read the EmailData.json file,
            # Regenerate the Email Signature JSON object
            # Overwrite the previous signature json file with the new version.

            if USE_ENCODED_DATA:           
                self.generateSignatureJSONfile(self.datafilename, self.data)
        
        elif input == '__refresh_groups__':
            self.RefreshEmailGroups() 
            
        elif input == '__delete_group__': 
            choice_email_group = self.combobox_box_EmailAddress.get()
            userChoice = messagebox.askokcancel("Warning! Deleting Email Groups!", "Are you sure you want to remove " + choice_email_group + "?")
            if userChoice:
                del self.data[choice_email_group] 
                self.SaveDatatoDisk()      
                self.RefreshEmailGroups() 
                if USE_ENCODED_DATA:
                    self.generateSignatureJSONfile(self.datafilename, self.data)
Example #55
0
def askToCancel():
    response = messagebox.askokcancel("Attention", "Would you like to cancel?")
    Label(root, text=response).pack()
def on_closing():
    print(checkbutton_dict['check_0'].get())
    if messagebox.askokcancel("Quit", "You sure you want to quit?"):
        task.close_proto()
        window.destroy()
def sur():
    #fenetre "êtes vous sur de quitter?"
    global fenprinc
    if messagebox.askokcancel("Confirmation",
                              "Etes-vous sûr de vouloir quitter ? "):
        fenprinc.destroy()
Example #58
0
def exit_program():
    answer = messagebox.askokcancel('Eixit', 'Выйти из программы?')
    if answer:
        root.destroy()
Example #59
0
def callback():
    if msgbox.askokcancel("Quit", "Do you really wish to quit?"):
        root.destroy()
Example #60
0
def on_closing():
    from tkinter import messagebox
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
                pygame.mixer.music.stop()
                root.destroy()