tkinter canvas mvc

James Stroud jstroud at mbi.ucla.edu
Fri Apr 6 12:22:42 CEST 2007


Gigs_ wrote:
> Hi all!
> 
> I have just finished my tkinter text editor, learning tkinter purpose.
> 
> Now I want to learn canvas so I want to make my paint program, I think 
> that this will be the best to do over model-view-controler pattern which 
> I need to learn also.
> 
> Is there any good tutorial for mvc in python or can someone explain me 
> little bit about mvc?
> or maybe some code snippet in mvc, that will be nice.
> 
> Thanks in advance!
> 

MVC in a nutshell.

1. You need a model.
2. You need a view.
3. You need a controller.

Lets see how they work together, using dictionary-like interfaces:


class Model(dict): pass

class View(object):
   def __init__(self, controller, keys):
     self.controller = controller
     self.widgets = {}
     for k in keys:
       w = make_a_widget(k)
       def _callback(w=w):
         v = w.get_value()
         self.controller[k] = v
       w.bind(SomeEvent, _callback)
       self.widgets[k] = w
     self.controller.register_view(self)
   def __setitem__(self, k, v):
     self.widgets[k].set_value(v)
   def __contains__(self, k):
     return k in self.widgets

class Controller(object):
   def __init__(self, model):
     self.views = []
     self.data = model
   def register_view(self, aview):
     self.views.append(aview)
   def __setitem__(self, k, v):
     self.data[k] = v
     for aview in self.views:
       if k in aview:
         aview[k] = v
   def __getitem__(self, k):
     return self.data[k]
   def update(self, adict):
     self.data.update(adict)
     for k,v in adict.items():
       for aview in self.views:
         if k in aview:
           aview[k] = v



James



More information about the Python-list mailing list