如何为Gtk.FileChooserWidget?

2024-10-04 05:34:14 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我通过Gtk.FileChooserWidget.set_current_folder()方法设置当前文件夹,则第一次打开文件选择器时,它将在用作set_current_folder()参数的位置打开

但是,如果我选择一个文件,我会重新打开文件选择器,它会在“最近使用过的文件”上打开。在

我希望它在最后选定文件的文件夹路径上打开。在

怎么做?在

谢谢。在


Tags: 文件方法路径文件夹gtk参数选择器current
2条回答

每次都设置当前文件夹对我都有效,但有点棘手。我使用的是gtk3.14和python2.7。在

在重置目录之前必须获取文件名,否则它会丢失,而当前目录可能是None,因此您必须进行检查。在

这段代码在DebianJessie和Windows7上进行了测试。在

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()

从文件中:

Old versions of the file chooser's documentation suggested using gtk_file_chooser_set_current_folder() in various situations, with the intention of letting the application suggest a reasonable default folder. This is no longer considered to be a good policy, as now the file chooser is able to make good suggestions on its own. In general, you should only cause the file chooser to show a specific folder when it is appropriate to use gtk_file_chooser_set_filename() - i.e. when you are doing a File/Save As command and you already have a file saved somewhere.

你可能喜欢也可能不喜欢这种行为的原因。如果您想知道它是如何产生的,请参见邮件列表中的File chooser recent-files和gnomewiki上的Help the user choose a place to put a new file。在

相关问题 更多 >