[Tutor] tkinter events: <B1-Motion>

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Aug 22 21:59:53 CEST 2006


> def handler(event):
> 	if buttonpressed == 1 :
> 		/#if the mousebutton is pressed and moved, circles should 
> appear, but they do not/
> 		can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
> fill="orange")
> 	lab.config(text='buttonpressed=' + str(buttonpressed) )


The variables of functions are normally independent of each other.  That 
is, if I have a function square():

##############
def square(x):
     y = x * x
     return y
##############

and if I have a function that uses square that itself has a 'y' variable, 
I should not see interference:

##############
def test():
     y = 17
     print "square of y is", square(y)
     print "y itself is", y
##############

This black-boxing is what allows us to write and reuse functions with 
reckless abandon: their innards are meant not to interact with one 
another.  This is a feature that you usually want to have.


But for your purposes, you want some controlled form of leakage.  Use 
'global' for this purpose by declaring the shared variable at the head of 
your functions.  Compare the results above to the ones below:

#####################################
def square(x):
      global y
      y = x * x
      return y

def test():
     global y
     y = 17
     print "square of y is", square(y)
     print "y itself is", y
#####################################

There's terse reference material here about global:

     http://www.python.org/doc/ref/global.html#l2h-558

It's idiomatic programming practice to limit the use of 'global' to 
situations where it's necessary; using it in an uncontrolled way leads to 
code that's difficult to read or reason with.  There are more sophsticated 
ways to share variables between functions.  That being said, though, the 
'global' mechanism will probably be simplest for your purposes.


Good luck to you!


More information about the Tutor mailing list