【问题标题】:wxPython: Ensure only one instance of a panel is openwxPython:确保仅打开一个面板实例
【发布时间】:2024-01-01 15:05:01
【问题描述】:

我正在编写一个多窗口、多框架的应用程序。对于打开的每个新窗口/框架,应该只有一个该窗口的实例。我希望用户能够在这些窗口之间快速切换,所以ShowModal() 不起作用。我试过使用SingleInstanceChecker,但我无法让它工作,因为它更多地用于应用程序而不是框架。我应该如何做到这一点?

【问题讨论】:

    标签: python wxpython instance frame wxwidgets


    【解决方案1】:

    我做了一点 Google-Fu 并找到了这个旧线程:

    使用它作为我的模板,我整理了这个小脚本,它似乎可以在我的 Linux 机器上运行:

    import wx
    
    ########################################################################
    class MyPanel(wx.Panel):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self, parent):
            """Constructor"""
            wx.Panel.__init__(self, parent)
    
    
    ########################################################################
    class SingleInstanceFrame(wx.Frame):
        """"""
    
        instance = None
        init = 0
    
        #----------------------------------------------------------------------
        def __new__(self, *args, **kwargs):
            """"""
            if self.instance is None:
                self.instance = wx.Frame.__new__(self)
            elif isinstance(self.instance, wx._core._wxPyDeadObject):
                self.instance = wx.Frame.__new__(self)
            return self.instance
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
            print id(self)
            if self.init:
                return
            self.init = 1
    
            wx.Frame.__init__(self, None, title="Single Instance Frame")
            panel = MyPanel(self)
            self.Show()
    
    
    
    ########################################################################
    class MainFrame(wx.Frame):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
            wx.Frame.__init__(self, None, title="Main Frame")
            panel = MyPanel(self)
            btn = wx.Button(panel, label="Open Frame")
            btn.Bind(wx.EVT_BUTTON, self.open_frame)
            self.Show()
    
        #----------------------------------------------------------------------
        def open_frame(self, event):
            frame = SingleInstanceFrame()
    
    if __name__ == '__main__':
        app = wx.App(False)
        frame = MainFrame()
        app.MainLoop()
    

    【讨论】:

      【解决方案2】:

      除了迈克的回答之外,我还找到了另一种方法,所以我想我会发布它以防万一有人需要它。

      SingleInstanceChecker 实际上适用于 wx.Frames 和 wx.Panels。它的工作方式与在 App 中的工作方式相同。

      将这段代码片段放入面板的__init__ 函数中

      self.instance = wx.SingleInstanceChecker(self.name)
      

      然后,在实例化您的面板时,调用它:

          if panel.instance.IsAnotherRunning():
            wx.MessageBox("Another instance is running!", "ERROR")
            return
      

      而且它的工作方式与您期望的完全一样。

      【讨论】:

        最近更新 更多