Python tkinter.filedialog.asksaveasfilename() Examples

The following are 30 code examples of tkinter.filedialog.asksaveasfilename(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tkinter.filedialog , or try the search function .
Example #1
Source File: editor.py    From Python-Prolog-Interpreter with MIT License 10 votes vote down vote up
def save_file_as(self, file_path=None):
        # If there is no file path specified, prompt the user with a dialog which
        # allows him/her to select where they want to save the file
        if file_path is None:
            file_path = filedialog.asksaveasfilename(
                filetypes=(
                    ("Text files", "*.txt"),
                    ("Prolog files", "*.pl *.pro"),
                    ("All files", "*.*"),
                )
            )

        try:

            # Write the Prolog rule editor contents to the file location
            with open(file_path, "wb") as file:
                self.write_editor_text_to_file(file)
                self.file_path = file_path
                return "saved"

        except FileNotFoundError:
            return "cancelled" 
Example #2
Source File: gui.py    From snn_toolbox with MIT License 9 votes vote down vote up
def save_settings(self):
        """Save current settings."""
        s = {key: self.settings[key].get() for key in self.settings}

        if self.store_last_settings:
            if not os.path.exists(self.default_path_to_pref):
                os.makedirs(self.default_path_to_pref)
            with open(os.path.join(self.default_path_to_pref,
                                   '_last_settings.json'), 'w') as f:
                f.write(json.dumps(s))
            self.store_last_settings = False
        else:
            path_to_pref = filedialog.asksaveasfilename(
                defaultextension='.json', filetypes=[("json files", '*.json')],
                initialdir=self.default_path_to_pref,
                title="Choose filename")
            with open(path_to_pref, 'w') as f:
                f.write(json.dumps(s)) 
Example #3
Source File: 5.visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 7 votes vote down vote up
def save_log():
        # 获取路径
        filename = asksaveasfilename(filetypes=[('比赛记录', '*.zlog')])
        if not filename:
            return

        if not filename.endswith('.zlog'):
            filename += '.zlog'

        # 写入比赛记录
        widget_off()
        try:
            with open(filename, 'wb') as f:
                f.write(zlib.compress(pickle.dumps(MATCH_LOG), -1))
        except Exception as e:
            showerror(type(e).__name__, str(e))
        widget_on()

    # 清空存储区 
Example #4
Source File: 6.glory_of_mankind.py    From paper.io.sessdsa with GNU General Public License v3.0 7 votes vote down vote up
def save_log():
        # 获取路径
        filename = asksaveasfilename(filetypes=[('比赛记录', '*.zlog')])
        if not filename:
            return

        if not filename.endswith('.zlog'):
            filename += '.zlog'

        # 写入比赛记录
        widget_off()
        try:
            with open(filename, 'wb') as f:
                f.write(zlib.compress(pickle.dumps(MATCH_LOG), -1))
        except Exception as e:
            showerror('%s: %s' % (self.name, type(e).__name__), str(e))
        widget_on()

    # 清空存储区 
Example #5
Source File: fileOperator.py    From Pyno with MIT License 6 votes vote down vote up
def save(self, data, filepath=None, initialfile='pyno_file.pn'):
        if filepath:
            path = filepath
        else:
            root = Tk()
            root.withdraw()
            path = filedialog.asksaveasfilename(defaultextension='pn',
                                                initialfile=initialfile,
                                                filetypes=(
                                                    ('Pyno files', '*.pn'),
                                                    ('All files', '*.*')))
            root.destroy()
        try:
            file = open(path, 'w')
        except Exception as ex:
            print('Can\'t save file:', ex)
            return False
        file.write(data)
        file.close()
        print('File', path, 'saved!')
        return True 
Example #6
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def save_grammar(self, *args):
        filename = asksaveasfilename(filetypes=self.GRAMMAR_FILE_TYPES,
                                     defaultextension='.cfg')
        if not filename: return
        try:
            if filename.endswith('.pickle'):
                with open(filename, 'wb') as outfile:
                    pickle.dump((self._chart, self._tokens), outfile)
            else:
                with open(filename, 'w') as outfile:
                    prods = self._grammar.productions()
                    start = [p for p in prods if p.lhs() == self._grammar.start()]
                    rest = [p for p in prods if p.lhs() != self._grammar.start()]
                    for prod in start: outfile.write('%s\n' % prod)
                    for prod in rest: outfile.write('%s\n' % prod)
        except Exception as e:
            tkinter.messagebox.showerror('Error Saving Grammar',
                                   'Unable to open file: %r' % filename) 
Example #7
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def print_to_file(self, filename=None):
        """
        Print the contents of this ``CanvasFrame`` to a postscript
        file.  If no filename is given, then prompt the user for one.

        :param filename: The name of the file to print the tree to.
        :type filename: str
        :rtype: None
        """
        if filename is None:
            from tkinter.filedialog import asksaveasfilename
            ftypes = [('Postscript files', '.ps'),
                      ('All files', '*')]
            filename = asksaveasfilename(filetypes=ftypes,
                                         defaultextension='.ps')
            if not filename: return
        (x0, y0, w, h) = self.scrollregion()
        self._canvas.postscript(file=filename, x=x0, y=y0,
                                width=w+2, height=h+2,
                                pagewidth=w+2, # points = 1/72 inch
                                pageheight=h+2, # points = 1/72 inch
                                pagex=0, pagey=0) 
Example #8
Source File: glory_of_mankind.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def save_log():
        # 获取路径
        filename = asksaveasfilename(filetypes=[('比赛记录', '*.clog')])
        if not filename:
            return

        if not filename.endswith('.clog'):
            filename += '.clog'

        # 写入比赛记录
        widget_off()
        try:
            match_interface.save_compact_log(MATCH_LOG, filename)
        except Exception as e:
            showerror('%s: %s' % (self.name, type(e).__name__), str(e))
        widget_on()

    # 清空存储区 
Example #9
Source File: visualize.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def save_log():
        # 获取路径
        filename = asksaveasfilename(filetypes=[('比赛记录', '*.clog')])
        if not filename:
            return

        if not filename.endswith('.clog'):
            filename += '.clog'

        # 写入比赛记录
        widget_off()
        try:
            match_interface.save_compact_log(MATCH_LOG, filename)
        except Exception as e:
            showerror(type(e).__name__, str(e))
        widget_on()

    # 清空存储区 
Example #10
Source File: io.py    From vy with MIT License 6 votes vote down vote up
def save_as(self, event):
        """
        It pops a asksaveasfilename window to save the contents of
        the text area.
        """
    
        filename = asksaveasfilename()
    
        if not filename: 
            return

        try:
            self.area.save_data_as(filename)
        except Exception:
            root.status.set_msg('It failed to save data.')
        else:
            root.status.set_msg('Data saved.') 
Example #11
Source File: DeviceManager.py    From python-dvr with MIT License 6 votes vote down vote up
def export(self):
        filename = asksaveasfilename(
            filetypes=(
                (_("JSON files"), "*.json"),
                (_("HTML files"), "*.html;*.htm"),
                (_("Text files"), "*.csv;*.txt"),
                (_("All files"), "*.*"),
            )
        )
        if filename == "":
            return
        ProcessCMD(["log", filename])
        ProcessCMD(["loglevel", str(100)])
        if ".json" in filename:
            ProcessCMD(["json"])
        elif ".csv" in filename:
            ProcessCMD(["csv"])
        elif ".htm" in filename:
            ProcessCMD(["html"])
        else:
            ProcessCMD(["table"])
        ProcessCMD(["loglevel", str(10)]) 
Example #12
Source File: pyint.py    From Pyint_Pixel-Painter with GNU General Public License v3.0 6 votes vote down vote up
def FileManager(var):
    global fileExtension
    window = Tk()
    window.withdraw()
    if var != 2:
        availableFormats = [("Windows Text File", "*.txt")]
    else:
        availableFormats = [("Portable Network Graphics", "*.png")]

    if var == 0:
        filename = askopenfilename(title="Open File", filetypes=availableFormats)
    elif var == 1:
        filename = asksaveasfilename(title="Save File", filetypes=availableFormats)
    elif var == 2:
        filename = asksaveasfilename(title="Export File", filetypes=availableFormats)

    if filename:
        name = filename[:]
        return name 
Example #13
Source File: entry.py    From tts-backup with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 *args,
                 filetypes=[],
                 defaultextension="",
                 action,
                 **kwargs):

        super().__init__(*args, **kwargs)
        self.defaultextension = defaultextension
        self.filetypes = filetypes

        if action == 'save':
            self.ask_func = filedialog.asksaveasfilename
        elif action == 'open':
            self.ask_func = filedialog.askopenfilename
        else:
            raise TypeError("Unknown action type: {}".format(action)) 
