how to enable mouse movement events in python-curses

只愿长相守 提交于 2020-01-15 05:13:08

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/56303971/how-to-enable-mouse-movement-events-in-python-curses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!