LoginSignup
3
7

More than 3 years have passed since last update.

Tkinterでファイル選択をGUIで行う。

Posted at

本当はドラッグアンドドロップがしたい

ファイルを指定する際、エクスプローラからドラッグアンドドロップして指定できたらすごく楽だなぁ・・・と思っていたら、なんとTkinterは標準では別アプリケーションからのドラッグアンドドロップに対応していないとの事。
(頑張ればできるらしいが面倒くさいので)今回はダイアログボックスを使うことにする。
※Pythonのバージョンは3.7.2です。

コード

pori.py
import os, shutil, sys
from tkinter import filedialog as tkFileDialog

これでインポートして

pori.py

def dialog_action(event):
    dir_entry.delete(0, tkinter.END)
    dir_=tkFileDialog.askdirectory()
    dir_entry.insert(tkinter.END, dir_)

dialog = tkinter.Button(text=form1_dialog_text, font=btn_font)
dialog.bind("<Button-1>",dir_dialog_action)
dialog.pack(anchor = 'w')

イベントとボタンの実装はこんな感じ。ダイアログで選択したディレクトリのパスをエントリーに入力する。入力する前にエントリーの中身を消しておかないと、入力済みの内容の後ろにパスが入力される。

完成品

前回作ったアプリにこのボタンを追加。
c06ac7eb7bda91ff62fa839c59d425e5.png

使いやすくなっていくのが楽しい。

おまけ

前回の投稿でもらったコメントにあったこのコード

pori.py
dir_ = input() or dir_

すげえ(語彙力が無い)
1行で書けることに衝撃を受けました。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7