Example #14
Source File: sqlite_bro.py    From sqlite_bro with MIT License 6 votes vote down vote up
def new_db(self, filename=''):
        """create a new database"""
        if filename == '':
            filename = filedialog.asksaveasfilename(
                initialdir=self.initialdir, defaultextension='.db',
                title="Define a new database name and location",
                filetypes=[("default", "*.db"), ("other", "*.db*"),
                           ("all", "*.*")])
        if filename != '':
            self.database_file = filename
            if os.path.isfile(filename):
                self.set_initialdir(filename)
                if messagebox.askyesno(
                   message='Confirm Destruction of previous Datas ?',
                   icon='question', title='Destroying'):
                    os.remove(filename)
            self.conn = Baresql(self.database_file)
            self.actualize_db() 
Example #15
Source File: sqlite_bro.py    From sqlite_bro with MIT License 6 votes vote down vote up
def sav_script(self):
        """save a script in a file"""
        active_tab_id = self.n.notebook.select()
        if active_tab_id != '':
            # get current selection (or all)
            fw = self.n.fw_labels[active_tab_id]
            script = fw.get(1.0, END)[:-1]
            filename = filedialog.asksaveasfilename(
                initialdir=self.initialdir, defaultextension='.db',
                title="save script in a sql file",
                filetypes=[("default", "*.sql"), ("other", "*.txt"),
                           ("all", "*.*")])
        if filename != "":
            self.set_initialdir(filename)
            with io.open(filename, 'w', encoding='utf-8') as f:
                if "你好 мир Artisou à croute" not in script:
                    f.write("/*utf-8 tag : 你好 мир Artisou à croute*/\n")
                f.write(script) 
