当用户单击textCtrl时,我试图触发一行代码。最终目标是在单击该框时突出显示该框的内容。我知道可以通过wx.EVT_SET_FOCUS做到这一点,但它可能是错误的,或者我实现错误。这是我的代码:

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)


该代码可以在需要时成功触发highlightText,但是由于某种原因,光标已从textCtrl中删除,从而使用户无法选择其位置,突出显示或退格键。任何建议,将不胜感激。附带说明一下,在wxFormBuilder中有没有办法做到这一点?我使用它构建了应用程序,但是无法添加焦点事件。似乎它提供的唯一焦点事件是针对整个窗口的。

编辑9/19/14:
迈克,这是我在gui.py中自动生成的wxFormBuilder代码:

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()


...这是我编写的事件处理程序

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'


该事件运行正常(如需要时可以在测试中打印出来),但是我无法突出显示文本,也看不到光标。

最佳答案

您没有显示事件处理程序,但是我猜想您需要在其末尾调用event.Skip()。我还想指出您错误地绑定了事件。它应该是:

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


要么

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


有关完整说明,请参见wxPython Wiki:


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

09-11 17:50
查看更多