Help for Tkinter and python's programming

paul colby spam at eatshit.net
Sun Jun 2 12:38:09 EDT 2002


Russell E. Owen wrote:

<snip great response>

> The thing I usually do in this situation is to create a callable object.
> This is handy because an object can hold state, i.e. the "stuff I know
> now", yet can also have a __call__ method which allows you to call the
> object just like a function.
> 

I think your suggestion is great and has many uses. One that I find pleasing
is passing a member function to handle events. When a member function is
passed the "self" argument tags along for the ride thus giving your callback
access to all the members of the class as well as all the member data of the
instance. For example consider a box drawn on a canvas. Lets say we want to 
make the box red when clicked and blue when clicked again,

from Tkinter import *

canvas = Canvas(Tk(),bg='white')
canvas.pack(fill=BOTH,expand=1)

class Box:

  def __init__(self, canvas, x, y):
        self.canvas = canvas
        self.tag = canvas.create_rectangle(x-10,y-10,x+10,y+10,fill='blue')
        # here we set the callback
        canvas.tag_bind(self.tag,'<Button-1>',self.mouseClick)

  # here we define the callback. Note the "self" argument gets
  # handled by python's class mechanisms
  def mouseClick(self,event):
        color = self.canvas.itemcget(self.tag,'fill')
        if color == 'blue':
          self.canvas.itemconfigure(self.tag,fill='red')
        else:
          self.canvas.itemconfigure(self.tag,fill='blue')

b1 = Box(canvas,30,30)
b2 = Box(canvas,50,100)


Regards
Paul Colby



More information about the Python-list mailing list