俺言語。

自分にしか理解できない言語で書かれた備忘録

【Python】 ドラッグアンドドロップを実装したファイル選択ダイアログ

正確にはファイル選択ダイアログではなく、FilePickerを使ってファイルを選択している。

import wx

## 本体のクラス
class MyFileChooseDialog:

    def __init__(self, *dir):

        if len(dir) == 0:
            self.inidir = ""
        else:
            self.inidir = dir[0]

    def MyFileChooseDialog(self):
        app = wx.PySimpleApp()
        frame = MyFrame(self.inidir)
        frame.Show()
        app.MainLoop()

        return self.output

## D&Dを実装するクラス
class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window # ファイルをドロップする対象

    def OnDropFiles(self, x, y, filenames): # ファイルをドロップする時の処理

        for file in filenames:
            self.window.filePicker.SetPath(file) # ←なんでwindow が必要なのかがわからない。。
            #self.window.text.SetValue(file)

## GUIを実装するクラス
class MyFrame(wx.Frame):

    def __init__(self, *inidir):

        if len(inidir) == 0:
            inidir = ""
        else:
            inidir = inidir[0]

        wx.Frame.__init__(self, None, title = "Choose mat file", size = (500,200))

        p = wx.Panel(self)
        sizer_main = wx.BoxSizer(wx.VERTICAL)

        # Sizer1
        sizer1 = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(p, -1, "FileName")
        self.filePicker = wx.FilePickerCtrl(p, wx.ID_ANY, path= inidir+"\\", style=wx.FLP_DEFAULT_STYLE)

        sizer1.Add(label, proportion=0, flag=wx.ALL, border=15)
        sizer1.Add(self.filePicker, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)

        # Sizer2
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)

        btn_load = wx.Button(p, wx.ID_ANY, 'Load')

        sizer2.Add(btn_load, proportion=1, flag=wx.ALL | wx.ALIGN_CENTRE, border=5)

        # パネルにSizerをadd
        sizer_main.Add(sizer1)
        sizer_main.Add(sizer2)
        p.SetSizer(sizer_main)

        # D&Dの設定
        dt = MyFileDropTarget(self) # ドロップする対象をこのフレーム全体にする
        self.SetDropTarget(dt)

        # Loadボタンを押したときのイベント
        self.Bind(wx.EVT_BUTTON, self.OnClick, btn_load)

    def OnClick(self, event):

        MyFileChooseDialog.output = self.filePicker.GetPath()
        self.Close()

# for debug---------------------------------------------------------------------------------------------
if __name__ == "__main__":

    import os
    # インスタンス化
    a = MyFileChooseDialog(os.path.abspath(r"C:\Users\hogehoge\Desktop"))
    # インスタンスメソッドを実行
    print a.MyFileChooseDialog()

こちらを参考にさせてもらいました↓

d.hatena.ne.jp