[Python,Gtk4] Gtk.FileDialogの使用について③  フォルダを選択する

目標

 Gtk.FileDialogは、フォルダの選択にも使用することができます。今回は、Gtk.FileDialogを使用したフォルダの選択の方法を紹介します。

Gtk.FileDialogの定義

フォルダを開く

 Gtk.FileDialogでファイルを開く作業は、以下の手順でおこないます。
 1. メソッドselect_folderによりファイルダイアログを表示する。
 2. 関数on_filedialog_select_folder(1.で指定)内で、メソッドselect_folder_finishにより
  選択したファイル(戻り値は、Gio.FileもしくはNone)を取得する。
 3. 取得したGio.Fileよりファイルのパスやファイル名を取得する。

        filedialog.select_folder(
            parent=self, cancellable=None,
            callback=self.on_filedialog_select_folder)

    def on_filedialog_select_folder(self, filedialog, task):
        try:
            file = filedialog.select_folder_finish(task)
        except GLib.GError:
            return

        print(file.get_path())
        print(file.get_parent().get_path())
        print(file.get_basename())

サンプルプログラム

 以下のプログラムを実行すると、左図のようなウィンドウが表示されます。ウィンドウ内の`Gtk.FileDialoの表示`ボタンを押すと、右図のようなGtk.FileDialogが表示されます。
 Gtk.FileDialogでフォルダを選択してOkボタンを押すと、ターミナルに選択したフォルダのパスやフォルダ名を表示します。

import os
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk, GLib


APPID = 'com.github.taniyoshima.g4_fblog2_filedialog3'


class Gtk4TestTest(Gtk.Window):

    def __init__(self, app):
        Gtk.Window.__init__(
            self, application=app, title='FileDialog Test3',
            default_width=400, default_height=80)

        button = Gtk.Button(
            label='Gtk.FileDialogの表示',
            margin_top=20, margin_bottom=20,
            margin_start=20, margin_end=20,
        )
        button.connect('clicked', self.on_button_clicked)

        self.set_child(button)

    def on_button_clicked(self, button):
        filedialog = Gtk.FileDialog(
            title="フォルダの選択",
            accept_label="Ok",
            modal=True,
        )

        filedialog.select_folder(
            parent=self, cancellable=None,
            callback=self.on_filedialog_select_folder)

    def on_filedialog_select_folder(self, filedialog, task):
        try:
            file = filedialog.select_folder_finish(task)
        except GLib.GError:
            return

        print(file.get_path())
        print(file.get_parent().get_path())
        print(file.get_basename())


class Gtk4TestApp(Gtk.Application):

    def __init__(self):
        Gtk.Application.__init__(self, application_id=APPID)

    def do_activate(self):
        window = Gtk4TestTest(self)
        window.present()


def main():
    app = Gtk4TestApp()
    app.run()


if __name__ == '__main__':
    main()
タイトルとURLをコピーしました