为什么在wx中.组合框 wx.EVT_TEXT事件被调用两次?



在代码中,我将事件self.Bind(wx.EVT_TEXT, self.OnText)绑定到wx。组合框。OnText被调用两次。我也在其他事件中看到类似的行为。

我的问题是:

  • 这是预期行为吗?
  • 如果是,正确的处理方式如何 他们?

我看到了以下解决方案:

def OnText(self, event):
if self.event_skip:
self.event_skip = False
return
do_somthing()
self.event_skip = True

可以说,您的第一个问题的答案是肯定的!
您绑定到wx.EVT_TEXT而不是更常见的wx.EVT_COMBOBOX,我希望的结果是为该组合框中的每个文本事件触发的事件,例如在其中键入或取消字符。
我怀疑,您真正想要的是仅在按 Enter 键时才发出事件的wx.EVT_TEXT_ENTER,这将允许您输入不在choices中的选择。为此,您需要使用style=wx.TE_PROCESS_ENTER选项创建组合框。
组合框的事件包括:

EVT_COMBOBOX: Process a wxEVT_COMBOBOX event, when an item on the list is selected. Note that calling GetValue returns the new value of selection.
EVT_TEXT: Process a wxEVT_TEXT event, when the combobox text changes.
EVT_TEXT_ENTER: Process a wxEVT_TEXT_ENTER event, when RETURN is pressed in the combobox (notice that the combobox must have been created with wx.TE_PROCESS_ENTER style to receive this event).
EVT_COMBOBOX_DROPDOWN: Process a wxEVT_COMBOBOX_DROPDOWN event, which is generated when the list box part of the combo box is shown (drops down). Notice that this event is only supported by wxMSW, wxGTK with GTK+ 2.10 or later, and OSX/Cocoa.
EVT_COMBOBOX_CLOSEUP: Process a wxEVT_COMBOBOX_CLOSEUP event, which is generated when the list box of the combo box disappears (closes up). This event is only generated for the same platforms as wxEVT_COMBOBOX_DROPDOWN above. Also note that only wxMSW and OSX/Cocoa support adding or deleting items in this event.

编辑: 我看了一下您在另一个答案的评论中引用的代码。它有点令人困惑,因为它指的是self.ignoreEvtText,这使它看起来好像以某种方式与eventEVT_TEXT有关。
不是!编码人员自己设置该变量,

self.Bind(wx.EVT_TEXT, self.EvtText)
self.Bind(wx.EVT_CHAR, self.EvtChar)
self.Bind(wx.EVT_COMBOBOX, self.EvtCombobox)
self.ignoreEvtText = False

并使用它来操纵发生的事情,因为他们将 3 个事件绑定到同一个组合框。
如果用户从选项中选择wx.EVT_COMBOBOX项目,或者如果用户按back tab(键码 8(wx.EVT_CHAR,则忽略wx.EVT_TEXT事件。
我希望这能澄清一些事情。

我不认为获得两个事件是预期的行为。我构建了一个 wx 的最小工作示例。TextCtrl,无论我尝试什么,对该控件内容的一次更改只会触发一个wx。对我来说EVT_TEXT事件,而不是两个:

import time
import wx
def evthandler(evt):
print(time.time())
if __name__ == "__main__":
app = wx.App()
frame = wx.Frame(None)
text = wx.TextCtrl(frame)
text.Bind(wx.EVT_TEXT, evthandler)
frame.Show()
app.MainLoop()

最新更新