Skip to main content
 首页 » 编程设计

python之具有现有进程的 wxPython GUI

2025年05月04日75fff_TT

我最初想用带有看门狗和进程的 Python 创建一个文件监控系统。在我的程序中,我有一个 FileSystemEventHandler 子类 (DirectoryMonitorHandler) 来监视文件夹更改。声明一个全局队列,以便 DirectoryMonitorHandler 将项目插入队列。队列然后可以处理子类,用于处理由 DirectoryMonitorHandler 插入的对象。这是我程序中的代码片段:

if __name__ == "__main__": 
    # The global queue that is shared by the DirectoryMonitorHandler and BacklogManager is created 
    q = Queue() 
 
    # Check if source directory exists 
    if os.path.exists(source): 
        # DirectoryMonitorHandler is initialized with the global queue as the input 
        monitor_handler = DirectoryMonitorHandler(q) 
        monitor = polling.PollingObserver() 
        monitor.schedule(monitor_handler, source, recursive = True) 
        monitor.start() 
 
        # BacklogManager is initialized with the global queue as the input 
        mamanger = BacklogManager(q) 
        mamanger.start() 
 
        mamanger.join() 
        monitor.join() 
    else: 
        handleError('config.ini', Error.SourceError) 

这个程序运行良好,但现在我决定向它添加一个 GUI 组件。这是我目前所拥有的:

class MonitorWindow(wx.Frame): 
    def __init__(self, parent): 
        super(MonitorWindow, self).__init__(parent, title='Monitor', size=(size_width, size_height)) 
        staticBox = wx.StaticBox(self, label='Monitor Status:', pos=(5, 105), size=(size_width - 28, size_height/3)) 
        self.statusLabel = wx.StaticText(staticBox, label='None', pos=(10, 35), size=(size_width, 20), style=wx.ALIGN_LEFT) 
        self.InitUI() 
 
    def InitUI(self): 
        panel = wx.Panel(self) 
        self.SetBackgroundColour(background_color) 
        self.Centre() 
        self.Show() 
 
    def updateStatus(self, status): 
        self.statusLabel.SetLabel('Update: ' + status) 
 
if __name__ == '__main__': 
    app = wx.App() 
    window = MonitorWindow(None) 
    app.MainLoop() 

此窗口工作正常,但我不确定如何将这两个组件集成在一起。 wxPython GUI 应该作为一个单独的进程运行吗?我想我可以创建一个 MonitorWindow 的实例,在它们启动之前将其传递给 DirectoryMonitorHandlerBacklogManager

我也读过这个http://wiki.wxpython.org/LongRunningTasks它确实解释了 wxPython 窗口如何与线程一起工作,但我需要它来与进程一起工作。另一种可能的解决方案是,我必须从 Window 类中创建并启动 DirectoryMonitorHandlerBacklogManager 的实例。大家怎么看?

请您参考如下方法:

wxPython 本身应该是主进程,它应该启动监控文件系统的长时间运行的进程。如果您正在使用多处理模块,那么您可能应该阅读以下内容之一:

您提到的 Long Running Tasks wiki 文章非常适合学习如何使用 wxPython 和线程。我已经多次使用该文章中的技术,没有出现任何问题。