wxPython question

J. Random Hacker jrandom at mddd.com
Mon Nov 18 10:14:45 EST 2002


On Sun, 17 Nov 2002 21:26:44 +0200, Chris Liechti wrote:

> "joshua solomon" <jslm at earthlink.net> wrote in
> news:lNRB9.2743$fY3.294687 at newsread2.prod.itd.earthlink.net:
> 
>> Basically I have a loop within the OnPaint handler which I am using for
>> bouncing a ball around on a screen.
> 
> don't do the loop for the animation in the event handler. do it in a
> separate thread nad call Refresh() or us a wxClientDC to draw in that loop
> directly.
> 
> GUI rule 1: event handlers have to be short (in time)
> 
> so no animations and workers. use Threading instead.
> 

But don't always use threads, especially if you don't need to. I mention
it here, because things like your bouncing ball routine don't really need
threads. Threads come in handy when you want to schedule some long running
process that would be difficult or impossible to run in the main thread.
This solution works well, because having a few threads for throwing some
long running task to is cheap.

But in your case, there is no long running task that you have to break
out. All you are doing is changing some variables (the ball) at regular
intervals (thats all animation is). Changing variables doesn't take much
time at all, so its OK to do this in a event handler.
This is a prime job for a timer handler (a wxTimer).

Basically, write your bouncing ball actor in such a way that you can
update it on a frame by frame basis. It just needs some attributes like
vx, and vy (velocity). Then use a wxTimer at an apporpriate rate (say
40ms), to call a handler. The handler simply: updates the
ball vars (calculate new x and y values), and then draws.

class Canvas(wxPanel):
	def __init__(self, parent, id):
		...
	        tid = wxNewId()
        	self.timer = wxTimer(self, tid)
        	self.timer.Start(40)
		...
		EVT_TIMER(self, tid, self.OnNextFrame)

	def OnNextFrame(self, event):
		... update ball variables
		self.Refresh()




More information about the Python-list mailing list