Wxpython浏览或拖放文件夹

时间:2014-02-13 07:05:03

标签: python drag-and-drop wxpython

我目前有以下代码手动获取目录路径,我也想添加拖放功能,所以我可以将文件夹拖放到窗口中。

self.pathindir1 = wx.TextCtrl(self.panel1, -1, pos=(35, 120), size=(300, 25))
self.buttonout = wx.Button(self.panel1, -1, "Open", pos=(350,118))
self.buttonout.Bind(wx.EVT_BUTTON, self.openindir1)

def openindir1(self, event):
    global indir1
    dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
    if dlg.ShowModal() == wx.ID_OK:
        indir1 = dlg.GetPath()
        self.SetStatusText("Your selected directory is: %s" % indir1)
    self.pathindir1.Clear()
    self.pathindir1.WriteText(indir1)

1 个答案:

答案 0 :(得分:1)

我不确定您希望如何将wx.DirDialog与拖放条目合并,因为它们是两种不同的方式来读取程序中的文件路径。
对于拖放条目,您可能需要定义wx.FileDropTarget类:

class MyFileDropTarget(wx.FileDropTarget):
    """"""
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filenames):
        self.window.notify(filenames)
#

然后在你的框架中:

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, None)
        ...........................
        dt1 = MyFileDropTarget(self)
        self.tc_files = wx.TextCtrl(self, wx.ID_ANY)
        self.tc_files.SetDropTarget(dt1)
        ...........................

    def notify(self, files):
        """Update file in testcontrol after drag and drop"""
        self.tc_files.SetValue(files[0])

通过此示例,您可以生成文本控件,您可以在其中删除文件。 请注意,notify方法在其files参数中收到的是列表 如果删除文件夹,则会获得如下文件夹名称:

[u'C:\\Documents and Settings\\Joaquin\\Desktop\\MyFolder']

或者如果您从文件夹中删除一个或多个文件:

[u'C:\\Documents and Settings\\Joaquin\\Desktop\\MyFolder\\file_1.txt',
 u'C:\\Documents and Settings\\Joaquin\\Desktop\\MyFolder\\file_2.txt',
 ...................................................................
 u'C:\\Documents and Settings\\Joaquin\\Desktop\\MyFolder\\file_n.txt']

由您决定如何处理这些列表。对于该示例,我假设您正在选择文件,我在测试控件中编写第一个文件files[0]