The global local dipole

Using tkinter I wanted to make something happen but only if the mouse moves from one square to the next. In order to do so, I wanted to have the square coordinates the mouse was clicked and compare it with the one it is now. The prevPos variable serves this purpose. It has a global initialization (line 1) and both functions clicked and motion need to access it. So I wrote the following code:

prevPos = (0,0)
def clicked(event):
  i = event.y//LD
  j = event.x//LD
  prevPos = (event.y//LD,event.x//LD)
  #do something
def motion(event):
  i = event.y//LD
  j = event.x//LD
  if math.fabs(prevPos[0]-i) > 0 or math.fabs(prevPos[1]-j) >0:
    pass#do something

but it was not working as expected. Actually, the initialization inside the clicked function never happened.
The reason is that the assignment inside clicked created a local variable prevPos. The following code corrected the problem:

prevPos = (0,0)
def clicked(event):
  i = event.y//LD
  j = event.x//LD
  global prevPos
  prevPos = (event.y//LD,event.x//LD)
  #do something
def motion(event):
  i = event.y//LD
  j = event.x//LD
  global prevPos
  if math.fabs(prevPos[0]-i) > 0 or math.fabs(prevPos[1]-j) >0:
    pass#do something
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s