wxPython: Calling an event manually

后端 未结 6 1728
青春惊慌失措
青春惊慌失措 2020-12-02 17:14

How can I call a specific event manually from my own code?

6条回答
  •  一向
    一向 (楼主)
    2020-12-02 18:00

    While methods like PostEvent and ProcessEvent, mentioned in other answers, can sort-of do this, be aware that they have significant limitations:

    • You're limited in what events you can easily create. For instance, there's no way to create a wx.KeyEvent with a particular key code, because the constructor doesn't take a key code and there's no setter. Maybe there are workarounds for this (like subclassing KeyEvent), but you're essentially having to hack around the limitations of the framework.
    • Even for events that you can create, like a click event, the behavior you get from programmatically dispatching the event won't match the behaviour you'd get from actually performing the action as a user, because the native handling of the event won't fire. For instance, programmatically firing a click event on a text field won't give the text field focus.

    I'd recommend against using PostEvent or ProcessEvent in most circumstances. If you just to make your event handling function to run, then manually creating events is pointless; instead just call the function explicitly. If you want them because you're trying to write an automated UI test, then you probably aren't going to end up with something that satisfies you due to the limitations listed above; instead, I'd recommend writing something that actually simulates clicks and keypresses at the level of the OS/desktop manager using wx.UIActionSimulator. It's kind of gross, and will take control of your system's mouse and keyboard which usually makes such tests inappropriate for a test suite that you run on a development machine... but at least it works, which is more than can be said for dispatching events with PostEvent.

提交回复
热议问题