When using wxPython with Twisted in the way described in the Twisted docs wxPython will be stuck on menus and modal dialogs. This is due to the fact that wxPython uses private eventloops for menus and modal dialogs. You can't run Twisted cleanly in a thread (meaning without modification) and though using wxPython in a thread is possible, it's often not a viable option. Best would be to write a threaded wxreactor for Twisted which is a major project due to the internal nature of wx - using whatever GUI toolkit is available on the target platform. This recipe is simple and works nicely on platforms using the select reactor (linux and windows).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from wxPython.wx import *
from twisted.internet import reactor
class MyApp(wxApp):
def OnInit(self):
# Twisted Reactor Code
reactor.startRunning()
EVT_TIMER(self,999999,self.OnTimer)
self.timer=wxTimer(self,999999)
self.timer.Start(250,False)
# End Twisted Code
# Do whatever you need to do here
return True
def OnTimer(self,event):
reactor.runUntilCurrent()
reactor.doIteration(0)
|
The "reactor" calls are copied from the select reactors mainloop. Note that the reactor.run() method is never called. This neverending loop is emulated by the timer events. Initialize your wxApp as usual by calling app.MainLoop() in your main module.
You might have to play with the timer value (250 ms above) as well as with the timeout value of the doIteration call. If you have only a few remote calls you can increase the timer value - so the OnTimer event will be triggered less often. This will increase the responsetime of your application. If you do heavy networking via Twisted you might want to increase the doIteration timeout (maybe 0.002) and probably decrease the timer value to somewhere around 150ms. Since the wx mainloop is running normally menus and modal dialogs won't block.
Twisted 1.1.1 has wxreactor. This recipe is no longer necessary. Itamar Shtull-Trauring added twisted.internet.wxreactor, which is a full-fledged reactor and runs each of Twisted and wx in timeslices. Modal dialogs (and menus, which are secretly modal dialogs) will now work on MSWindows with no additional code. Update your wx projects to use wxreactor and rejoice! :-)
wxreactor didn't make it into Twisted 1.1.1, although judging from the twisted-users mailling looks like it'll be in 1.1.2.
Use OnIdle for better responsiveness. I've used the wxreactor in twisted and found that the gui was too unresponsive. The solution I found that worked best was to process twisted deferred's in wxPython's OnIdle() event.