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)

我不确定如何将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])

使用此示例,您将生成一个文本控件,您可以在其中放置文件。请注意,通知方法在其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]

最新更新