0

So i am fairly new to python and i am trying to build a "stock-market-like" game.

If the clicks per time goes up, the price goes up and the other way around.

My first challenge now is to store the number of times I've clicked.

Till now my code looks like this:

from pynput.mouse import Listener

count = 0

def on_click(x, y, button, pressed):

 print("check")
 count += 1
 print(count)

with Listener(on_click=on_click) as listener:
listener.join()

Now when i click it prints out "check" as it should and also prints out "0", because i defined it like this before. But if i click again it doesn't count up. Sorry i only recently started programming.

Later on i want to find out how many times i clicked per timespan. But there's still a long way to go.

Thanks for any help

  • Trying saving to a database/file with the time of the click with `import datetime` and `time = datetime.datetime.utcnow` – Axisnix Sep 17 '19 at 12:09
  • Specifically, the issue you are running into is local vs global variable. Your first `count = 0` is a global scope variable, but when you tried to reassign it `count += 1` within your function, it's referring to the local variable within the function. Thus each time the function gets executed the local variable `count` is empty. – r.ook Sep 17 '19 at 12:13
  • the solution can be seen in @Roca's link. Put `global count` in your on_click funktion – R. Jüntgen Sep 17 '19 at 12:14
  • Thanks you helped me so much. Now it works. Now it actually counts 2. Once when in press the mouse and once when I release it again. – tester123 Sep 17 '19 at 12:18

2 Answers2

0

try with global variable

from pynput.mouse import Listener

count = 0

def on_click(x, y, button, pressed):
    print("check")
    global count 
    count += 1
    print(count)

with Listener(on_click=on_click) as listener:
    listener.join()
Kevno
  • 53
  • 5
0

In addition to my comment of using local vs global, depending on your usage, you might also consider using an OOP approach:

class Mouse:
    def __init__(self):
        self.count = 0
    def on_click(self, x, y, button, pressed):
        print('check')
        self.count += 1
        print(self.count)

m = Mouse()
with Listener(on_click=m.on_click) as listener:
    listener.join()

This way, if you have different mouse events you want to keep track of, you can create separate instances of Mouse() so it's much easier to keep the count separate than using one global variable.

r.ook
  • 13,466
  • 2
  • 22
  • 39