【问题标题】:wxpython - wx.EVT_COMBOBOX event and GetSelection method: manual vs user triggeringwxpython - wx.EVT_COMBOBOX 事件和 GetSelection 方法:手动与用户触发
【发布时间】:2020-08-29 01:47:03
【问题描述】:

众所周知,在代码中的 wxpython 设置中,组合框的值不会像用户用鼠标选择项目时那样触发 EVT_COMBOBOX 事件。因此,如果需要,您必须手动触发事件。

在我的程序中,在handler函数中,我需要使用event.GetSelection()方法返回的值,其中event是传入handler函数的事件对象。

现在的问题是,如果我在代码中设置组合框的值,然后手动触发 EVT_COMBOBOX 事件,则 event.GetSelection() 方法不会返回与事件上升时相同的值用户用鼠标选择相同的项目。

问题如下代码所示。

正如执行代码所见,当事件被代码触发时,event.GetSelection() 方法总是返回值 0(即组合框列表中的第一项,因此项 'a'显示在文本框中)而不是在代码中设置的值 1 将显示项目 'b'。

为什么会这样?感谢您的任何回答。

import wx
class ManualEventFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Manual Event Rising',size=(550, 200))
        self.panel = wx.Panel(self)
        self.st=wx.StaticText(self.panel, label='Select an item', pos=(10,10))
        self.cb=wx.ComboBox(self.panel,pos=(110,10),choices=['a','b','c'])
        self.st2 = wx.StaticText(self.panel, label='You choosed item', pos=(10, 75))
        self.tc=wx.TextCtrl(self.panel,pos=(110,75))
        self.button = wx.Button(self.panel,label="Select item 'b' and rise\nmanually the EVT_COMBOBOX event", pos=(300, 40))

        self.button.Bind(wx.EVT_BUTTON,self.onButton)
        self.cb.Bind(wx.EVT_COMBOBOX, self.onSelect)

    def onSelect(self,event):
        self.tc.SetValue(self.cb.GetString(event.GetSelection()))
    
    def onButton(self, event):
        self.cb.SetSelection(1)
        myevent = wx.CommandEvent(wx.EVT_COMBOBOX._getEvtType(), self.cb.GetId())
        myevent.SetEventObject(self.cb)
        self.cb.GetEventHandler().ProcessEvent(myevent)


if __name__ == '__main__':
    app = wx.App()
    frame = ManualEventFrame(parent=None, id=-1)
    frame.Show()
    app.MainLoop()

【问题讨论】:

    标签: combobox event-handling wxpython getselection


    【解决方案1】:

    我不确定为什么 event.GetSelection 在这种情况下会继续返回 0 但解决问题的方法是从“马嘴”中获取价值。
    使用:
    self.tc.SetValue(self.cb.GetStringSelection())
    或:
    self.tc.SetValue(self.cb.GetValue())

    【讨论】:

    • 感谢您的回答!我以您建议的相同方式绕过了该问题,但我很想知道为什么该方法的行为如此不同。我不太了解创建事件,所以也许我忘记了一些事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多