Example #16
Source File: sqlite_bro.py    From sqlite_bro with MIT License 6 votes vote down vote up
def exsav_script(self):
        """write script commands + top results to a log file"""
        # idea from http://blog.mp933.fr/post/2014/05/15/Script-vs.-copy/paste
        active_tab_id = self.n.notebook.select()
        if active_tab_id != '':
            # get current selection (or all)
            fw = self.n.fw_labels[active_tab_id]
            script = fw.get(1.0, END)[:-1]
            filename = filedialog.asksaveasfilename(
                initialdir=self.initialdir, defaultextension='.db',
                title="execute Script + output in a log file",
                filetypes=[("default", "*.txt"), ("other", "*.log"),
                           ("all", "*.*")])
        if filename == "":
            return
        self.set_initialdir(filename)
        with io.open(filename, 'w', encoding='utf-8') as f:
            if "你好 мир Artisou à croute" not in script:
                f.write("/*utf-8 tag : 你好 мир Artisou à croute*/\n")
            self.create_and_add_results(script, active_tab_id, limit=99, log=f)
            fw.focus_set()  # workaround bug http://bugs.python.org/issue17511 
Example #17
Source File: sqlite_bro.py    From sqlite_bro with MIT License 6 votes vote down vote up
def export_csv_dialog(self, query="--", text="undefined.csv", actions=[]):
        """export csv dialog"""
        # proposed encoding (we favorize utf-8 or utf-8-sig)
        encodings = ["utf-8", locale.getdefaultlocale()[1], "utf-16",
                     "utf-8-sig"]
        if os.name == 'nt':
            encodings = ["utf-8-sig", locale.getdefaultlocale()[1], "utf-16",
                         "utf-8"]
        # proposed csv separator
        default_sep = [",", "|", ";"]
        csv_file = filedialog.asksaveasfilename(
            initialdir=self.initialdir, defaultextension='.db', title=text,
            filetypes=[("default", "*.csv"), ("other", "*.txt"),
                       ("all", "*.*")])
        if csv_file != "":
            # Idea from (http://www.python-course.eu/tkinter_entry_widgets.php)
            fields = ['', ['csv Name', csv_file, 'r', 100], '',
                      ['column separator', default_sep],
                      ['Header line', True],
                      ['Encoding', encodings], '',
                      ["Data to export (MUST be 1 Request)",
                       (query), 'w', 100, 10]]

            create_dialog(("Export to %s" % csv_file), fields,
                          ("Export", export_csv_ok), actions) 
