pygtk, threads and the Game of Life

Simon Burton simonb at webone.com.au
Fri Dec 6 03:22:04 EST 2002


On Thu, 05 Dec 2002 16:00:59 +0000, Rajarshi Guha wrote:

> HI,
>   I'm new to threads and am trying to program a Game Of Life with PyGTK
> and threads. The structure of my program is as follows:
> 
> class GUIThread(Thread):
>   
>   def __init__(self):
>    Thread.__init__(self)
>   
>   def run(self):
>    # Create GUI
>    gtk.mainloop()
> 
> if __name__ == '__main__':
>   g = GUIThread()
>   g.run()
>   for i in range(0,1000): print i
> 
> Now, I expected that the program would draw a window with a grid and
> randomly fill in boxes and also print out the numbers from 1 to 1000 in
> the console window. However, only the GUI shows and the numbers dont get
> printed.
> 
> I think I should be using an idle function - but I was'nt sure how to
> implement it. Basically I not very clear as to how I can iterate over an
> array and each time an element changes change the corresponding grid in
> the GUI. I though that I could start up the GUI in a thread and let it
> run in the background. Meanwhile in the foreground I would iterate over
> the array and change the GUI display when required. But it does'nt seem
> to be working.
> 
> Can anybody point out the proper path to take?
> 
> Thanks,

# here is some code that draws a line and
# then gets polled; check it out.

#!/usr/bin/env python

import gtk

def pix_init(d_area, width, height):
  d_area.realize()
  #win = d_area.get_window()
  win = d_area.window
  pixmap = gtk.create_pixmap(win, width, height, -1)
  context = win.new_gc()
  cmap = d_area.get_colormap()
  #r = 1<<15
  context.foreground = cmap.alloc_color(128*64,128*64,128*64)
  for x in range(width):
    pixmap.draw_point(context, x, height / 2)
  d_area.connect("expose-event", pix_expose, pixmap)
  return pixmap

def pix_expose(da, event, pixmap):
  x, y, width, height = da.get_allocation()
  da.window.draw_drawable(
    da.get_style().fg_gc[0], pixmap, 0, 0, 0, 0, -1, -1)

def cb(da,pixmap):
  print "hi!"
  
  gtk.timeout_add(320,cb,da,pixmap)
  da.queue_draw()

def main():
  width,height=640,480
  top = gtk.Window(gtk.WINDOW_TOPLEVEL)
  da = gtk.DrawingArea()
  #print dir(da)
  da.set_size_request(width, height)
  top.add(da)
  pixmap=pix_init(da, width, height)
  top.show_all()

  gtk.timeout_add(120,cb,da,pixmap)
  top.connect("destroy",gtk.mainquit)
  gtk.mainloop()

if __name__ =="__main__":
  main()







More information about the Python-list mailing list