【问题标题】:Wxpython browse for or drag and drop folderwxpython 浏览或拖放文件夹
【发布时间】:2014-02-13 07:05:02
【问题描述】:

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

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 已经支持拖放,但是这个操作意味着“复制和粘贴”。也许你需要实现自己的 DirDialog

标签: python drag-and-drop wxpython


【解决方案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]

【讨论】:

  • 所以我使用了第一块代码并将其保留为一个类,第二块我插入到我当前的面板中,点之间的代码,但似乎无法得到它一切正常。
  • 请参阅编辑。我忘记了主类中的通知方法。这是从 filedroptarget 类调用的,并在删除文件时做任何你想做的事情
  • 感谢 joaquin,现在当我拖放文件夹时,我得到 TypeError: String or Unicode type required
  • 抱歉,我从我的一个应用程序中复制了代码,该应用程序使用 ListCtrl 而不是 TextCtrl 来同时读取多个文件,我仅针对此处的示例对其进行了部分调整。现在,当您按照说明删除一个或多个文件时,代码确实可以工作。
  • 这很奏效。如何将 [u'/Library/Java'] 更改为 /Library/Java
猜你喜欢
  • 1970-01-01
  • 2019-10-10
  • 2020-02-10
  • 2011-10-09
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多