Skip to main content
 首页 » 编程设计

python之无法专注于 OS/X 中的小部件

2025年05月04日11grandyang

我正在运行 Python 2.7.5,并通过自制软件安装了 wxWidgets。

我的问题是在 OS/X 上运行时根本无法接收键盘事件。考虑以下示例源:

无名.py:

import wx 
import wx.xrc 
class MyFrame2 ( wx.Frame ): 
   def __init__( self, parent ): 
      wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 500,300 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) 
      self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) 
      bSizer1 = wx.BoxSizer( wx.VERTICAL ) 
      self.m_button1 = wx.Button( self, wx.ID_ANY, u"MyButton", wx.DefaultPosition, wx.DefaultSize, 0 ) 
      bSizer1.Add( self.m_button1, 0, wx.ALL, 5 ) 
      self.SetSizer( bSizer1 ) 
      self.Layout() 
      self.Centre( wx.BOTH ) 
      # Connect Events 
      self.m_button1.Bind( wx.EVT_BUTTON, self.OnClick ) 
   def __del__( self ): 
      pass 
   # Virtual event handlers, overide them in your derived class 
   def OnClick( self, event ): 
      event.Skip() 

主要.py:

from noname import MyFrame2 
class MyFrame2Impl(MyFrame2): 
    def __init__(self, parent): 
        MyFrame2.__init__(self, parent) 
    def OnClick(self, event): 
        self.m_button1.SetLabel(str(wx.Window.FindFocus() != None)) 
 
import wx 
app = wx.App(False)  # Create a new app, don't redirect stdout/stderr to a window. 
frame = MyFrame2Impl(None) # A Frame is a top-level window. 
frame.m_button1.SetFocus() 
frame.Show(True)     # Show the frame. 
app.MainLoop() 

在 Ubuntu 上,一旦我点击按钮,它就会显示“True”。按空格键单击按钮。在 OS/X 上,单击按钮后,它显示“False”。按空格键没有任何效果。

在 WxMac 常见问题 (http://www.wxwidgets.org/docs/faqmac.htm) 的底部,它是这样说的:

Why can't I set focus to my wxMac application? Because you didn't build your application as a bundle. You must create a bundle for Mac OS X applications, simply running the usual g++ wx-config --cxxflags --libs -o minimal minimal.cpp is not enough to build a correctly working Mac application. Please look at the samples makefiles which do build bundles under Mac OS X or read this wiki topic for more details.

我用这个脚本做了一个包:

from setuptools import setup 
APP = ["main.py"] 
OPTIONS = {"argv_emulation": True, "includes": ["wx"]} 
setup(app=APP, options={"py2app": OPTIONS}, setup_requires=["py2app"]) 

我用它来通过命令构建一个包:

python setup.py py2app 

这生成了可执行文件,但焦点问题仍然存在。因此,我无法使用键盘来控制应用程序。如何让应用程序检测键盘事件?

请您参考如下方法:

尝试将 wx.Panel 作为框架的唯一子项。接下来将所有其他小部件放入面板中(即将面板设置为其他小部件的父级)。我知道该面板添加了跨平台的 Tab 键功能,因此我怀疑这可能有助于处理其他键盘事件。