Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

tkinter - how to use Python SaveAs dialog

I'm trying to find a python function for presenting a 'save file as' dialog that returns a filename as a string.

I quickly found the tkFileDialog module, only to realize that its asksaveasfilename function throws an exception if the file entered doesn't already exist, which is not the behavior I'm looking for.

I think the answer I'm looking for is in the Python FileDialog module, but my best guess is that it's the get_selection method of the SaveFileDialog class. Below, you can see my blundering about in interactive mode trying to figure out 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)

First I was trying to see if I could just invoke the dialog box. Then seeing that I needed a SaveFileDialog instance, I tried to assign one to the variable x. But apparently that also takes two arguments, and that's where I get really lost.

Help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a small example for the asksaveasfilename() function. I 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 was able to open (and create) in-existent files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...