Drawing in "Slow motion".

Eric Brunel eric.brunel at pragmadev.com
Tue Feb 12 10:55:41 EST 2002


Hi Hans,

Hans Kristian Ruud wrote:
> I have written a small script concerned with some drawing into a Canvas
> widget
> (The actual drawing procedure is triggered by an event bound to a
> Button).
> 
> My problem is that I would like the program to draw one line at a time;
> then
> pause, then draw the next line... and so on.
> 
> I have tried to insert pauses by calling time.seep,
> however, the drawing operations are realized only
> when the drawing procedure ends and program control is resumed by
> 
> root.mainloop()

Two solutions come to my mind:
- keep your time.sleep calls, but call the update_idletasks method on the 
canvas after each sleep. The call should redraw the screen.
- a bit trickier: use the delayed callback facility in Tk via the "after" 
method to draw while your application is running. This is a bit more 
complicated and you would certainly have to rewrite your code differently. 
But it's the only way to have a "reacting" application while the drawing 
takes place (i.e. user is able to click on buttons, call menus, etc...). 
Here is a simple example, just drawing random lines:

--------------------------------------------
import random
from Tkinter import *

w, h = 500, 500
x, y = random.randrange(w), random.randrange(h)

root = Tk()
cnv = Canvas(root, width=w, height=h)
cnv.pack(side=TOP)
Button(root, text='Enough', command=root.quit).pack(side=TOP)

def f(*whatever):
  global x, y
  oldx, oldy = x, y
  x, y = random.randrange(w), random.randrange(h)
  cnv.create_line(oldx, oldy, x, y)
  root.after(500, f)

root.after(500, f)
root.mainloop()
--------------------------------------------

HTH
 - eric -




More information about the Python-list mailing list