dimanche 4 mai 2014

Python, Tkinter et thread

Voici un petit programme d'exemple pour mise en oeuvre de Python 3.4, Tkinter et un thread.

import tkinter as tk
import threading
import time

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.quitButton = tk.Button(self, text='Quit',
            command=self.wait_and_quit)
        self.quitButton.grid()
        self.text = tk.Text(self)

        self.text.grid()
        self.text.config(state=tk.DISABLED)

        self.threadEvent= threading.Event()
        self.threadObj = ThreadedTask(self.threadEvent,self)
        self.threadObj.start()

    def wait_and_quit(self):
        # A l'arret, on pose l'event et on attend la fin du thread avant de quitter
        self.threadEvent.set()
        self.threadObj.join()
        quit()

    def addLine(self,txt):
        # Methode permettant d'afficher une chaine de texte sur une nouvelle
        # ligne du widget text
        self.text.config(state=tk.NORMAL)
        self.text.insert(tk.END, txt+"\n")
        self.text.config(state=tk.DISABLED)

class ThreadedTask(threading.Thread):
    def __init__(self, quitEvent, applicationObj):
        threading.Thread.__init__(self)
        self.quitEvent = quitEvent
        self.appliObj=applicationObj

    def run(self):
        while self.quitEvent.wait(1.0) == False:
            self.appliObj.addLine("New line")
            time.sleep(2)  # Attente de 2 seconde

if __name__=='__main__':
    app = Application()
    app.master.title('Thread Test')
    app.addLine("Ligne essai 1")
    app.addLine("Ca semble fonctionner ?")
    app.mainloop()

Aucun commentaire:

Enregistrer un commentaire