How to use Python SaveAs dialog

I am trying to find a python function to represent the save file as dialog that returns the file name as a string.

I quickly found the tkFileDialog module, only to understand that its asksaveasfilename function asksaveasfilename an exception if the input file does not already exist, and this is not the behavior I'm looking for.

I think the answer I'm looking for is in the Python FileDialog module, but I think this is the get_selection method of the get_selection class. Below you can see my errors interactively, trying to figure out the usage:

 >>> FileDialog.SaveFileDialog.get_selection() Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: unbound method get_selection() must be called with SaveFileDialog instance as first argument (got nothing instead) >>> x = FileDialog.SaveFileDialog() Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: __init__() takes at least 2 arguments (1 given) 

At first I tried to see if I could just call up a dialog box. Then, seeing that I needed an instance of SaveFileDialog , I tried to assign it to the variable x . But apparently this also takes two arguments and what I really am losing.

reference

+6
source share
1 answer

Here is a small example of the asksaveasfilename() function. Hope you can use it:

 import Tkinter, Tkconstants, tkFileDialog class TkFileDialogExample(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root) button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt) self.file_opt = options = {} options['filetypes'] = [('all files', '.*'), ('text files', '.txt')] options['initialfile'] = 'myfile.txt' options['parent'] = root def asksaveasfilename(self): filename = tkFileDialog.asksaveasfilename(**self.file_opt) if filename: return open(filename, 'w') if __name__=='__main__': root = Tkinter.Tk() TkFileDialogExample(root).pack() root.mainloop() 

I managed to open (and create) existing files.

+7
source

Source: https://habr.com/ru/post/895251/


All Articles