How can I set the default open path for Gtk.FileChooserWidget?

If I set the current folder using the method Gtk.FileChooserWidget.set_current_folder()

, the first time I open the file selection, it opens at the location used as the argument forset_current_folder()

But, if I select a file, I open the selector file again, it will open in the "most_recent_used_files" file.

I would like it to open in the last selected path to the file folder.

How to do it?

Thank.

+3


source to share


2 answers


From the docs:

Older versions of the documentation suggest using gtk_file_chooser_set_current_folder () in various situations to allow the application to suggest a reasonable default folder. This is no longer considered good policy as the file picker can now make good suggestions on its own. In general, you should force the selection file to display a specific folder when it makes sense to use gtk_file_chooser_set_filename () - that is, when you issue the File / Save As command and you already have a file saved somewhere.



You may or may not like the reasoning behind this behavior. If you are wondering how this happened, see "Featured Files" on the mailing list and Help the user choose where to put the new file on the GNOME wiki.

+3


source


Setting the current folder each time works for me, but it is a little tricky. I am using Gtk 3.14 and Python 2.7.

You must get the filename before dumping the directory, or it is lost and the current directory may be None, so you need to check that.



This code has been tested on Debian jessie and Windows 7.

import os.path as osp

from gi.repository import Gtk

class FileDialog(Gtk.FileChooserDialog):
    def __init__(self, parent, title):
        Gtk.FileChooserDialog.__init__(self, title, parent)
        self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
        self.add_button(Gtk.STOCK_OPEN, Gtk.ResponseType.OK)

        self.set_current_folder(osp.abspath('.'))

    def __call__(self):
        resp = self.run()
        self.hide()

        fname = self.get_filename()

        d = self.get_current_folder()
        if d:
            self.set_current_folder(d)

        if resp == Gtk.ResponseType.OK:
            return fname
        else:
            return None

class TheApp(Gtk.Window):
    def on_clicked(self, w, dlg):
        fname = dlg()
        print fname if fname else 'canceled'

    def __init__(self):
        Gtk.Window.__init__(self)

        self.connect('delete_event', Gtk.main_quit)
        self.set_resizable(False)

        dlg = FileDialog(self, 'Your File Dialog, Sir.')
        btn = Gtk.Button.new_with_label('click here')
        btn.connect('clicked', self.on_clicked, dlg)

        self.add(btn)
        btn.show()

if __name__ == '__main__':
    app = TheApp()
    app.show()
    Gtk.main()

      

0


source







All Articles