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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
   | #!/usr/local/bin/python
# -*- coding:utf-8 -*-
from Tkinter import *
import threading
import time
from math import *
 
class ObjetTournant(threading.Thread):
    def __init__(self, x, y, dans_canvas, ray, couleur):
        threading.Thread.__init__(self)
        self.rayon = ray
        self.x0 = x
        self.y0 = y
        self.coul = couleur
        self.angle = 0
        self.c = dans_canvas
        self.Fini = False
        self.ref = self.c.create_line(self.x0, self.y0, self.x0+self.rayon, self.y0, width = 8, fill=self.coul)
 
    def run(self):
        while not self.Fini:
            new_x = self.x0 + int(self.rayon * sin (radians(self.angle)))
            new_y = self.y0 + int(self.rayon * cos (radians(self.angle)))
            self.c.coords(self.ref, self.x0, self.y0, int(new_x), int(new_y))
            self.angle += 1
            if self.angle >= 360:
                self.angle = 0
            time.sleep(0.01)
        print "Le thread ",self.coul," est fini."
 
    def stop(self):
        self.Fini = True
 
class Application:
    def __init__(self):
        self.root=Tk()
        self.root.title('Objets tournants avec threads - v02')
        self.root.geometry('700x400')
        self.root.protocol("WM_DELETE_WINDOW", self.finirapplication)
 
        self.ca = Canvas(self.root, bg="white")
        self.ca.pack(side=LEFT, expand=YES, fill=BOTH)
 
        self.listeDesObjetsTournant = []
 
        self.listeDesObjetsTournant.append(ObjetTournant(100,200,self.ca, 50, "red"))
        self.listeDesObjetsTournant.append(ObjetTournant(500,100,self.ca, 30, "green"))
        self.listeDesObjetsTournant.append(ObjetTournant(340,200,self.ca, 40, "blue"))
        self.listeDesObjetsTournant.append(ObjetTournant(200,100,self.ca, 80, "black"))
 
        self.fra = Frame(self.root)
 
        t = 0
        for i in self.listeDesObjetsTournant:
            but1 = Button(self.fra, text="Start "+str(t), command=lambda m=i:self.objetdemarrer(m))
            but1.grid(row=t,column=0)
            but2 = Button(self.fra, text="Stop "+str(t), command=lambda m=i:self.objetstop(m))
            but2.grid(row=t,column=1)
            t += 1
 
        self.fra.pack(side=RIGHT)
 
        self.root.mainloop()
 
    def finirapplication(self):
        for obj in self.listeDesObjetsTournant:
            #obj.Fini = True
            obj.stop()
        sys.exit()
 
    def objetdemarrer(self, m):
        m.Fini = False
        m.start()
 
    def objetstop(self, m):
        m.stop()
 
if __name__ == "__main__":
    app = Application() | 
Partager