Example #18
Source File: Controlador.py    From proyectoDownloader with MIT License 6 votes vote down vote up
def cargarFB(self):

        try:
            rpta = msg.askyesno("Pregunta", "No se puede obtener información "+
                "de un video de facebook, desea continuar con la descarga?")

            if rpta:
                path = filedialog.asksaveasfilename()
                os.popen("facebook-dl.py {} hd {}".format(self.vista.url.get(),path))
                msg.showinfo("Mensaje", "Archivo descargado correctamente.")
                
        except:
            msg.showerror("Error", "El video no es público, o la url es inválida.")

        self.vista.button.config(state=NORMAL)
        self.vista.bvideo.config(state=NORMAL)
        self.vista.baudio.config(state=NORMAL)
        self.vista.bborrar.config(state=NORMAL)
        self.vista.config(cursor="") 
Example #19
Source File: gui.py    From baldr with GNU General Public License v2.0 6 votes vote down vote up
def save_clicked(self):
		request = {	'component': 'draw',
					'draw': {'args': [None],
					'kwargs': {} } }
		try:
			request['draw']['kwargs']['power'] = float(self.power_var.get())
			if self.tilt_var.get(): request['draw']['kwargs']['tilt'] = float(self.tilt_var.get()) * np.pi
			else: request['draw']['kwargs']['tilt'] = None
			request['draw']['kwargs']['guess'] = float(self.guess_var.get())
		except ValueError: pass
		else:
			request['draw']['args'][0] = filedialog.asksaveasfilename(initialdir=self.get_save_dir(), initialfile='piecewise_polynomial.dat')
			if request['draw']['args'][0]:
				print ('\
Running trajectory drawing tool in a new process. Key bindings:\n\
shift: run optimization routine\n\
Z: save trajectory to data file\n\
T: toggle waypoint adjustment\n\
Path:', request['draw']['args'][0], end='\n\n')
				self.request_q.put(request) 
Example #20
Source File: tkgui.py    From ATX with Apache License 2.0 6 votes vote down vote up
def _save_crop(self):
        log.debug('crop bounds: %s', self._bounds)
        if self._bounds is None:
            return
        bounds = self.select_bounds
        # ext = '.%dx%d.png' % tuple(self._size)
        # tkFileDialog doc: http://tkinter.unpythonic.net/wiki/tkFileDialog
        save_to = tkFileDialog.asksaveasfilename(**dict(
            initialdir=self._save_parent_dir,
            defaultextension=".png",
            filetypes=[('PNG', ".png")],
            title='Select file'))
        if not save_to:
            return
        save_to = self._fix_path(save_to)
        # force change extention with info (resolution and offset)
        save_to = os.path.splitext(save_to)[0] + self._fileext_text.get()

        self._save_parent_dir = os.path.dirname(save_to)

        log.info('Crop save to: %s', save_to)
        self._image.crop(bounds).save(save_to)
        self._genfile_name.set(os.path.basename(save_to))
        self._gencode_text.set('d.click_image(r"%s")' % save_to) 
Example #21
Source File: 6.09.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 5 votes vote down vote up
def on_save_as_menu_clicked(self):
        file_name = filedialog.asksaveasfilename(
            master=self.root, filetypes=[('All Files', ('*.ps', '*.ps'))], title="Save...")
        if not file_name:
            return
        self.file_name = file_name
        self.actual_save() 
Example #22
Source File: 3.09.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 5 votes vote down vote up
def save_project(self):
        saveas_file_name = filedialog.asksaveasfilename(
            filetypes=[('Explosion Beat File', '*.ebt')], title="Save project as...")
        if saveas_file_name is None:
            return
        pickle.dump(self.all_patterns, open(saveas_file_name, "wb"))
        self.root.title(os.path.basename(saveas_file_name) + PROGRAM_NAME) 
Example #23
Source File: 3.12.py    From Tkinter-GUI-Application-Development-Blueprints-Second-Edition with MIT License 5 votes vote down vote up
def save_project(self):
        saveas_file_name = filedialog.asksaveasfilename(
            filetypes=[('Explosion Beat File', '*.ebt')], title="Save project as...")
        if saveas_file_name is None:
            return
        pickle.dump(self.all_patterns, open(saveas_file_name, "wb"))
        self.root.title(os.path.basename(saveas_file_name) + PROGRAM_NAME) 
Example #24
Source File: easygui.py    From mantaray with GNU General Public License v3.0 5 votes vote down vote up
def filesavebox(msg=None
    , title=None
    , default=""
    , filetypes=None
    ):
    """
    A file to get the name of a file to save.
    Returns the name of a file, or None if user chose to cancel.

    The "default" argument should contain a filename (i.e. the
    current name of the file to be saved).  It may also be empty,
    or contain a filemask that includes wildcards.

    The "filetypes" argument works like the "filetypes" argument to
    fileopenbox.
    """

    boxRoot = Tk()
    boxRoot.withdraw()

    initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)

    f = tk_FileDialog.asksaveasfilename(parent=boxRoot
        , title=getFileDialogTitle(msg,title)
        , initialfile=initialfile
        , initialdir=initialdir
        , filetypes=filetypes
        )
    boxRoot.destroy()
    if not f: return None
    return os.path.normpath(f)


