1

I want m_listener to start only when I press f6 

and if I clicked F7, it stopped.

f6 it again to continue. 

My issue is that when I click f7 it totally stops the listener and on_x_y_click never run again if i clicked f6 

import pynput
import easygui

from pynput import *


def on_x_y_click(x, y, button, pressed):
    print((x, y, button, pressed))

def on_release(key):
    print(key)
    if key == keyboard.Key.f6:
        m_listener.join()
    elif key == keyboard.Key.f7:
        m_listener.stop()
    elif key == keyboard.Key.esc:
        # Stop listeners
        m_listener.stop()
        return False



# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, \
        mouse.Listener(on_click=on_x_y_click) as m_listener:
    k_listener.join()
    m_listener.join()

1 Answers1

1

In the documentation, there doesn't seem to be any functionality to do this directly.

However, you can fairly easily implement this yourself by simply setting a flag and ignoring events when that flag is set:

from pynput import *

b_ignore_mouse_events = False

def on_x_y_click(x, y, button, pressed):
    if b_ignore_mouse_events:
        return

    print((x, y, button, pressed))

def on_release(key):
    global b_ignore_mouse_events

    print(key)
    if key == keyboard.Key.f6:
        b_ignore_mouse_events = False
    elif key == keyboard.Key.f7:
        b_ignore_mouse_events = True

# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, \
        mouse.Listener(on_click=on_x_y_click) as m_listener:
    k_listener.join()
    m_listener.join()

Some notes about this:

  • Using global variables is often bad in larger applications, it seems fine for this simple script though.

  • Currently, the listeners are not stopped immediately when <ESC> is pressed. Instead, you need to press a mouse button again because the mouse listener thread is waiting for the next key to be pressed and doesn't notice that it was stopped until that happens.

    I just removed that part of the code because it did not function correctly. If you need that, you can ask another question about that (after searching for a solution yourself).

asynts
  • 2,213
  • 2
  • 21
  • 35