On 01.10.2011 14:41, Emeka wrote:
Hello All,

I need a basic example where MVC pattern is used with Python TK.

I'm still not 100% sure if I really understand the MVC pattern. Some say the view and the model must not interact directly, some say the view must not access the controller (but the controller controls the view). Some insist on a certain interface, others just talk about a certain data/control flow, etc.

But I think a simple (and quick 'n' dirty) Tk MVC example can look like this:


#!/usr/bin/python

import Tkinter as tk

class Model(object):
    def __init__(self):
        self._data = ["foo", "bar", "baz"]
        self.controllers = []

    def data(self):
        return self._data

    def add(self, value):
        self._data.append(value)
        self.changed()

    def delete(self, index):
        del self._data[index]
        self.changed()

    def changed(self):
        for controller in self.controllers:
            controller.update()


class Controller(object):
    def __init__(self, model):
        self.model = model
        self.views = []

    def handle_insert(self, value):
        self.model.add(value)

    def handle_delete(self, index):
        self.model.delete(index)

    def get_data(self):
        return self.model.data()

    def update(self):
        for view in self.views:
            view.update()


class View(object):
    def __init__(self, master, controller):
        self.controller = controller
        self.master = master
        self.list = tk.Listbox(self.master)
        self.list.pack(expand=1, fill="both")
        self.entry = tk.Entry(self.master)
        self.entry.pack(fill="x", expand=1)
        self.entry.bind("<Return>", self.enter_handler)
        self.list.bind("<Delete>", self.delete_handler)
        self.update()

    def enter_handler(self, event):
        text = self.entry.get()
        self.controller.handle_insert(text)


    def delete_handler(self, event):
        for index in self.list.curselection():
            self.controller.handle_delete(int(index))

    def update(self):
        self.list.delete(0, "end")
        for entry in self.controller.get_data():
            self.list.insert("end", entry)


def main():
    root = tk.Tk()

    model = Model()
    controller = Controller(model)
    view = View(root, controller)

    model.controllers.append(controller)
    controller.views.append(view)

    root.mainloop()

if __name__ == '__main__':
    main()
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to