Pythonでファイルを開くダイアログを使う
Pythonのtkinterで、「ファイルを開く」ダイアログを使ってみました。
開くファイルを選択するダイアログ
GUIのいわゆるコモンダイアログで、開くファイルを選択するダイアログがあります。
PythonのGUIモジュールのtkinterでもこのダイアログがありますので、使ってみます。
import tkinter.filedialog
ret = tkinter.filedialog.askopenfilename([filetypes], [initialdir], [title], [multiple])
ret = tkinter.filedialog.askopenfilenames([filetypes], [initialdir], [title])
ret = tkinter.filedialog.askopenfile([filetypes], [initialdir], [title])
ret = tkinter.filedialog.askopenfiles([filetypes], [initialdir], [title])
変数 |
型 |
内容 |
---|---|---|
filetypes |
list |
省略可。ダイアログに表示するファイルのタイプ。 |
initialdir |
str |
省略可。ファイルを開くときの初期ディレクトリ。 |
title |
str |
省略可。ダイアログのタイトル。 |
multiple |
bool |
省略可。既定値はFalse。複数選択可能にするかどうか。 |
ret |
戻り値はメソッドによる。下記参照。 |
filetypesはタプルのリストです。タプルは、ファイルタイプの名前とファイルの拡張子のパターンの組み合わせです。例えば、テキストファイルと実行ファイルを指定する場合はこのようにします。
filetypes=[('text', '*.txt'), ('実行ファイル', '*.exe')]
戻り値はメソッドによって異なります。実際に試しながら見てみましょう。
askopenfilename
ボタンを押すとファイルを選択するダイアログを表示して、ダイアログの入力が確定すると戻り値の型と内容と長さをラベルに表示するプログラムです。
import tkinter
import tkinter.filedialog
class Application(tkinter.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title('tkinter dialog trial')
self.pack()
self.create_widgets()
def create_widgets(self):
self.dialog_button = tkinter.Button(self, text='File Open...', command=file_open, width=120)
self.dialog_button.pack(anchor=tkinter.NW)
self.text_1 = tkinter.StringVar()
self.type_label = tkinter.Label(self, textvariable=self.text_1)
self.type_label.pack(anchor=tkinter.W)
self.text_2 = tkinter.StringVar()
self.content_label = tkinter.Label(self, textvariable=self.text_2)
self.content_label.pack(anchor=tkinter.W)
self.text_3 = tkinter.StringVar()
self.len_label = tkinter.Label(self, textvariable=self.text_3)
self.len_label.pack(anchor=tkinter.W)
def file_open():
ini_dir = 'C:\Program Files\Python37'
ret = tkinter.filedialog.askopenfilename(initialdir=ini_dir, )
app.text_1.set('Type : ' + str(type(ret)))
app.text_2.set('Content : ' + str(ret))
app.text_3.set('Length : ' + str(len(ret)))
root = tkinter.Tk()
app = Application(master=root)
app.mainloop()
askopenfilenameはファイル名を返すメソッドです。
まず、初期ディレクトリだけを指定して実行してみます。

ボタンを押すとダイアログが開きます。

この条件ですと、全てのファイルが表示されます。
では、キャンセルしてみます。

戻り値としては、空の文字列(型がstrで長さが0)が返りました。
では、LICENSE.txtを選択してみましょう。

ファイルの絶対パスが戻されました。
では、ファイルのタイプを指定してみましょう。テキストファイルと実行ファイルだけを選択できるようにしてみます。
def file_open():
f_type = [('text', '*.txt'), ('実行ファイル', '*.exe')]
ini_dir = 'C:\Program Files\Python37'
ret = tkinter.filedialog.askopenfilename(filetypes=f_type , initialdir=ini_dir, title='file dialog test')
app.text_1.set('Type : ' + str(type(ret)))
app.text_2.set('Content : ' + str(ret))
app.text_3.set('Length : ' + str(len(ret)))

テキストファイルだけが表示されるようになりました。右下のリストボックスで表示するファイルタイプを選択できます。

では、multipleをTrueにしてみましょう。
def file_open():
f_type = [('text', '*.txt'), ('実行ファイル', '*.exe')]
ini_dir = 'C:\Program Files\Python37'
ret = tkinter.filedialog.askopenfilename(filetypes=f_type , initialdir=ini_dir, title='file dialog test', multiple=True)
app.text_1.set('Type : ' + str(type(ret)))
app.text_2.set('Content : ' + str(ret))
app.text_3.set('Length : ' + str(len(ret)))

複数のファイルを選択できるようになりました。2つのファイルを選択した状態で開いてみると、こうなります。

戻り値は、ファイルの絶対パス文字列のタプルです。ダイアログをキャンセルした場合は、空の文字列が戻されます。
askopenfilenames
askopenfilenameでmultipleをTrueにしたのと同じ動作をします。
askopenfile
askopenfileはファイルオブジェクトを開いて返します。
テキストファイルを一つ開いて、中身を表示してみましょう。
def file_open():
f_type = [('text', '*.txt')]
ini_dir = 'C:\Program Files\Python37'
ret = tkinter.filedialog.askopenfile(filetypes=f_type , initialdir=ini_dir, title='file dialog test')
app.text_1.set('Type : ' + str(type(ret)))
app.text_2.set('Content : ' + str(ret))
app.text_3.set(ret.read())

ダイアログは同じですね。

戻り値はファイルオブジェクトになりました。開いてあるので、そのままreadメソッドで読み込みできました。ファイルオブジェクトの閉じ忘れに注意です。
では、キャンセルしたらどうなるでしょうか。

Noneが戻されました。askopenfilenameと戻り値が異なるので注意です。
askopenfiles
askopenfileの複数ファイル版がaskopenfilesです。
def file_open():
f_type = [('text', '*.txt')]
ini_dir = 'C:\Program Files\Python37'
ret = tkinter.filedialog.askopenfiles(filetypes=f_type , initialdir=ini_dir, title='file dialog test')
app.text_1.set('Type : ' + str(type(ret)))
app.text_2.set('Content : ' + str(ret))
app.text_3.set(ret[0].read())

ダイアログは変わらず、複数のファイルが選択できます。テキストファイルを2つ選択して開いてみます。

戻り値は、オープンしたファイルオブジェクトのリストになっています。
ちなみに、ダイアログをキャンセルすると、空の文字列が戻されます。
戻り値の判定をするときには、Noneと空文字列の両方に対応できるようにして置いた方が良いかもしれませんね。
公開日
広告
PythonでGUIカテゴリの投稿
- PythonからWindowsのクリップボードに画像をコピーする
- PythonでCanvasをリサイズできるようにしてみた
- PythonでGUIに画像を表示する
- Pythonでクリップボードとのデータのやりとりをする
- Pythonでグラフ(Matplotlib)を表示して動的に変更する
- Pythonでディレクトリを選択するダイアログを使う
- Pythonでファイルを開くダイアログを使う
- Pythonで名前を付けて保存するダイアログを使う
- PythonのGUIを試してみた
- Pythonのcanvasにマウスで線を描いてみる
- Pythonのcanvasに表示した四角形を変形する
- Pythonのcanvasのマウスポインタの座標を取得する
- Pythonのtkinterのcanvasにクリップボードから画像をペーストする
- Pythonのtkinterのcanvasに表示する画像を切り替える