Ali M.
0
Q:

python watchdog tkinter

from tkinter import *
from tkinter import filedialog
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

class Watchdog(PatternMatchingEventHandler, Observer):
    def __init__(self, path='.', patterns='*', logfunc=print):
        PatternMatchingEventHandler.__init__(self, patterns)
        Observer.__init__(self)
        self.schedule(self, path=path, recursive=False)
        self.log = logfunc

    def on_created(self, event):
        # This function is called when a file is created
        self.log(f"hey, {event.src_path} has been created!")

    def on_deleted(self, event):
        # This function is called when a file is deleted
        self.log(f"what the f**k! Someone deleted {event.src_path}!")

    def on_modified(self, event):
        # This function is called when a file is modified
        self.log(f"hey buddy, {event.src_path} has been modified")

    def on_moved(self, event):
        # This function is called when a file is moved    
        self.log(f"ok ok ok, someone moved {event.src_path} to {event.dest_path}")

class GUI:
    def __init__(self):
        self.watchdog = None
        self.watch_path = '.'
        self.root = Tk()
        self.messagebox = Text(width=80, height=10)
        self.messagebox.pack()
        frm = Frame(self.root)
        Button(frm, text='Browse', command=self.select_path).pack(side=LEFT)
        Button(frm, text='Start Watchdog', command=self.start_watchdog).pack(side=RIGHT)
        Button(frm, text='Stop Watchdog', command=self.stop_watchdog).pack(side=RIGHT)
        frm.pack(fill=X, expand=1)
        self.root.mainloop()

    def start_watchdog(self):
        if self.watchdog is None:
            self.watchdog = Watchdog(path=self.watch_path, logfunc=self.log)
            self.watchdog.start()
            self.log('Watchdog started')
        else:
            self.log('Watchdog already started')

    def stop_watchdog(self):
        if self.watchdog:
            self.watchdog.stop()
            self.watchdog = None
            self.log('Watchdog stopped')
        else:
            self.log('Watchdog is not running')

    def select_path(self):
        path = filedialog.askdirectory()
        if path:
            self.watch_path = path
            self.log(f'Selected path: {path}')

    def log(self, message):
        self.messagebox.insert(END, f'{message}\n')
        self.messagebox.see(END)

if __name__ == '__main__':
    GUI()
0

New to Communities?

Join the community