Search code examples
pythonwxpython

wxPython SetFocus() not working


I'm trying to use SetFocus() on a window in wxPython. I'm not sure exactly what it should look like on Mac, but as far as I can tell there are no visual changes at all when I call window.SetFocus(), and window.HasFocus() returns False. Here's some simplified example code:

app = wx.App()

frame = wx.Frame(None, -1, '')
box = wx.StaticBox(frame, -1, "")
sizer = wx.StaticBoxSizer(box, orient=wx.HORIZONTAL)
text = wx.StaticText(frame, label="Some Text")
sizer.Add(text, wx.ALIGN_LEFT|wx.ALL, border=10)
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(sizer)
frame.SetSizer(main_sizer)

frame.Centre()
frame.Show()
text.SetFocus()
print 'text.HasFocus?', text.HasFocus()

app.MainLoop()

This problem is present with wxPython versions '2.9.2.4' and '3.0.2.0'. Any ideas?

edit:

It looks like a StaticText widget cannot accept focus (window.AcceptFocus()) returns False). In that case, is there a simple, accepted way of highlighting a window like this? Or, is it possible to change whether or not a window can accept focus?


Solution

  • As it is static text arguably there is nothing to receive focus as you cannot click into it.
    Try your code amended slightly to see how to set focus and use event.focus to see changes in focus.

    import wx
    def onFocus(event):
        print "widget received focus!"
    
    def onKillFocus(event):
        print "widget lost focus!"
    
    app = wx.App()
    
    frame = wx.Frame(None, -1, '')
    box = wx.StaticBox(frame, -1, "")
    sizer = wx.StaticBoxSizer(box, orient=wx.VERTICAL)
    text0 = wx.StaticText(frame,label="1st Item")
    text0_input = wx.TextCtrl(frame, wx.ID_ANY, size=(345,25))
    text = wx.StaticText(frame, label="Some Text")
    text_input = wx.TextCtrl(frame, wx.ID_ANY, size=(345,25))
    sizer.Add(text0, wx.ALIGN_LEFT|wx.ALL, border=10)
    sizer.Add(text0_input, wx.ALIGN_LEFT|wx.ALL, border=10)
    sizer.Add(text, wx.ALIGN_LEFT|wx.ALL, border=10)
    sizer.Add(text_input, wx.ALIGN_LEFT|wx.ALL, border=10)
    text0_input.Bind(wx.EVT_SET_FOCUS, onFocus)
    text0_input.Bind(wx.EVT_KILL_FOCUS, onKillFocus)
    
    main_sizer = wx.BoxSizer(wx.VERTICAL)
    main_sizer.Add(sizer)
    frame.SetSizer(main_sizer)
    
    frame.Centre()
    frame.Show()
    text_input.SetFocus()
    #print 'text_input.HasFocus?', text_input.HasFocus()
    
    app.MainLoop()