#-------------------------------------------------------------------
#
# fileboxSetup
#
#------------------------------------------------------------------- 
Example #25
Source File: ankimaker.py    From ankimaker with MIT License 5 votes vote down vote up
def select_file(self):
        options = {'defaultextension':'apkg',
                   'parent':self,
                   'title':'Select the Anki deck location'}
        self.filename = filedialog.asksaveasfilename(**options)
        if self.filename != '': 
            self.file_entry.delete(0, tkinter.END)
            self.file_entry.insert(0, self.filename) 
Example #26
Source File: gun.py    From lections_2019 with GNU General Public License v3.0 5 votes vote down vote up
def get_save_file_name(self):
        os.makedirs(self.save_dir, exist_ok=True)
        file_name = filedialog.asksaveasfilename(
            initialdir=self.save_dir,
            title='Save game',
            filetypes=(("json files", "*.json"), ("all files", "*.*"))
        )
        if file_name in [(), '']:
            return None
        return file_name 
Example #27
Source File: easygui.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def filesavebox(msg=None
    , title=None
    , default=""
    , filetypes=None
    ):
    """
    A file to get the name of a file to save.
    Returns the name of a file, or None if user chose to cancel.

    The "default" argument should contain a filename (i.e. the
    current name of the file to be saved).  It may also be empty,
    or contain a filemask that includes wildcards.

    The "filetypes" argument works like the "filetypes" argument to
    fileopenbox.
    """
    if sys.platform == 'darwin':
        _bring_to_front()
    localRoot = Tk()
    localRoot.withdraw()

    initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)

    f = tk_FileDialog.asksaveasfilename(parent=localRoot
        , title=getFileDialogTitle(msg,title)
        , initialfile=initialfile
        , initialdir=initialdir
        , filetypes=filetypes
        )
    localRoot.destroy()
    if not f: return None
    return os.path.normpath(f)


#-------------------------------------------------------------------
#
# fileboxSetup
#
#------------------------------------------------------------------- 
Example #28
Source File: rollingshutter.py    From rollingshutterpy with GNU General Public License v3.0 5 votes vote down vote up
def select_output(self) -> None:
        path = asksaveasfilename(title='Please select the path of the image to create.',
                                 defaultextension='.png',
                                 filetypes=[('PNG File', '*.png'), ('JPEG File', '*.jpg')])
        if not path:
            return None
        
        self.file_output = path

        self.speed_scale.state(['!disabled'])
        self.btn_start['state'] = 'normal' 
Example #29
Source File: CDNSP-GUI-Bob.py    From CDNSP-GUI with GNU General Public License v3.0 5 votes vote down vote up
def export_persistent_queue(self):
        self.dump_persistent_queue(self.normalize_file_path(filedialog.asksaveasfilename(initialdir = self.path, title = "Select file", filetypes = (("JSON files","*.json"),("all files","*.*"))))) 
Example #30
Source File: pdfviewer.py    From pdfviewer with MIT License 5 votes vote down vote up
def _run_ocr(self):
        if self.pdf is None:
            return
        pdf_pages = list()
        for page in self.pdf.pages:
            image = page.to_image(resolution=100)
            pdf = pytesseract.image_to_pdf_or_hocr(image.original, extension='pdf')
            pdf_pages.append(pdf)

        pdf_writer = PyPDF2.PdfFileWriter()
        for page in pdf_pages:
            pdf = PyPDF2.PdfFileReader(io.BytesIO(page))
            pdf_writer.addPage(pdf.getPage(0))

        dirname = os.path.dirname(self.paths[self.pathidx])
        filename = os.path.basename(self.paths[self.pathidx])

        path = filedialog.asksaveasfilename(title='Save OCR As', defaultextension='.pdf',
                                            initialdir=dirname, initialfile=filename,
                                            filetypes=[('PDF files', '*.pdf'), ('all files', '.*')])
        if path == '' or path is None:
            return

        with open(path, 'wb') as out:
            pdf_writer.write(out)

        self.paths[self.pathidx] = path
        self._load_file()