How to write wxPython textCtrl focus event

 ̄綄美尐妖づ 提交于 2019-12-24 03:10:12

问题


I'm trying to fire a line of code when the user clicks on a textCtrl. The end goal is to highlight the contents of the box when it is clicked on. I am aware that this is possible with wx.EVT_SET_FOCUS, but it's either buggy or I'm implementing it wrong. Here's my code:

self.m_textCtrl1 = wx.TextCtrl(self.m_panel2, wx.ID_ANY, wx.EmptyString, 
                               wx.DefaultPosition, wx.Size(100,-1), wx.TE_LEFT)
self.m_textCtrl1.SetMaxLength(8) 
self.m_textCtrl1.SetMinSize(wx.Size(100,-1))
self.m_textCtrl1.SetMaxSize(wx.Size(100,-1))
self.m_textCtrl1.Bind(wx.EVT_SET_FOCUS, self.highlightText, self.m_textCtrl1)

This code is able to successfully fire highlightText when I want it to, but for some reason the cursor is removed from the textCtrl, leaving the user unable to pick his spot, highlight, or backspace. Any suggestions would be appreciated. As a side note, is there a way to do this in wxFormBuilder? I built my application using it but was unable to add a focus event. It seems the only focus events it offers are for the entire window.

EDIT 9/19/14: Mike, here's my automatically generated wxFormBuilder code, in gui.py:

class OrderNumEntry ( wx.Frame ):
    def __init__( self, parent ):
        # there's a lot more stuff here, but it's irrelevant
        self.m_textCtrl1.Bind( wx.EVT_SET_FOCUS, self.highlightText )

    def __del__( self ):
        pass

    # Virtual event handlers, overide them in your derived class
    def highlightText( self, event ):
        event.Skip()

... and here's the event handler that I wrote

import wx, gui

class OrderFrame(gui.OrderNumEntry):
    def __init__(self, parent):
        gui.OrderNumEntry.__init__(self, parent)
        # again, a lot more irrelevant stuff here

    def highlightText(self, event):
        print 'test'

The event works fine (as in test is printed when I want it), but I'm not able to highlight text and I can't see my cursor.


回答1:


You don't show your event handler, but my guess would be that you need to call event.Skip() at the end of it. I want to also note that you binding the event incorrectly. It should be:

self.m_textCtrl1.Bind(wx.EVT_SET_FOCUS, self.highlightText)

or

self.Bind(wx.EVT_SET_FOCUS, self.highlightText, self.m_textCtrl1)

See the wxPython wiki for a complete explanation:

  • http://wiki.wxpython.org/self.Bind%20vs.%20self.button.Bind


来源:https://stackoverflow.com/questions/25899489/how-to-write-wxpython-textctrl-focus-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!