【Python】GUIでファイル選択する tkinter.filedialog 雛形

Python
この記事は約2分で読めます。

各局皆様、こんにちは。アマチュア無線局、JS2IIUです。

自分用に、雛形を置いておきます。Pythonでファイル選択、フォルダ選択をユーザがGUIで選択できるようにするサンプルです。tkinterのfiledialogを使っています。MacでもWindowsでも動作するはずです。

ファイル選択でフルパスを取得する

from tkinter import filedialog
import os

currentPath, basename = os.path.split(__file__)
filepath = filedialog.askopenfilename(
    title='Select File',
    filetypes=[('CSV file', '.csv'), ('Log File', '.log .lgf')],
    initialdir=currentPath
)

ファイル選択でファイルオブジェクトを取得する

from tkinter import filedialog
import os

currentPath, basename = os.path.split(__file__)
fileobj = filedialog.askopenfile(
    title='Select File',
    filetypes=[('CSV file', '.csv'), ('Log File', '.log .lgf')],
    initialdir=currentPath
)

フォルダを選択する

from tkinter import filedialog
import os

currentPath, basename = os.path.split(__file__)
dirPath = filedialog.askdirectory(initialdir=currentPath)

コメント

タイトルとURLをコピーしました