如何在wxPython 3.0.2.0中通过wx.GenericDirCtrl双击触发事件加载文件?
Got it, I’ve run into this exact snag before when working with older wxPython releases! Since EVT_DIRCTRL_FILEACTIVATED is a Phoenix-specific event that doesn’t exist in wxPython 3.0.2.0 (for Python 2.7), you can fall back to using the underlying TreeCtrl event that’s supported in all legacy versions. Here’s how to make it work:
The Core Idea
wx.GenericDirCtrl is built on top of wx.TreeCtrl, so you can use the generic EVT_TREE_ITEM_ACTIVATED event — this triggers when a tree node is double-clicked (or activated with the Enter key). You just need to add a check to ensure you’re handling files, not folders.
Full Working Example
import wx import os class FileLoaderFrame(wx.Frame): def __init__(self, parent, title): super(FileLoaderFrame, self).__init__(parent, title=title, size=(700, 500)) # Initialize the GenericDirCtrl with your preferred style self.dir_ctrl = wx.GenericDirCtrl( self, style=wx.DIRCTRL_SHOW_FILTERS | wx.DIRCTRL_EDIT_LABELS ) # Bind the tree item activation event to our handler self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.on_double_click, self.dir_ctrl) self.Show() def on_double_click(self, event): # Get the activated tree item selected_item = event.GetItem() if not selected_item: return # Fetch the full path of the item item_path = self.dir_ctrl.GetPath(selected_item) # Check if the item is a file (skip folder double-clicks) if os.path.isfile(item_path): # Replace this with your actual file loading logic print(f"Loading file: {item_path}") # Example: open the file in a text editor, parse its content, etc. else: # Let the default folder expand/collapse behavior run event.Skip() if __name__ == "__main__": app = wx.App() FileLoaderFrame(None, "Double-Click File Loader") app.MainLoop()
Key Details
- Event Binding: We bind
wx.EVT_TREE_ITEM_ACTIVATEDdirectly to thewx.GenericDirCtrlinstance — it forwards the event from its internal TreeCtrl automatically. - File vs Folder Check: Using
os.path.isfile()ensures we only trigger your loading logic when a file is double-clicked. For folders,event.Skip()lets the default behavior (expanding/collapsing) continue working as expected. - Path Retrieval:
self.dir_ctrl.GetPath(selected_item)gives you the full absolute path of the activated item, which you can use to load or process the file.
This approach is reliable for wxPython 3.0.2.0 and other pre-Phoenix versions, and it mimics the behavior you wanted from the Phoenix-specific event.
内容的提问来源于stack exchange,提问作者user668074

