Tkinter + threads = trouble?

Roman Suzi rnd at onego.ru
Mon Sep 17 00:50:42 EDT 2001


Here is an example I prepared. It runs OK on Linux/X window, but stops
dead on Win98SE (do I file a bug report on windows98.sourceforge.net ;-)?
(WARNING: Windows could require rebooting to return to normal look)

--------------------------------------------------------------

import thread, time, sys
from Tkinter import *

distance = 300
colors = ["Red","Orange","Yellow","Green","Blue","DarkBlue","Violet"]
nrunners = len(colors)

def quit():
  tk.quit()
  sys.exit(0)

tk = Tk()
tk.title("Race")
c = Canvas(tk, width=distance, height=len(colors)*20)
c.pack()

rects = []
for i in range(nrunners):
  rects.append(c.create_rectangle(0, i*20, 0, i*20+10, fill=colors[i]))

champion = StringVar()
Label(tk, textvariable=champion).pack()
b = Button(text="Go", command=tk.quit)
b.pack(side=LEFT)
qb = Button(text="Quit", command=quit)
qb.pack(side=RIGHT)

def run(n):
  while 1:
    graph_lock.acquire()
    positions[n] = x = positions[n] + 1
    c.coords(rects[n], 0, n*20, x, n*20+10)
    tk.update_idletasks()
    if x == distance:
      if not champion.get():
        champion.set("%s - champion!" % colors[n])   # TROUBLE
        tk.update_idletasks()
      graph_lock.release()
      break
    graph_lock.release()

def prepare():
  champion.set("")
  for i in range(nrunners):
    c.coords(rects[i], 0, i*20, 0, i*20+10)
    thread.start_new_thread(run, (i,))
  tk.update_idletasks()

graph_lock = thread.allocate_lock()
while 1:
  b.config(state=NORMAL); qb.config(state=NORMAL)
  tk.mainloop()
  b.config(state=DISABLED); qb.config(state=DISABLED)
  graph_lock.acquire()
  positions = [0]*nrunners
  prepare()
  graph_lock.release()
  while reduce(lambda x, y: x+y, positions, 0) < distance*nrunners:
    time.sleep(0.1)
  tk.update_idletasks()
  print champion.get()

----------------------------------------------------------------------


Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Monday, September 17, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "Murphy was an optimist." _/





More information about the Python-list mailing list