【Python GUIサンプル】Tkinterでfiledialog(ファイルダイアログ)を使ってみる

<tkinterトップページに戻る>

ファイルダイアログ

ファイルをGUI上で選択しファイルパスを取得するダイアログ

filedialog

使用するモジュール

tkinter.filedialog

使い方

まずはモジュールをimport

import tkinter.filedialog as filedialog

※tkinter.filedialogを使うごとに書くのはめんどくさいのでfiledialogという別名をつける

ダイアログを開く

filedialog.askopenfilename()

ちなみにファイルダイアログでファイルが選択されるまで処理は中断(待ち状態)される。

以下サンプルコード

from tkinter import *
import tkinter.ttk as ttk
import tkinter.filedialog as filedialog

class FiledialogSampleApp(ttk.Frame):

    def __init__(self, app):
        super().__init__(app)
        self.pack()

        # Widget用変数を定義
        self.filename = StringVar()

        label = ttk.Label(self,text="File名")
        label.pack(side="left")
        # textvariableにWidget用の変数を定義することで変数の値が変わるとテキストも動的に変わる
        filenameEntry = ttk.Entry(self,text="",textvariable= self.filename)
        filenameEntry.pack(side="left")

        button = ttk.Button(self,text="open",command = self.openFileDialog )
        button.pack(side="left")

    #ファイルダイアログを開いてfilenameEntryに反映させる
    def openFileDialog(self):
        file  = filedialog.askopenfilename();
        self.filename.set(file)


if __name__ == '__main__':
    #Tkインスタンスを作成し、app変数に格納する
    app  = Tk()
    #縦幅400横幅300に画面サイズを変更します。
    app.geometry("400x300")
    #タイトルを指定
    app.title("File Dialog Sample Program")
    # #フレームを作成する
    frame = FiledialogSampleApp(app)
    # 格納したTkインスタンスのmainloopで画面を起こす
    app.mainloop()

 

 

①openを押す

filedialog_1

②ファイルダイアログが開く。ファイルを選択して開くを押下。

filedialog_2

③filenameEntryに値が反映させる

filedialog_3

 

ファイルダイアログに拡張子を指定することで、選択可能なファイルを絞る

askopenfilenameのオプションfiletypesにファイルタイプを定義する。

tuple型で”(filetypes名,実際のファイルタイプ)”で指定する。

  • すべてのファイルタイプ:filedialog.askopenfilename(filetypes=[(“all files”, “*”)])
  • pngファイル:filedialog.askopenfilename(filetypes=[(“png”,”*.png”)])
  • pythonファイル:filedialog.askopenfilename(filetypes=[(“python”,”*.py”)])
  • 複数のファイルタイプ:filedialog.askopenfilename(filetypes=[(“all files”, “*”),(“png”,”*.png”),(“gif”,”*.gif”),(“python”,”*.py”)])

filedialog_4

ファイル名欄の隣にファイルタイプが選択できるようになる。

 

関連記事

・ファイルダイアログで初期ディレクトリを指定する

・ファイルダイアログで初期ファイルを指定する

 

あわせて読みたい