3

I want to detect mouse movement events with python-curses. I don't know how to enable these events. I tried to enable all mouse-events as follows:

stdscr = curses.initscr()
curses.mousemask(curses.REPORT_MOUSE_POSITION | curses.ALL_MOUSE_EVENTS)
while True:
    c = stdscr.getch()
    if c == curses.KEY_MOUSE:
        id, x, y, z, bstate = curses.getmouse()
        stdscr.addstr(curses.LINES-2, 0, "x: " + str(x))
        stdscr.addstr(curses.LINES-1, 0, "y: " + str(y))
        stdscr.refresh()
    if c == ord('q'):
        break
 curses.endwin()

I only get mouse-events when a mouse-button is clicked, pushed-down, etc but no mouse move events. How do I enable these events?

Rolf
  • 84
  • 6

1 Answers1

2

I got it to work by changing my $TERM env var / terminfo. On Ubuntu it worked by simply setting TERM=screen-256color, but on OSX I had to edit a terminfo file, using the instructions here:

Which $TERM to use to have both 256 colors and mouse move events in python curses?

but for me the format was different so I added the line:

XM=\E[?1003%?%p1%{1}%=%th%el%;,

To test it, I used this Python code (note screen.keypad(1) is very necessary, otherwise mouse events cause getch to return escape key codes).

import curses

screen = curses.initscr()
screen.keypad(1)
curses.curs_set(0)
curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
curses.flushinp()
curses.noecho()
screen.clear()

while True:
    key = screen.getch()
    screen.clear()
    screen.addstr(0, 0, 'key: {}'.format(key))
    if key == curses.KEY_MOUSE:
        _, x, y, _, button = curses.getmouse()
        screen.addstr(1, 0, 'x, y, button = {}, {}, {}'.format(x, y, button))
    elif key == 27:
        break

curses.endwin()
curses.flushinp()
Abram
  • 413
  • 1
  • 3
  • 13
  • 1
    If you're not getting the exact mouse position reporting behavior you want, I posted a [follow-up answer to the answer you referenced](https://stackoverflow.com/a/70735193/7915759). I included the steps to find the satisfactory `XM` string. The problem I faced using the string provided was mouse position reporting was always going - even with no mouse buttons pressed. That might be good for a "hover" feature. But I didn't implement hover in my app, and the constant reporting was wasted. I only needed a "mouse drag" feature. – Todd Jan 16 '22 at 23:57
  • 1
    Setting `curses.keypad(True)` was unnecessary on my Ubuntu 20 system. – Todd Jan 17 '22 at 00:53