如何在python-curses中启用鼠标移动事件

时间:2019-05-25 10:30:12

标签: python python-3.x python-curses

我想用python-curses检测鼠标移动事件。我不知道如何启用这些事件。我尝试启用所有鼠标事件,如下所示:

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

我仅在单击,按下鼠标按钮等情况下获得鼠标事件,但没有鼠标移动事件。如何启用这些事件?

1 个答案:

答案 0 :(得分:0)

我通过更改$ TERM env var / terminfo使它起作用。在Ubuntu上,只需设置TERM=screen-256color就可以了,但是在OSX上,我必须按照以下说明编辑terminfo文件:

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

但是对我来说格式是不同的,所以我添加了一行:

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

为了测试它,我使用了以下Python代码(请注意screen.keypad(1)是非常必要的,否则鼠标事件会导致getch返回转义键代码)。

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