-1

I need to increase a counter variable, count, each time the mouse is pressed. I do not want to use global variables, and hence I get the following errors:

I get global name 'count' is not defined, if I use the global count line in the on_mouse_press function.

If I do not use the global line, I get the error UnboundLocalError: local variable 'count' referenced before assignment

The code is the following:

import pyglet
from pyglet import clock
import time
from pyglet.gl import *
from pyglet.window import mouse, key, Window

def dispatch_mouse_events(mywindow, count, dataclick, datatime):
    @mywindow.event
    def on_mouse_press(x, y, button, modifiers):
        #global count
        timeNow = time.clock()

        if button == mouse.LEFT:
            dataclick[count] = '-1'
            datatime[count] = timeNow

        if button == mouse.RIGHT:
            dataclick[count] = '1'
            datatime[count] = timeNow

        count += 1 # increase counter

    return count

def mymain():
    mywindow = Window(fullscreen = False)

    framerate = 60.0

    clock.set_fps_limit(framerate)

    mywindow.set_visible(True)

    # Necessary variables for the data file
    count = 0   # counter for each click
    dataclick   = [0]*15000
    datatime    = [0]*15000

    while not mywindow.has_exit:
        startMs = clock.tick() 

        mywindow.dispatch_events()
        count = dispatch_mouse_events(mywindow, count, dataclick, datatime)

        # Display frame
        mywindow.clear()           # clear window

        fps.draw()
        mywindow.flip()
    pass           

if __name__ == "__main__":
    fps = pyglet.clock.ClockDisplay(color=(1,1,1,1))
    mymain()

How can I increase a counter and avoiding using a global variable for it?

jl.da
  • 627
  • 1
  • 11
  • 30
  • Have you tried changing the name within the `dispatch...` function? I feel like python is getting confused by the line `count = count`. It can't tell the difference since the names are identical. – Al.Sal Jul 14 '14 at 14:21
  • I'll edit the question, I forgot to delete this line, with it I was trying to check if copying the value from another variable will change anything. Thanks for answering! – jl.da Jul 14 '14 at 14:25

1 Answers1

1

It sounds like you want a static variable for the function. Here is a python example...

What is the Python equivalent of static variables inside a function?

Community
  • 1
  • 1
ZJS
  • 3,991
  • 2
  • 15
  • 22