1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
import threading
import Tkinter as tk
import time
import random
class Th(threading.Thread):
def __init__(self, lock, widget):
threading.Thread.__init__(self)
self.counter = random.randint(0, 1000000)
self.lock = lock # le semaphore doit etre partage
self.widget = widget
self.running = True # en prevision de l'arret du thread
def run(self):
while self.running:
self.lock.acquire()
#section supposee critique
self.widget.config(text=str(self.counter))
self.counter += 1
# fin de section critique
self.lock.release()
time.sleep(0.001)
class App():
def __init__(self, win, *widgets):
self.widgets = widgets
self.win = win
def run(self, bt):
# demarre les threads
threads = []
lock = threading.Lock()
for widget in self.widgets:
item = Th(lock, widget)
item.start()
threads.append(item)
#prepare l'arret de l'application
command = lambda win=self.win, threads=threads:cleanQuit(win, *threads)
self.win.protocol("WM_DELETE_WINDOW", command)
bt['command'] = command
bt['text'] = 'STOP'
def cleanQuit(win, *threads):
for item in threads:
item.running = False
win.quit()
print "Bye..."
class Gui():
def __init__(self):
gui = tk.Tk()
widgets = []
for x in range(5):
widget = tk.Label(gui)
widget.pack()
widgets.append(widget)
app = App(gui, *widgets)
bt = tk.Button(gui, text="START", width=10)
bt['command'] = lambda bt=bt:app.run(bt)
bt.pack()
gui.mainloop()
Gui() |
Partager