【问题标题】:Using Command-W or Control-W to close a Frame使用 Command-W 或 Control-W 关闭框架
【发布时间】:2014-04-11 17:07:46
【问题描述】:

我有一个 wx.Frame 子类,用户应该能够通过按 Command-W(在 OS X 上)或 Control-W(在 Windows 上)来关闭它。我的代码看起来像

def MyWindow(wx.Frame):
    def __init__(self):
        # ...
        self.Bind(wx.EVT_KEY_DOWN, self.handle_key)
        # ...

    def handle_key(self, event):
        if event.GetKeyCode() == wx.WXK_CONTROL_W:
            self.Destroy()

在 Windows 下,handle_key 什么都不做,直到我通过单击将 Frame 聚焦。之后,按下一个键会触发handle_key,但 CtrlW 会触发函数的单独调用,因此条件永远不会满足。

在 OS X 下,任何按键都不会调用 handle_key,即使在我单击 Frame 以设置焦点之后也是如此。

我怎样才能实现这个按键处理程序,以便

  1. 其行为跨平台是一致的,除了 CtrlCmd
  2. 用户可以在Frame位于最前面时随时按下组合键,无论哪个窗口实际具有焦点?

【问题讨论】:

    标签: wxpython wxwidgets


    【解决方案1】:

    您应该使用 AcceleratorTable 而不是自己尝试捕捉按键。这是文档的链接:

    您可能会发现本教程也很有帮助:

    在您的情况下,代码如下所示:

    exitId = wx.NewId()
    self.Bind(wx.EVT_MENU, self.onExit, id=exitId )
    
    accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('W'), exitMenuItem.GetId()) ])
    self.frame.SetAcceleratorTable(accel_tbl)
    

    【讨论】:

      【解决方案2】:

      使用加速器表的建议很好。但是为了完整起见,如果你真的需要处理 Ctrl/Cmd+W 你的代码应该是这样的:

      def handle_key(self, event):
          if event.GetKeyCode() == 'W' and event.GetModifiers() == wxMOD_CONTROL:
               # ... whatever ...
      

      注意wxMOD_CONTROL 在 Mac 下确实是 Cmd (如果你真的想要在所有平台下使用 Ctrl,你可以使用单独的 wxMOD_RAW_CONTROL)。

      【讨论】:

        【解决方案3】:

        使用 Command-W 或 Control-W 关闭框架

        使用 Ctrl-W 关闭 wx.Frame 的准系统示例:

        import wx
        class MyForm(wx.Frame):
            def __init__(self):
                wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(500,500))
                panel = wx.Panel(self, wx.ID_ANY)
        
        
                #attach the key bind event to accellerator table
                randomId = wx.NewId()
                self.Bind(wx.EVT_MENU, self.onKeyCombo, id=randomId)
                accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('W'), randomId )])
                self.SetAcceleratorTable(accel_tbl)
        
            #method invoked on key press
            def onKeyCombo(self, event):
                print "You pressed CTRL+W!"
                self.Destroy()
        
        if __name__ == "__main__":
            app = wx.App(False)
            frame = MyForm()
            frame.Show()
            app.MainLoop()
        

        来源:https://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators

        【讨论】:

          猜你喜欢
          • 2013-10-12
          • 1970-01-01
          • 2014-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-28
          • 2020-06-06
          相关资源
          最近更新 更多