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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: texteditor.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def file_save(self, event=None):
        """
        Ctrl+S
        """
        current_file = self.open_file if self.open_file else None
        if not current_file:
            current_file = filedialog.asksaveasfilename()

        if current_file:
            contents = self.text_area.get(1.0, tk.END)
            with open(current_file, 'w') as file:
                file.write(contents) 
Example #22
Source File: texteditor.py    From Tkinter-GUI-Programming-by-Example with MIT License 5 votes vote down vote up
def file_save(self, event=None):
        """
        Ctrl+S
        """
        current_file = self.open_file if self.open_file else None
        if not current_file:
            current_file = filedialog.asksaveasfilename()

        if current_file:
            contents = self.text_area.get(1.0, tk.END)
            with open(current_file, 'w') as file:
                file.write(contents) 
Example #23
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def save_chart_dialog(self, *args):
        filename = asksaveasfilename(filetypes=self.CHART_FILE_TYPES,
                                     defaultextension='.pickle')
        if not filename: return
        try:
            with open(filename, 'wb') as outfile:
                pickle.dump(self._out_chart, outfile)
        except Exception as e:
            tkinter.messagebox.showerror('Error Saving Chart',
                                   'Unable to open file: %r\n%s' %
                                   (filename, e)) 
Example #24
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def save_chart(self, *args):
        "Save a chart to a pickle file"
        filename = asksaveasfilename(filetypes=self.CHART_FILE_TYPES,
                                     defaultextension='.pickle')
        if not filename: return
        try:
            with open(filename, 'wb') as outfile:
                pickle.dump(self._chart, outfile)
        except Exception as e:
            raise
            tkinter.messagebox.showerror('Error Saving Chart',
                                   'Unable to open file: %r' % filename) 
Example #25
Source File: map-creator.py    From rpg-text with MIT License 5 votes vote down vote up
def _on_data_save(self, *args):
        fname = fd.asksaveasfilename()
        self.data.save(fname) 
Example #26
Source File: pynpuzzle.py    From pynpuzzle with MIT License 5 votes vote down vote up
def save_file_cmd(puzzle_frame, parent):
    """
    Input's save to file button click handler

    puzzle_frame : The puzzle frame which it's puzzle will be saved to file
    parent : The parent window of the puzzle_frame
             This is used for showing the 'save as file' dialog so it can be showed on top of the window.
    """
    # Check if puzzle frame has a valid input, and if not, ask the user if he's sure he wants to save the puzzle
    lst = is_input_puzzle_valid(puzzle_frame)
    if not lst:
        if not messagebox.askokcancel("Input not valid",
                                      "Input puzzle is not valid, are you sure to save it as a file?",
                                      parent=parent):
            return

    # Open the 'save as file' dialog
    file_name = filedialog.asksaveasfilename(title="Choose a file to save puzzle", parent=parent)
    # Check if user has selected a file
    if not file_name:
        return

    # Generate file's content
    len_sqrt = int(math.sqrt(len(lst)))
    file_lines = []
    for i in range(0, len(lst), 3):
        line_nums = []
        for j in range(0, len_sqrt):
            line_nums.append(str(lst[i + j]))
        file_lines.append(' '.join(line_nums))

    try:
        with open(file_name, 'w') as file:
            file.write('\n'.join(file_lines))
    except:
        messagebox.showerror("Error saving to file",
                             "Some problem happened while saving puzzle to the file.",
                             parent=parent)


# Save to file button widgget 
Example #27
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 #28
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 #29
Source File: viewer.py    From meshrender with Apache License 2.0 5 votes vote down vote up
def _save_image(self):
        # Get save file location
        try:
            root = Tk()
            fn = ''
            if self._save_filename:
                fn = '{}.png'.format(self._save_filename)
            filename = filedialog.asksaveasfilename(initialfile = fn,
                                                    initialdir = (self._save_directory or os.getcwd()),
                                                    title = 'Select file save location',
                                                    filetypes = (('png files','*.png'),
                                                                ('jpeg files', '*.jpg'),
                                                                ('all files','*.*')))
        except:
            logging.warning('Cannot use Tkinter file dialogs over SSH')
            return

        root.destroy()
        if filename == ():
            return
        else:
            self._save_directory = os.path.dirname(filename)

        # Extract color image from frame buffer
        width, height = self._size
        glReadBuffer(GL_FRONT)
        color_buf = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE)

        # Re-format them into numpy arrays
        color_im = np.frombuffer(color_buf, dtype=np.uint8).reshape((height, width, 3))
        color_im = np.flip(color_im, axis=0)

        imageio.imwrite(filename, color_im) 
Example #30
Source File: viewer.py    From meshrender with Apache License 2.0 5 votes vote down vote up
def _save_gif(self):
        # Get save file location
        try:
            root = Tk()
            fn = ''
            if self._save_filename:
                fn = '{}.gif'.format(self._save_filename)
            filename = filedialog.asksaveasfilename(initialfile = fn,
                                                    initialdir = (self._save_directory or os.getcwd()),
                                                    title = 'Select file save location',
                                                    filetypes = (('gif files','*.gif'),
                                                                ('all files','*.*')))
        except:
            logging.warning('Cannot use Tkinter file dialogs over SSH')
            self._saved_frames = []
            return

        root.destroy()
        if filename == ():
            self._saved_frames = []
            return
        else:
            self._save_directory = os.path.dirname(filename)

        imageio.mimwrite(filename, self._saved_frames, fps=30.0, palettesize=128, subrectangles=True)

        self._saved_frames = []