为什么在wx.ComboBox中调用wx.EVT_TEXT事件两次?

时间:2017-08-09 13:36:16

标签: wxpython

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

我的问题是:

  • 这是预期的行为吗?
  • 如果是,那么正确的处理方式是怎样的 它们?

我看到了以下解决方案:

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

2 个答案:

答案 0 :(得分:2)

可以说,第一个问题的答案是肯定的。
您绑定到wx.EVT_TEXT而不是更常见的wx.EVT_COMBOBOX,我期望的结果是为该组合框中的每个文本事件触发的事件,例如键入或取消其中的字符。登记/> 我怀疑,你真正想要的是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个事件。
我希望能澄清一些事情。

答案 1 :(得分:0)

我不认为获得两个事件是预期的行为。我构建了一个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()
相关问题